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 |
---|---|---|---|---|
test_class_2_find_the_torsional_angle.py
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle
import io
import math
import sys
import unittest
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def subtract(self, other):
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vector(x, y, z)
def dot_product(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross_product(self, other):
zero = Vector(0, 0, 0)
x = self.y * other.z - self.z * other.y
y = self.z * other.x - self.x * other.z
z = self.x * other.y - self.y * other.x
return zero.subtract(Vector(x, y, z))
def value(self):
xx = math.pow(self.x, 2)
yy = math.pow(self.y, 2)
zz = math.pow(self.z, 2)
return math.sqrt(xx + yy + zz)
def torsional_angle(a, b, c, d):
ab = a.subtract(b)
bc = b.subtract(c)
cd = c.subtract(d)
x = ab.cross_product(bc)
y = bc.cross_product(cd)
cosine = x.dot_product(y) / (x.value() * y.value())
return math.degrees(math.acos(cosine))
def main():
a = Vector(*tuple(map(float, input().strip().split())))
b = Vector(*tuple(map(float, input().strip().split())))
c = Vector(*tuple(map(float, input().strip().split())))
d = Vector(*tuple(map(float, input().strip().split())))
print('%.2f' % torsional_angle(a, b, c, d))
if __name__ == '__main__': # pragma: no cover
main()
class TestCode(unittest.TestCase):
def generalized_test(self, which):
sys.stdin = open(__file__.replace('.py', f'.{which}.in'), 'r')
sys.stdout = io.StringIO()
expected = open(__file__.replace('.py', f'.{which}.out'), 'r')
main()
self.assertEqual(sys.stdout.getvalue(), expected.read())
for handle in [sys.stdin, sys.stdout, expected]:
|
def test_0(self):
self.generalized_test('0')
|
handle.close()
|
conditional_block
|
test_class_2_find_the_torsional_angle.py
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle
import io
import math
import sys
import unittest
class Vector:
def
|
(self, x, y, z):
self.x = x
self.y = y
self.z = z
def subtract(self, other):
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vector(x, y, z)
def dot_product(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross_product(self, other):
zero = Vector(0, 0, 0)
x = self.y * other.z - self.z * other.y
y = self.z * other.x - self.x * other.z
z = self.x * other.y - self.y * other.x
return zero.subtract(Vector(x, y, z))
def value(self):
xx = math.pow(self.x, 2)
yy = math.pow(self.y, 2)
zz = math.pow(self.z, 2)
return math.sqrt(xx + yy + zz)
def torsional_angle(a, b, c, d):
ab = a.subtract(b)
bc = b.subtract(c)
cd = c.subtract(d)
x = ab.cross_product(bc)
y = bc.cross_product(cd)
cosine = x.dot_product(y) / (x.value() * y.value())
return math.degrees(math.acos(cosine))
def main():
a = Vector(*tuple(map(float, input().strip().split())))
b = Vector(*tuple(map(float, input().strip().split())))
c = Vector(*tuple(map(float, input().strip().split())))
d = Vector(*tuple(map(float, input().strip().split())))
print('%.2f' % torsional_angle(a, b, c, d))
if __name__ == '__main__': # pragma: no cover
main()
class TestCode(unittest.TestCase):
def generalized_test(self, which):
sys.stdin = open(__file__.replace('.py', f'.{which}.in'), 'r')
sys.stdout = io.StringIO()
expected = open(__file__.replace('.py', f'.{which}.out'), 'r')
main()
self.assertEqual(sys.stdout.getvalue(), expected.read())
for handle in [sys.stdin, sys.stdout, expected]:
handle.close()
def test_0(self):
self.generalized_test('0')
|
__init__
|
identifier_name
|
chunks.rs
|
use std::sync::{Arc, Mutex};
use simple_parallel;
use state::LSystem;
use super::{LProcessor, SimpleProcessor};
/// Parallel processor dividing a state into chunks to be individually iterated
/// within a pool of threads.
pub struct
|
{
/// The number of symbols per full chunk.
chunk_size: usize,
/// The thread pool.
pool: simple_parallel::Pool,
}
impl ChunksProcessor {
/// Try and create a new 'ChunksProcessor' instance with the given parameters.
/// Typical values:
/// - max_tasks : number of CPU logical cores
/// - chunks_size : between 100_000 and 1_000_000 symbols per chunk
pub fn new(max_tasks: usize, chunks_size: usize) -> Result<ChunksProcessor, String> {
if max_tasks == 0 {
Err(format!("ChunksProcessor::new : invalid maximum tasks number ({})",
max_tasks))
} else if chunks_size == 0 {
Err(format!("ChunksProcessor::new : invalid chunks size ({})",
chunks_size))
} else {
Ok(ChunksProcessor {
chunk_size: chunks_size,
pool: simple_parallel::Pool::new(max_tasks),
})
}
}
}
impl<S> LProcessor<S> for ChunksProcessor
where S: Clone + Eq + Send + Sync
{
// TODO : better error handling...
fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> {
// Set-up
let mut vec: Vec<Vec<S>> = Vec::new();
let state_len = lsystem.state().len();
if state_len == 0 {
return Err(format!("cannot iterate an empty state"));
}
let rem = state_len % self.chunk_size;
let chunks_number = state_len / self.chunk_size +
match rem {
0 => 0,
_ => 1,
};
for _ in 0..chunks_number {
vec.push(Vec::new());
}
let sub_states = Arc::new(Mutex::new(vec));
// Chunks processing
let rules = lsystem.rules().clone();
let errors = Mutex::new(String::new());
let chunks_iter = lsystem.state().chunks(self.chunk_size);
self.pool
.for_(chunks_iter.enumerate(), |(n, chunk)| {
let result: Vec<S> = match SimpleProcessor::iterate_slice(chunk, &rules) {
Ok(v) => v,
Err(why) => {
let mut error_lock = errors.lock().unwrap();
*error_lock = format!("{}\n{}", *error_lock, why);
Vec::new()
}
};
let mut chunk_data = sub_states.lock().unwrap();
chunk_data[n] = result;
});
// Error handling
let error_lock = errors.lock().unwrap();
if !error_lock.is_empty() {
return Err(format!("ChunksProcessor : iteration error(s):\n{}", *error_lock));
}
// Final assembling
let mut new_state_size = 0usize;
let mut new_state: Vec<S> = Vec::new();
let data = sub_states.lock().unwrap();
for n in 0..chunks_number {
let chunk_iterated = &data[n];
new_state_size = match new_state_size.checked_add(chunk_iterated.len()) {
Some(v) => v,
None => {
return Err(format!("ChunksProcessor::iterate : usize overflow, state too big \
for for Vec"))
}
};
new_state.extend(chunk_iterated.iter().cloned());
}
Ok(LSystem::<S>::new(new_state, rules, Some(lsystem.iteration() + 1)))
}
}
#[cfg(test)]
mod test {
use rules::HashMapRules;
use state::{LSystem, new_rules_value};
use interpret::TurtleCommand;
use process::{LProcessor, ChunksProcessor};
#[test]
fn chunks_processing() {
let mut rules = HashMapRules::new(); // algae rules
rules.set_str('A', "AB", TurtleCommand::None);
rules.set_str('B', "A", TurtleCommand::None);
let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
2584, 4181, 6765, 10946, 17711, 28657, 46368];
let mut lsystem = LSystem::new_with_char("A", new_rules_value(rules));
let mut processor = ChunksProcessor::new(4, 10_000).ok().unwrap();
for n in 0..expected_sizes.len() {
assert_eq!(lsystem.iteration(), n as u64);
assert_eq!(lsystem.state().len(), expected_sizes[n]);
lsystem = processor.iterate(&lsystem).ok().unwrap();
}
}
}
|
ChunksProcessor
|
identifier_name
|
chunks.rs
|
use std::sync::{Arc, Mutex};
use simple_parallel;
use state::LSystem;
use super::{LProcessor, SimpleProcessor};
/// Parallel processor dividing a state into chunks to be individually iterated
/// within a pool of threads.
pub struct ChunksProcessor {
/// The number of symbols per full chunk.
chunk_size: usize,
/// The thread pool.
pool: simple_parallel::Pool,
}
impl ChunksProcessor {
/// Try and create a new 'ChunksProcessor' instance with the given parameters.
/// Typical values:
/// - max_tasks : number of CPU logical cores
/// - chunks_size : between 100_000 and 1_000_000 symbols per chunk
pub fn new(max_tasks: usize, chunks_size: usize) -> Result<ChunksProcessor, String> {
if max_tasks == 0 {
Err(format!("ChunksProcessor::new : invalid maximum tasks number ({})",
max_tasks))
} else if chunks_size == 0 {
Err(format!("ChunksProcessor::new : invalid chunks size ({})",
chunks_size))
} else {
Ok(ChunksProcessor {
chunk_size: chunks_size,
pool: simple_parallel::Pool::new(max_tasks),
})
}
|
where S: Clone + Eq + Send + Sync
{
// TODO : better error handling...
fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> {
// Set-up
let mut vec: Vec<Vec<S>> = Vec::new();
let state_len = lsystem.state().len();
if state_len == 0 {
return Err(format!("cannot iterate an empty state"));
}
let rem = state_len % self.chunk_size;
let chunks_number = state_len / self.chunk_size +
match rem {
0 => 0,
_ => 1,
};
for _ in 0..chunks_number {
vec.push(Vec::new());
}
let sub_states = Arc::new(Mutex::new(vec));
// Chunks processing
let rules = lsystem.rules().clone();
let errors = Mutex::new(String::new());
let chunks_iter = lsystem.state().chunks(self.chunk_size);
self.pool
.for_(chunks_iter.enumerate(), |(n, chunk)| {
let result: Vec<S> = match SimpleProcessor::iterate_slice(chunk, &rules) {
Ok(v) => v,
Err(why) => {
let mut error_lock = errors.lock().unwrap();
*error_lock = format!("{}\n{}", *error_lock, why);
Vec::new()
}
};
let mut chunk_data = sub_states.lock().unwrap();
chunk_data[n] = result;
});
// Error handling
let error_lock = errors.lock().unwrap();
if !error_lock.is_empty() {
return Err(format!("ChunksProcessor : iteration error(s):\n{}", *error_lock));
}
// Final assembling
let mut new_state_size = 0usize;
let mut new_state: Vec<S> = Vec::new();
let data = sub_states.lock().unwrap();
for n in 0..chunks_number {
let chunk_iterated = &data[n];
new_state_size = match new_state_size.checked_add(chunk_iterated.len()) {
Some(v) => v,
None => {
return Err(format!("ChunksProcessor::iterate : usize overflow, state too big \
for for Vec"))
}
};
new_state.extend(chunk_iterated.iter().cloned());
}
Ok(LSystem::<S>::new(new_state, rules, Some(lsystem.iteration() + 1)))
}
}
#[cfg(test)]
mod test {
use rules::HashMapRules;
use state::{LSystem, new_rules_value};
use interpret::TurtleCommand;
use process::{LProcessor, ChunksProcessor};
#[test]
fn chunks_processing() {
let mut rules = HashMapRules::new(); // algae rules
rules.set_str('A', "AB", TurtleCommand::None);
rules.set_str('B', "A", TurtleCommand::None);
let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
2584, 4181, 6765, 10946, 17711, 28657, 46368];
let mut lsystem = LSystem::new_with_char("A", new_rules_value(rules));
let mut processor = ChunksProcessor::new(4, 10_000).ok().unwrap();
for n in 0..expected_sizes.len() {
assert_eq!(lsystem.iteration(), n as u64);
assert_eq!(lsystem.state().len(), expected_sizes[n]);
lsystem = processor.iterate(&lsystem).ok().unwrap();
}
}
}
|
}
}
impl<S> LProcessor<S> for ChunksProcessor
|
random_line_split
|
chunks.rs
|
use std::sync::{Arc, Mutex};
use simple_parallel;
use state::LSystem;
use super::{LProcessor, SimpleProcessor};
/// Parallel processor dividing a state into chunks to be individually iterated
/// within a pool of threads.
pub struct ChunksProcessor {
/// The number of symbols per full chunk.
chunk_size: usize,
/// The thread pool.
pool: simple_parallel::Pool,
}
impl ChunksProcessor {
/// Try and create a new 'ChunksProcessor' instance with the given parameters.
/// Typical values:
/// - max_tasks : number of CPU logical cores
/// - chunks_size : between 100_000 and 1_000_000 symbols per chunk
pub fn new(max_tasks: usize, chunks_size: usize) -> Result<ChunksProcessor, String> {
if max_tasks == 0 {
Err(format!("ChunksProcessor::new : invalid maximum tasks number ({})",
max_tasks))
} else if chunks_size == 0 {
Err(format!("ChunksProcessor::new : invalid chunks size ({})",
chunks_size))
} else {
Ok(ChunksProcessor {
chunk_size: chunks_size,
pool: simple_parallel::Pool::new(max_tasks),
})
}
}
}
impl<S> LProcessor<S> for ChunksProcessor
where S: Clone + Eq + Send + Sync
{
// TODO : better error handling...
fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> {
// Set-up
let mut vec: Vec<Vec<S>> = Vec::new();
let state_len = lsystem.state().len();
if state_len == 0 {
return Err(format!("cannot iterate an empty state"));
}
let rem = state_len % self.chunk_size;
let chunks_number = state_len / self.chunk_size +
match rem {
0 => 0,
_ => 1,
};
for _ in 0..chunks_number {
vec.push(Vec::new());
}
let sub_states = Arc::new(Mutex::new(vec));
// Chunks processing
let rules = lsystem.rules().clone();
let errors = Mutex::new(String::new());
let chunks_iter = lsystem.state().chunks(self.chunk_size);
self.pool
.for_(chunks_iter.enumerate(), |(n, chunk)| {
let result: Vec<S> = match SimpleProcessor::iterate_slice(chunk, &rules) {
Ok(v) => v,
Err(why) => {
let mut error_lock = errors.lock().unwrap();
*error_lock = format!("{}\n{}", *error_lock, why);
Vec::new()
}
};
let mut chunk_data = sub_states.lock().unwrap();
chunk_data[n] = result;
});
// Error handling
let error_lock = errors.lock().unwrap();
if !error_lock.is_empty() {
return Err(format!("ChunksProcessor : iteration error(s):\n{}", *error_lock));
}
// Final assembling
let mut new_state_size = 0usize;
let mut new_state: Vec<S> = Vec::new();
let data = sub_states.lock().unwrap();
for n in 0..chunks_number {
let chunk_iterated = &data[n];
new_state_size = match new_state_size.checked_add(chunk_iterated.len()) {
Some(v) => v,
None => {
return Err(format!("ChunksProcessor::iterate : usize overflow, state too big \
for for Vec"))
}
};
new_state.extend(chunk_iterated.iter().cloned());
}
Ok(LSystem::<S>::new(new_state, rules, Some(lsystem.iteration() + 1)))
}
}
#[cfg(test)]
mod test {
use rules::HashMapRules;
use state::{LSystem, new_rules_value};
use interpret::TurtleCommand;
use process::{LProcessor, ChunksProcessor};
#[test]
fn chunks_processing()
|
}
|
{
let mut rules = HashMapRules::new(); // algae rules
rules.set_str('A', "AB", TurtleCommand::None);
rules.set_str('B', "A", TurtleCommand::None);
let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
2584, 4181, 6765, 10946, 17711, 28657, 46368];
let mut lsystem = LSystem::new_with_char("A", new_rules_value(rules));
let mut processor = ChunksProcessor::new(4, 10_000).ok().unwrap();
for n in 0..expected_sizes.len() {
assert_eq!(lsystem.iteration(), n as u64);
assert_eq!(lsystem.state().len(), expected_sizes[n]);
lsystem = processor.iterate(&lsystem).ok().unwrap();
}
}
|
identifier_body
|
__init__.py
|
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import os
import sys
import mock
import time
import random
import shutil
import contextlib
import tempfile
import binascii
import platform
import select
import datetime
from io import BytesIO
from subprocess import Popen, PIPE
from dateutil.tz import tzlocal
import unittest
from nose.tools import assert_equal
import botocore.loaders
import botocore.session
from botocore.awsrequest import AWSResponse
from botocore.compat import (
parse_qs, six, urlparse, HAS_CRT
)
from botocore import utils
from botocore import credentials
from botocore.stub import Stubber
_LOADER = botocore.loaders.Loader()
def skip_unless_has_memory_collection(cls):
"""Class decorator to skip tests that require memory collection.
Any test that uses memory collection (such as the resource leak tests)
can decorate their class with skip_unless_has_memory_collection to
indicate that if the platform does not support memory collection
the tests should be skipped.
"""
if platform.system() not in ['Darwin', 'Linux']:
return unittest.skip('Memory tests only supported on mac/linux.')(cls)
return cls
def skip_if_windows(reason):
"""Decorator to skip tests that should not be run on windows.
Example usage:
@skip_if_windows("Not valid")
def test_some_non_windows_stuff(self):
self.assertEqual(...)
"""
def decorator(func):
return unittest.skipIf(
platform.system() not in ['Darwin', 'Linux'], reason)(func)
return decorator
def requires_crt(reason=None):
if reason is None:
reason = "Test requires awscrt to be installed"
def decorator(func):
return unittest.skipIf(not HAS_CRT, reason)(func)
return decorator
def random_chars(num_chars):
"""Returns random hex characters.
Useful for creating resources with random names.
"""
return binascii.hexlify(os.urandom(int(num_chars / 2))).decode('ascii')
def create_session(**kwargs):
# Create a Session object. By default,
# the _LOADER object is used as the loader
# so that we reused the same models across tests.
session = botocore.session.Session(**kwargs)
session.register_component('data_loader', _LOADER)
session.set_config_variable('credentials_file', 'noexist/foo/botocore')
return session
@contextlib.contextmanager
def temporary_file(mode):
"""This is a cross platform temporary file creation.
tempfile.NamedTemporary file on windows creates a secure temp file
that can't be read by other processes and can't be opened a second time.
For tests, we generally *want* them to be read multiple times.
The test fixture writes the temp file contents, the test reads the
temp file.
"""
temporary_directory = tempfile.mkdtemp()
basename = 'tmpfile-%s-%s' % (int(time.time()), random.randint(1, 1000))
full_filename = os.path.join(temporary_directory, basename)
open(full_filename, 'w').close()
try:
with open(full_filename, mode) as f:
yield f
finally:
shutil.rmtree(temporary_directory)
class BaseEnvVar(unittest.TestCase):
def setUp(self):
# Automatically patches out os.environ for you
# and gives you a self.environ attribute that simulates
# the environment. Also will automatically restore state
# for you in tearDown()
self.environ = {}
self.environ_patch = mock.patch('os.environ', self.environ)
self.environ_patch.start()
def tearDown(self):
self.environ_patch.stop()
class BaseSessionTest(BaseEnvVar):
"""Base class used to provide credentials.
This class can be used as a base class that want to use a real
session class but want to be completely isolated from the
external environment (including environment variables).
This class will also set credential vars so you can make fake
requests to services.
"""
def setUp(self, **environ):
super(BaseSessionTest, self).setUp()
self.environ['AWS_ACCESS_KEY_ID'] = 'access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
self.environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
self.environ.update(environ)
self.session = create_session()
self.session.config_filename = 'no-exist-foo'
@skip_unless_has_memory_collection
class BaseClientDriverTest(unittest.TestCase):
INJECT_DUMMY_CREDS = False
def setUp(self):
self.driver = ClientDriver()
env = None
if self.INJECT_DUMMY_CREDS:
env = {'AWS_ACCESS_KEY_ID': 'foo',
'AWS_SECRET_ACCESS_KEY': 'bar'}
self.driver.start(env=env)
def cmd(self, *args):
self.driver.cmd(*args)
def send_cmd(self, *args):
self.driver.send_cmd(*args)
def record_memory(self):
self.driver.record_memory()
@property
def memory_samples(self):
return self.driver.memory_samples
def tearDown(self):
self.driver.stop()
class ClientDriver(object):
CLIENT_SERVER = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'cmd-runner'
)
def __init__(self):
|
def _get_memory_with_ps(self, pid):
# It would be better to eventually switch to psutil,
# which should allow us to test on windows, but for now
# we'll just use ps and run on POSIX platforms.
command_list = ['ps', '-p', str(pid), '-o', 'rss']
p = Popen(command_list, stdout=PIPE)
stdout = p.communicate()[0]
if not p.returncode == 0:
raise RuntimeError("Could not retrieve memory")
else:
# Get the RSS from output that looks like this:
# RSS
# 4496
return int(stdout.splitlines()[1].split()[0]) * 1024
def record_memory(self):
mem = self._get_memory_with_ps(self._popen.pid)
self.memory_samples.append(mem)
def start(self, env=None):
"""Start up the command runner process."""
self._popen = Popen([sys.executable, self.CLIENT_SERVER],
stdout=PIPE, stdin=PIPE, env=env)
def stop(self):
"""Shutdown the command runner process."""
self.cmd('exit')
self._popen.wait()
def send_cmd(self, *cmd):
"""Send a command and return immediately.
This is a lower level method than cmd().
This method will instruct the cmd-runner process
to execute a command, but this method will
immediately return. You will need to use
``is_cmd_finished()`` to check that the command
is finished.
This method is useful if you want to record attributes
about the process while an operation is occurring. For
example, if you want to instruct the cmd-runner process
to upload a 1GB file to S3 and you'd like to record
the memory during the upload process, you can use
send_cmd() instead of cmd().
"""
cmd_str = ' '.join(cmd) + '\n'
cmd_bytes = cmd_str.encode('utf-8')
self._popen.stdin.write(cmd_bytes)
self._popen.stdin.flush()
def is_cmd_finished(self):
rlist = [self._popen.stdout.fileno()]
result = select.select(rlist, [], [], 0.01)
if result[0]:
return True
return False
def cmd(self, *cmd):
"""Send a command and block until it finishes.
This method will send a command to the cmd-runner process
to run. It will block until the cmd-runner process is
finished executing the command and sends back a status
response.
"""
self.send_cmd(*cmd)
result = self._popen.stdout.readline().strip()
if result != b'OK':
raise RuntimeError(
"Error from command '%s': %s" % (cmd, result))
# This is added to this file because it's used in both
# the functional and unit tests for cred refresh.
class IntegerRefresher(credentials.RefreshableCredentials):
"""Refreshable credentials to help with testing.
This class makes testing refreshable credentials easier.
It has the following functionality:
* A counter, self.refresh_counter, to indicate how many
times refresh was called.
* A way to specify how many seconds to make credentials
valid.
* Configurable advisory/mandatory refresh.
* An easy way to check consistency. Each time creds are
refreshed, all the cred values are set to the next
incrementing integer. Frozen credentials should always
have this value.
"""
_advisory_refresh_timeout = 2
_mandatory_refresh_timeout = 1
_credentials_expire = 3
def __init__(self, creds_last_for=_credentials_expire,
advisory_refresh=_advisory_refresh_timeout,
mandatory_refresh=_mandatory_refresh_timeout,
refresh_function=None):
expires_in = (
self._current_datetime() +
datetime.timedelta(seconds=creds_last_for))
if refresh_function is None:
refresh_function = self._do_refresh
super(IntegerRefresher, self).__init__(
'0', '0', '0', expires_in,
refresh_function, 'INTREFRESH')
self.creds_last_for = creds_last_for
self.refresh_counter = 0
self._advisory_refresh_timeout = advisory_refresh
self._mandatory_refresh_timeout = mandatory_refresh
def _do_refresh(self):
self.refresh_counter += 1
current = int(self._access_key)
next_id = str(current + 1)
return {
'access_key': next_id,
'secret_key': next_id,
'token': next_id,
'expiry_time': self._seconds_later(self.creds_last_for),
}
def _seconds_later(self, num_seconds):
# We need to guarantee at *least* num_seconds.
# Because this doesn't handle subsecond precision
# we'll round up to the next second.
num_seconds += 1
t = self._current_datetime() + datetime.timedelta(seconds=num_seconds)
return self._to_timestamp(t)
def _to_timestamp(self, datetime_obj):
obj = utils.parse_to_aware_datetime(datetime_obj)
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
def _current_timestamp(self):
return self._to_timestamp(self._current_datetime())
def _current_datetime(self):
return datetime.datetime.now(tzlocal())
def _urlparse(url):
if isinstance(url, six.binary_type):
# Not really necessary, but it helps to reduce noise on Python 2.x
url = url.decode('utf8')
return urlparse(url)
def assert_url_equal(url1, url2):
parts1 = _urlparse(url1)
parts2 = _urlparse(url2)
# Because the query string ordering isn't relevant, we have to parse
# every single part manually and then handle the query string.
assert_equal(parts1.scheme, parts2.scheme)
assert_equal(parts1.netloc, parts2.netloc)
assert_equal(parts1.path, parts2.path)
assert_equal(parts1.params, parts2.params)
assert_equal(parts1.fragment, parts2.fragment)
assert_equal(parts1.username, parts2.username)
assert_equal(parts1.password, parts2.password)
assert_equal(parts1.hostname, parts2.hostname)
assert_equal(parts1.port, parts2.port)
assert_equal(parse_qs(parts1.query), parse_qs(parts2.query))
class HTTPStubberException(Exception):
pass
class RawResponse(BytesIO):
# TODO: There's a few objects similar to this in various tests, let's
# try and consolidate to this one in a future commit.
def stream(self, **kwargs):
contents = self.read()
while contents:
yield contents
contents = self.read()
class BaseHTTPStubber(object):
def __init__(self, obj_with_event_emitter, strict=True):
self.reset()
self._strict = strict
self._obj_with_event_emitter = obj_with_event_emitter
def reset(self):
self.requests = []
self.responses = []
def add_response(self, url='https://example.com', status=200, headers=None,
body=b''):
if headers is None:
headers = {}
raw = RawResponse(body)
response = AWSResponse(url, status, headers, raw)
self.responses.append(response)
@property
def _events(self):
raise NotImplementedError('_events')
def start(self):
self._events.register('before-send', self)
def stop(self):
self._events.unregister('before-send', self)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.stop()
def __call__(self, request, **kwargs):
self.requests.append(request)
if self.responses:
response = self.responses.pop(0)
if isinstance(response, Exception):
raise response
else:
return response
elif self._strict:
raise HTTPStubberException('Insufficient responses')
else:
return None
class ClientHTTPStubber(BaseHTTPStubber):
@property
def _events(self):
return self._obj_with_event_emitter.meta.events
class SessionHTTPStubber(BaseHTTPStubber):
@property
def _events(self):
return self._obj_with_event_emitter.get_component('event_emitter')
class ConsistencyWaiterException(Exception):
pass
class ConsistencyWaiter(object):
"""
A waiter class for some check to reach a consistent state.
:type min_successes: int
:param min_successes: The minimum number of successful check calls to
treat the check as stable. Default of 1 success.
:type max_attempts: int
:param min_successes: The maximum number of times to attempt calling
the check. Default of 20 attempts.
:type delay: int
:param delay: The number of seconds to delay the next API call after a
failed check call. Default of 5 seconds.
"""
def __init__(self, min_successes=1, max_attempts=20, delay=5,
delay_initial_poll=False):
self.min_successes = min_successes
self.max_attempts = max_attempts
self.delay = delay
self.delay_initial_poll = delay_initial_poll
def wait(self, check, *args, **kwargs):
"""
Wait until the check succeeds the configured number of times
:type check: callable
:param check: A callable that returns True or False to indicate
if the check succeeded or failed.
:type args: list
:param args: Any ordered arguments to be passed to the check.
:type kwargs: dict
:param kwargs: Any keyword arguments to be passed to the check.
"""
attempts = 0
successes = 0
if self.delay_initial_poll:
time.sleep(self.delay)
while attempts < self.max_attempts:
attempts += 1
if check(*args, **kwargs):
successes += 1
if successes >= self.min_successes:
return
else:
time.sleep(self.delay)
fail_msg = self._fail_message(attempts, successes)
raise ConsistencyWaiterException(fail_msg)
def _fail_message(self, attempts, successes):
format_args = (attempts, successes)
return 'Failed after %s attempts, only had %s successes' % format_args
class StubbedSession(botocore.session.Session):
def __init__(self, *args, **kwargs):
super(StubbedSession, self).__init__(*args, **kwargs)
self._cached_clients = {}
self._client_stubs = {}
def create_client(self, service_name, *args, **kwargs):
if service_name not in self._cached_clients:
client = self._create_stubbed_client(service_name, *args, **kwargs)
self._cached_clients[service_name] = client
return self._cached_clients[service_name]
def _create_stubbed_client(self, service_name, *args, **kwargs):
client = super(StubbedSession, self).create_client(
service_name, *args, **kwargs)
stubber = Stubber(client)
self._client_stubs[service_name] = stubber
return client
def stub(self, service_name, *args, **kwargs):
if service_name not in self._client_stubs:
self.create_client(service_name, *args, **kwargs)
return self._client_stubs[service_name]
def activate_stubs(self):
for stub in self._client_stubs.values():
stub.activate()
def verify_stubs(self):
for stub in self._client_stubs.values():
stub.assert_no_pending_responses()
|
self._popen = None
self.memory_samples = []
|
identifier_body
|
__init__.py
|
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import os
import sys
import mock
import time
import random
import shutil
import contextlib
import tempfile
import binascii
import platform
import select
import datetime
from io import BytesIO
from subprocess import Popen, PIPE
from dateutil.tz import tzlocal
import unittest
from nose.tools import assert_equal
import botocore.loaders
import botocore.session
from botocore.awsrequest import AWSResponse
from botocore.compat import (
parse_qs, six, urlparse, HAS_CRT
)
from botocore import utils
from botocore import credentials
from botocore.stub import Stubber
_LOADER = botocore.loaders.Loader()
def skip_unless_has_memory_collection(cls):
"""Class decorator to skip tests that require memory collection.
Any test that uses memory collection (such as the resource leak tests)
can decorate their class with skip_unless_has_memory_collection to
indicate that if the platform does not support memory collection
the tests should be skipped.
"""
if platform.system() not in ['Darwin', 'Linux']:
return unittest.skip('Memory tests only supported on mac/linux.')(cls)
return cls
def skip_if_windows(reason):
"""Decorator to skip tests that should not be run on windows.
Example usage:
@skip_if_windows("Not valid")
def test_some_non_windows_stuff(self):
self.assertEqual(...)
"""
def decorator(func):
return unittest.skipIf(
platform.system() not in ['Darwin', 'Linux'], reason)(func)
return decorator
def requires_crt(reason=None):
if reason is None:
reason = "Test requires awscrt to be installed"
def decorator(func):
return unittest.skipIf(not HAS_CRT, reason)(func)
return decorator
def random_chars(num_chars):
"""Returns random hex characters.
Useful for creating resources with random names.
"""
return binascii.hexlify(os.urandom(int(num_chars / 2))).decode('ascii')
def create_session(**kwargs):
# Create a Session object. By default,
# the _LOADER object is used as the loader
# so that we reused the same models across tests.
session = botocore.session.Session(**kwargs)
session.register_component('data_loader', _LOADER)
session.set_config_variable('credentials_file', 'noexist/foo/botocore')
return session
@contextlib.contextmanager
def temporary_file(mode):
"""This is a cross platform temporary file creation.
tempfile.NamedTemporary file on windows creates a secure temp file
that can't be read by other processes and can't be opened a second time.
For tests, we generally *want* them to be read multiple times.
The test fixture writes the temp file contents, the test reads the
temp file.
"""
temporary_directory = tempfile.mkdtemp()
basename = 'tmpfile-%s-%s' % (int(time.time()), random.randint(1, 1000))
full_filename = os.path.join(temporary_directory, basename)
open(full_filename, 'w').close()
try:
with open(full_filename, mode) as f:
yield f
finally:
shutil.rmtree(temporary_directory)
class BaseEnvVar(unittest.TestCase):
def setUp(self):
# Automatically patches out os.environ for you
# and gives you a self.environ attribute that simulates
# the environment. Also will automatically restore state
# for you in tearDown()
self.environ = {}
self.environ_patch = mock.patch('os.environ', self.environ)
self.environ_patch.start()
def tearDown(self):
self.environ_patch.stop()
class BaseSessionTest(BaseEnvVar):
"""Base class used to provide credentials.
This class can be used as a base class that want to use a real
session class but want to be completely isolated from the
external environment (including environment variables).
This class will also set credential vars so you can make fake
requests to services.
|
self.environ['AWS_ACCESS_KEY_ID'] = 'access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
self.environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
self.environ.update(environ)
self.session = create_session()
self.session.config_filename = 'no-exist-foo'
@skip_unless_has_memory_collection
class BaseClientDriverTest(unittest.TestCase):
INJECT_DUMMY_CREDS = False
def setUp(self):
self.driver = ClientDriver()
env = None
if self.INJECT_DUMMY_CREDS:
env = {'AWS_ACCESS_KEY_ID': 'foo',
'AWS_SECRET_ACCESS_KEY': 'bar'}
self.driver.start(env=env)
def cmd(self, *args):
self.driver.cmd(*args)
def send_cmd(self, *args):
self.driver.send_cmd(*args)
def record_memory(self):
self.driver.record_memory()
@property
def memory_samples(self):
return self.driver.memory_samples
def tearDown(self):
self.driver.stop()
class ClientDriver(object):
CLIENT_SERVER = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'cmd-runner'
)
def __init__(self):
self._popen = None
self.memory_samples = []
def _get_memory_with_ps(self, pid):
# It would be better to eventually switch to psutil,
# which should allow us to test on windows, but for now
# we'll just use ps and run on POSIX platforms.
command_list = ['ps', '-p', str(pid), '-o', 'rss']
p = Popen(command_list, stdout=PIPE)
stdout = p.communicate()[0]
if not p.returncode == 0:
raise RuntimeError("Could not retrieve memory")
else:
# Get the RSS from output that looks like this:
# RSS
# 4496
return int(stdout.splitlines()[1].split()[0]) * 1024
def record_memory(self):
mem = self._get_memory_with_ps(self._popen.pid)
self.memory_samples.append(mem)
def start(self, env=None):
"""Start up the command runner process."""
self._popen = Popen([sys.executable, self.CLIENT_SERVER],
stdout=PIPE, stdin=PIPE, env=env)
def stop(self):
"""Shutdown the command runner process."""
self.cmd('exit')
self._popen.wait()
def send_cmd(self, *cmd):
"""Send a command and return immediately.
This is a lower level method than cmd().
This method will instruct the cmd-runner process
to execute a command, but this method will
immediately return. You will need to use
``is_cmd_finished()`` to check that the command
is finished.
This method is useful if you want to record attributes
about the process while an operation is occurring. For
example, if you want to instruct the cmd-runner process
to upload a 1GB file to S3 and you'd like to record
the memory during the upload process, you can use
send_cmd() instead of cmd().
"""
cmd_str = ' '.join(cmd) + '\n'
cmd_bytes = cmd_str.encode('utf-8')
self._popen.stdin.write(cmd_bytes)
self._popen.stdin.flush()
def is_cmd_finished(self):
rlist = [self._popen.stdout.fileno()]
result = select.select(rlist, [], [], 0.01)
if result[0]:
return True
return False
def cmd(self, *cmd):
"""Send a command and block until it finishes.
This method will send a command to the cmd-runner process
to run. It will block until the cmd-runner process is
finished executing the command and sends back a status
response.
"""
self.send_cmd(*cmd)
result = self._popen.stdout.readline().strip()
if result != b'OK':
raise RuntimeError(
"Error from command '%s': %s" % (cmd, result))
# This is added to this file because it's used in both
# the functional and unit tests for cred refresh.
class IntegerRefresher(credentials.RefreshableCredentials):
"""Refreshable credentials to help with testing.
This class makes testing refreshable credentials easier.
It has the following functionality:
* A counter, self.refresh_counter, to indicate how many
times refresh was called.
* A way to specify how many seconds to make credentials
valid.
* Configurable advisory/mandatory refresh.
* An easy way to check consistency. Each time creds are
refreshed, all the cred values are set to the next
incrementing integer. Frozen credentials should always
have this value.
"""
_advisory_refresh_timeout = 2
_mandatory_refresh_timeout = 1
_credentials_expire = 3
def __init__(self, creds_last_for=_credentials_expire,
advisory_refresh=_advisory_refresh_timeout,
mandatory_refresh=_mandatory_refresh_timeout,
refresh_function=None):
expires_in = (
self._current_datetime() +
datetime.timedelta(seconds=creds_last_for))
if refresh_function is None:
refresh_function = self._do_refresh
super(IntegerRefresher, self).__init__(
'0', '0', '0', expires_in,
refresh_function, 'INTREFRESH')
self.creds_last_for = creds_last_for
self.refresh_counter = 0
self._advisory_refresh_timeout = advisory_refresh
self._mandatory_refresh_timeout = mandatory_refresh
def _do_refresh(self):
self.refresh_counter += 1
current = int(self._access_key)
next_id = str(current + 1)
return {
'access_key': next_id,
'secret_key': next_id,
'token': next_id,
'expiry_time': self._seconds_later(self.creds_last_for),
}
def _seconds_later(self, num_seconds):
# We need to guarantee at *least* num_seconds.
# Because this doesn't handle subsecond precision
# we'll round up to the next second.
num_seconds += 1
t = self._current_datetime() + datetime.timedelta(seconds=num_seconds)
return self._to_timestamp(t)
def _to_timestamp(self, datetime_obj):
obj = utils.parse_to_aware_datetime(datetime_obj)
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
def _current_timestamp(self):
return self._to_timestamp(self._current_datetime())
def _current_datetime(self):
return datetime.datetime.now(tzlocal())
def _urlparse(url):
if isinstance(url, six.binary_type):
# Not really necessary, but it helps to reduce noise on Python 2.x
url = url.decode('utf8')
return urlparse(url)
def assert_url_equal(url1, url2):
parts1 = _urlparse(url1)
parts2 = _urlparse(url2)
# Because the query string ordering isn't relevant, we have to parse
# every single part manually and then handle the query string.
assert_equal(parts1.scheme, parts2.scheme)
assert_equal(parts1.netloc, parts2.netloc)
assert_equal(parts1.path, parts2.path)
assert_equal(parts1.params, parts2.params)
assert_equal(parts1.fragment, parts2.fragment)
assert_equal(parts1.username, parts2.username)
assert_equal(parts1.password, parts2.password)
assert_equal(parts1.hostname, parts2.hostname)
assert_equal(parts1.port, parts2.port)
assert_equal(parse_qs(parts1.query), parse_qs(parts2.query))
class HTTPStubberException(Exception):
pass
class RawResponse(BytesIO):
# TODO: There's a few objects similar to this in various tests, let's
# try and consolidate to this one in a future commit.
def stream(self, **kwargs):
contents = self.read()
while contents:
yield contents
contents = self.read()
class BaseHTTPStubber(object):
def __init__(self, obj_with_event_emitter, strict=True):
self.reset()
self._strict = strict
self._obj_with_event_emitter = obj_with_event_emitter
def reset(self):
self.requests = []
self.responses = []
def add_response(self, url='https://example.com', status=200, headers=None,
body=b''):
if headers is None:
headers = {}
raw = RawResponse(body)
response = AWSResponse(url, status, headers, raw)
self.responses.append(response)
@property
def _events(self):
raise NotImplementedError('_events')
def start(self):
self._events.register('before-send', self)
def stop(self):
self._events.unregister('before-send', self)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.stop()
def __call__(self, request, **kwargs):
self.requests.append(request)
if self.responses:
response = self.responses.pop(0)
if isinstance(response, Exception):
raise response
else:
return response
elif self._strict:
raise HTTPStubberException('Insufficient responses')
else:
return None
class ClientHTTPStubber(BaseHTTPStubber):
@property
def _events(self):
return self._obj_with_event_emitter.meta.events
class SessionHTTPStubber(BaseHTTPStubber):
@property
def _events(self):
return self._obj_with_event_emitter.get_component('event_emitter')
class ConsistencyWaiterException(Exception):
pass
class ConsistencyWaiter(object):
"""
A waiter class for some check to reach a consistent state.
:type min_successes: int
:param min_successes: The minimum number of successful check calls to
treat the check as stable. Default of 1 success.
:type max_attempts: int
:param min_successes: The maximum number of times to attempt calling
the check. Default of 20 attempts.
:type delay: int
:param delay: The number of seconds to delay the next API call after a
failed check call. Default of 5 seconds.
"""
def __init__(self, min_successes=1, max_attempts=20, delay=5,
delay_initial_poll=False):
self.min_successes = min_successes
self.max_attempts = max_attempts
self.delay = delay
self.delay_initial_poll = delay_initial_poll
def wait(self, check, *args, **kwargs):
"""
Wait until the check succeeds the configured number of times
:type check: callable
:param check: A callable that returns True or False to indicate
if the check succeeded or failed.
:type args: list
:param args: Any ordered arguments to be passed to the check.
:type kwargs: dict
:param kwargs: Any keyword arguments to be passed to the check.
"""
attempts = 0
successes = 0
if self.delay_initial_poll:
time.sleep(self.delay)
while attempts < self.max_attempts:
attempts += 1
if check(*args, **kwargs):
successes += 1
if successes >= self.min_successes:
return
else:
time.sleep(self.delay)
fail_msg = self._fail_message(attempts, successes)
raise ConsistencyWaiterException(fail_msg)
def _fail_message(self, attempts, successes):
format_args = (attempts, successes)
return 'Failed after %s attempts, only had %s successes' % format_args
class StubbedSession(botocore.session.Session):
def __init__(self, *args, **kwargs):
super(StubbedSession, self).__init__(*args, **kwargs)
self._cached_clients = {}
self._client_stubs = {}
def create_client(self, service_name, *args, **kwargs):
if service_name not in self._cached_clients:
client = self._create_stubbed_client(service_name, *args, **kwargs)
self._cached_clients[service_name] = client
return self._cached_clients[service_name]
def _create_stubbed_client(self, service_name, *args, **kwargs):
client = super(StubbedSession, self).create_client(
service_name, *args, **kwargs)
stubber = Stubber(client)
self._client_stubs[service_name] = stubber
return client
def stub(self, service_name, *args, **kwargs):
if service_name not in self._client_stubs:
self.create_client(service_name, *args, **kwargs)
return self._client_stubs[service_name]
def activate_stubs(self):
for stub in self._client_stubs.values():
stub.activate()
def verify_stubs(self):
for stub in self._client_stubs.values():
stub.assert_no_pending_responses()
|
"""
def setUp(self, **environ):
super(BaseSessionTest, self).setUp()
|
random_line_split
|
__init__.py
|
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import os
import sys
import mock
import time
import random
import shutil
import contextlib
import tempfile
import binascii
import platform
import select
import datetime
from io import BytesIO
from subprocess import Popen, PIPE
from dateutil.tz import tzlocal
import unittest
from nose.tools import assert_equal
import botocore.loaders
import botocore.session
from botocore.awsrequest import AWSResponse
from botocore.compat import (
parse_qs, six, urlparse, HAS_CRT
)
from botocore import utils
from botocore import credentials
from botocore.stub import Stubber
_LOADER = botocore.loaders.Loader()
def skip_unless_has_memory_collection(cls):
"""Class decorator to skip tests that require memory collection.
Any test that uses memory collection (such as the resource leak tests)
can decorate their class with skip_unless_has_memory_collection to
indicate that if the platform does not support memory collection
the tests should be skipped.
"""
if platform.system() not in ['Darwin', 'Linux']:
return unittest.skip('Memory tests only supported on mac/linux.')(cls)
return cls
def skip_if_windows(reason):
"""Decorator to skip tests that should not be run on windows.
Example usage:
@skip_if_windows("Not valid")
def test_some_non_windows_stuff(self):
self.assertEqual(...)
"""
def decorator(func):
return unittest.skipIf(
platform.system() not in ['Darwin', 'Linux'], reason)(func)
return decorator
def requires_crt(reason=None):
if reason is None:
reason = "Test requires awscrt to be installed"
def decorator(func):
return unittest.skipIf(not HAS_CRT, reason)(func)
return decorator
def random_chars(num_chars):
"""Returns random hex characters.
Useful for creating resources with random names.
"""
return binascii.hexlify(os.urandom(int(num_chars / 2))).decode('ascii')
def create_session(**kwargs):
# Create a Session object. By default,
# the _LOADER object is used as the loader
# so that we reused the same models across tests.
session = botocore.session.Session(**kwargs)
session.register_component('data_loader', _LOADER)
session.set_config_variable('credentials_file', 'noexist/foo/botocore')
return session
@contextlib.contextmanager
def temporary_file(mode):
"""This is a cross platform temporary file creation.
tempfile.NamedTemporary file on windows creates a secure temp file
that can't be read by other processes and can't be opened a second time.
For tests, we generally *want* them to be read multiple times.
The test fixture writes the temp file contents, the test reads the
temp file.
"""
temporary_directory = tempfile.mkdtemp()
basename = 'tmpfile-%s-%s' % (int(time.time()), random.randint(1, 1000))
full_filename = os.path.join(temporary_directory, basename)
open(full_filename, 'w').close()
try:
with open(full_filename, mode) as f:
yield f
finally:
shutil.rmtree(temporary_directory)
class BaseEnvVar(unittest.TestCase):
def setUp(self):
# Automatically patches out os.environ for you
# and gives you a self.environ attribute that simulates
# the environment. Also will automatically restore state
# for you in tearDown()
self.environ = {}
self.environ_patch = mock.patch('os.environ', self.environ)
self.environ_patch.start()
def tearDown(self):
self.environ_patch.stop()
class BaseSessionTest(BaseEnvVar):
"""Base class used to provide credentials.
This class can be used as a base class that want to use a real
session class but want to be completely isolated from the
external environment (including environment variables).
This class will also set credential vars so you can make fake
requests to services.
"""
def setUp(self, **environ):
super(BaseSessionTest, self).setUp()
self.environ['AWS_ACCESS_KEY_ID'] = 'access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
self.environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
self.environ.update(environ)
self.session = create_session()
self.session.config_filename = 'no-exist-foo'
@skip_unless_has_memory_collection
class BaseClientDriverTest(unittest.TestCase):
INJECT_DUMMY_CREDS = False
def setUp(self):
self.driver = ClientDriver()
env = None
if self.INJECT_DUMMY_CREDS:
env = {'AWS_ACCESS_KEY_ID': 'foo',
'AWS_SECRET_ACCESS_KEY': 'bar'}
self.driver.start(env=env)
def cmd(self, *args):
self.driver.cmd(*args)
def send_cmd(self, *args):
self.driver.send_cmd(*args)
def record_memory(self):
self.driver.record_memory()
@property
def memory_samples(self):
return self.driver.memory_samples
def tearDown(self):
self.driver.stop()
class ClientDriver(object):
CLIENT_SERVER = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'cmd-runner'
)
def __init__(self):
self._popen = None
self.memory_samples = []
def _get_memory_with_ps(self, pid):
# It would be better to eventually switch to psutil,
# which should allow us to test on windows, but for now
# we'll just use ps and run on POSIX platforms.
command_list = ['ps', '-p', str(pid), '-o', 'rss']
p = Popen(command_list, stdout=PIPE)
stdout = p.communicate()[0]
if not p.returncode == 0:
raise RuntimeError("Could not retrieve memory")
else:
# Get the RSS from output that looks like this:
# RSS
# 4496
return int(stdout.splitlines()[1].split()[0]) * 1024
def record_memory(self):
mem = self._get_memory_with_ps(self._popen.pid)
self.memory_samples.append(mem)
def start(self, env=None):
"""Start up the command runner process."""
self._popen = Popen([sys.executable, self.CLIENT_SERVER],
stdout=PIPE, stdin=PIPE, env=env)
def stop(self):
"""Shutdown the command runner process."""
self.cmd('exit')
self._popen.wait()
def send_cmd(self, *cmd):
"""Send a command and return immediately.
This is a lower level method than cmd().
This method will instruct the cmd-runner process
to execute a command, but this method will
immediately return. You will need to use
``is_cmd_finished()`` to check that the command
is finished.
This method is useful if you want to record attributes
about the process while an operation is occurring. For
example, if you want to instruct the cmd-runner process
to upload a 1GB file to S3 and you'd like to record
the memory during the upload process, you can use
send_cmd() instead of cmd().
"""
cmd_str = ' '.join(cmd) + '\n'
cmd_bytes = cmd_str.encode('utf-8')
self._popen.stdin.write(cmd_bytes)
self._popen.stdin.flush()
def
|
(self):
rlist = [self._popen.stdout.fileno()]
result = select.select(rlist, [], [], 0.01)
if result[0]:
return True
return False
def cmd(self, *cmd):
"""Send a command and block until it finishes.
This method will send a command to the cmd-runner process
to run. It will block until the cmd-runner process is
finished executing the command and sends back a status
response.
"""
self.send_cmd(*cmd)
result = self._popen.stdout.readline().strip()
if result != b'OK':
raise RuntimeError(
"Error from command '%s': %s" % (cmd, result))
# This is added to this file because it's used in both
# the functional and unit tests for cred refresh.
class IntegerRefresher(credentials.RefreshableCredentials):
"""Refreshable credentials to help with testing.
This class makes testing refreshable credentials easier.
It has the following functionality:
* A counter, self.refresh_counter, to indicate how many
times refresh was called.
* A way to specify how many seconds to make credentials
valid.
* Configurable advisory/mandatory refresh.
* An easy way to check consistency. Each time creds are
refreshed, all the cred values are set to the next
incrementing integer. Frozen credentials should always
have this value.
"""
_advisory_refresh_timeout = 2
_mandatory_refresh_timeout = 1
_credentials_expire = 3
def __init__(self, creds_last_for=_credentials_expire,
advisory_refresh=_advisory_refresh_timeout,
mandatory_refresh=_mandatory_refresh_timeout,
refresh_function=None):
expires_in = (
self._current_datetime() +
datetime.timedelta(seconds=creds_last_for))
if refresh_function is None:
refresh_function = self._do_refresh
super(IntegerRefresher, self).__init__(
'0', '0', '0', expires_in,
refresh_function, 'INTREFRESH')
self.creds_last_for = creds_last_for
self.refresh_counter = 0
self._advisory_refresh_timeout = advisory_refresh
self._mandatory_refresh_timeout = mandatory_refresh
def _do_refresh(self):
self.refresh_counter += 1
current = int(self._access_key)
next_id = str(current + 1)
return {
'access_key': next_id,
'secret_key': next_id,
'token': next_id,
'expiry_time': self._seconds_later(self.creds_last_for),
}
def _seconds_later(self, num_seconds):
# We need to guarantee at *least* num_seconds.
# Because this doesn't handle subsecond precision
# we'll round up to the next second.
num_seconds += 1
t = self._current_datetime() + datetime.timedelta(seconds=num_seconds)
return self._to_timestamp(t)
def _to_timestamp(self, datetime_obj):
obj = utils.parse_to_aware_datetime(datetime_obj)
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
def _current_timestamp(self):
return self._to_timestamp(self._current_datetime())
def _current_datetime(self):
return datetime.datetime.now(tzlocal())
def _urlparse(url):
if isinstance(url, six.binary_type):
# Not really necessary, but it helps to reduce noise on Python 2.x
url = url.decode('utf8')
return urlparse(url)
def assert_url_equal(url1, url2):
parts1 = _urlparse(url1)
parts2 = _urlparse(url2)
# Because the query string ordering isn't relevant, we have to parse
# every single part manually and then handle the query string.
assert_equal(parts1.scheme, parts2.scheme)
assert_equal(parts1.netloc, parts2.netloc)
assert_equal(parts1.path, parts2.path)
assert_equal(parts1.params, parts2.params)
assert_equal(parts1.fragment, parts2.fragment)
assert_equal(parts1.username, parts2.username)
assert_equal(parts1.password, parts2.password)
assert_equal(parts1.hostname, parts2.hostname)
assert_equal(parts1.port, parts2.port)
assert_equal(parse_qs(parts1.query), parse_qs(parts2.query))
class HTTPStubberException(Exception):
pass
class RawResponse(BytesIO):
# TODO: There's a few objects similar to this in various tests, let's
# try and consolidate to this one in a future commit.
def stream(self, **kwargs):
contents = self.read()
while contents:
yield contents
contents = self.read()
class BaseHTTPStubber(object):
def __init__(self, obj_with_event_emitter, strict=True):
self.reset()
self._strict = strict
self._obj_with_event_emitter = obj_with_event_emitter
def reset(self):
self.requests = []
self.responses = []
def add_response(self, url='https://example.com', status=200, headers=None,
body=b''):
if headers is None:
headers = {}
raw = RawResponse(body)
response = AWSResponse(url, status, headers, raw)
self.responses.append(response)
@property
def _events(self):
raise NotImplementedError('_events')
def start(self):
self._events.register('before-send', self)
def stop(self):
self._events.unregister('before-send', self)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.stop()
def __call__(self, request, **kwargs):
self.requests.append(request)
if self.responses:
response = self.responses.pop(0)
if isinstance(response, Exception):
raise response
else:
return response
elif self._strict:
raise HTTPStubberException('Insufficient responses')
else:
return None
class ClientHTTPStubber(BaseHTTPStubber):
@property
def _events(self):
return self._obj_with_event_emitter.meta.events
class SessionHTTPStubber(BaseHTTPStubber):
@property
def _events(self):
return self._obj_with_event_emitter.get_component('event_emitter')
class ConsistencyWaiterException(Exception):
pass
class ConsistencyWaiter(object):
"""
A waiter class for some check to reach a consistent state.
:type min_successes: int
:param min_successes: The minimum number of successful check calls to
treat the check as stable. Default of 1 success.
:type max_attempts: int
:param min_successes: The maximum number of times to attempt calling
the check. Default of 20 attempts.
:type delay: int
:param delay: The number of seconds to delay the next API call after a
failed check call. Default of 5 seconds.
"""
def __init__(self, min_successes=1, max_attempts=20, delay=5,
delay_initial_poll=False):
self.min_successes = min_successes
self.max_attempts = max_attempts
self.delay = delay
self.delay_initial_poll = delay_initial_poll
def wait(self, check, *args, **kwargs):
"""
Wait until the check succeeds the configured number of times
:type check: callable
:param check: A callable that returns True or False to indicate
if the check succeeded or failed.
:type args: list
:param args: Any ordered arguments to be passed to the check.
:type kwargs: dict
:param kwargs: Any keyword arguments to be passed to the check.
"""
attempts = 0
successes = 0
if self.delay_initial_poll:
time.sleep(self.delay)
while attempts < self.max_attempts:
attempts += 1
if check(*args, **kwargs):
successes += 1
if successes >= self.min_successes:
return
else:
time.sleep(self.delay)
fail_msg = self._fail_message(attempts, successes)
raise ConsistencyWaiterException(fail_msg)
def _fail_message(self, attempts, successes):
format_args = (attempts, successes)
return 'Failed after %s attempts, only had %s successes' % format_args
class StubbedSession(botocore.session.Session):
def __init__(self, *args, **kwargs):
super(StubbedSession, self).__init__(*args, **kwargs)
self._cached_clients = {}
self._client_stubs = {}
def create_client(self, service_name, *args, **kwargs):
if service_name not in self._cached_clients:
client = self._create_stubbed_client(service_name, *args, **kwargs)
self._cached_clients[service_name] = client
return self._cached_clients[service_name]
def _create_stubbed_client(self, service_name, *args, **kwargs):
client = super(StubbedSession, self).create_client(
service_name, *args, **kwargs)
stubber = Stubber(client)
self._client_stubs[service_name] = stubber
return client
def stub(self, service_name, *args, **kwargs):
if service_name not in self._client_stubs:
self.create_client(service_name, *args, **kwargs)
return self._client_stubs[service_name]
def activate_stubs(self):
for stub in self._client_stubs.values():
stub.activate()
def verify_stubs(self):
for stub in self._client_stubs.values():
stub.assert_no_pending_responses()
|
is_cmd_finished
|
identifier_name
|
__init__.py
|
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import os
import sys
import mock
import time
import random
import shutil
import contextlib
import tempfile
import binascii
import platform
import select
import datetime
from io import BytesIO
from subprocess import Popen, PIPE
from dateutil.tz import tzlocal
import unittest
from nose.tools import assert_equal
import botocore.loaders
import botocore.session
from botocore.awsrequest import AWSResponse
from botocore.compat import (
parse_qs, six, urlparse, HAS_CRT
)
from botocore import utils
from botocore import credentials
from botocore.stub import Stubber
_LOADER = botocore.loaders.Loader()
def skip_unless_has_memory_collection(cls):
"""Class decorator to skip tests that require memory collection.
Any test that uses memory collection (such as the resource leak tests)
can decorate their class with skip_unless_has_memory_collection to
indicate that if the platform does not support memory collection
the tests should be skipped.
"""
if platform.system() not in ['Darwin', 'Linux']:
return unittest.skip('Memory tests only supported on mac/linux.')(cls)
return cls
def skip_if_windows(reason):
"""Decorator to skip tests that should not be run on windows.
Example usage:
@skip_if_windows("Not valid")
def test_some_non_windows_stuff(self):
self.assertEqual(...)
"""
def decorator(func):
return unittest.skipIf(
platform.system() not in ['Darwin', 'Linux'], reason)(func)
return decorator
def requires_crt(reason=None):
if reason is None:
reason = "Test requires awscrt to be installed"
def decorator(func):
return unittest.skipIf(not HAS_CRT, reason)(func)
return decorator
def random_chars(num_chars):
"""Returns random hex characters.
Useful for creating resources with random names.
"""
return binascii.hexlify(os.urandom(int(num_chars / 2))).decode('ascii')
def create_session(**kwargs):
# Create a Session object. By default,
# the _LOADER object is used as the loader
# so that we reused the same models across tests.
session = botocore.session.Session(**kwargs)
session.register_component('data_loader', _LOADER)
session.set_config_variable('credentials_file', 'noexist/foo/botocore')
return session
@contextlib.contextmanager
def temporary_file(mode):
"""This is a cross platform temporary file creation.
tempfile.NamedTemporary file on windows creates a secure temp file
that can't be read by other processes and can't be opened a second time.
For tests, we generally *want* them to be read multiple times.
The test fixture writes the temp file contents, the test reads the
temp file.
"""
temporary_directory = tempfile.mkdtemp()
basename = 'tmpfile-%s-%s' % (int(time.time()), random.randint(1, 1000))
full_filename = os.path.join(temporary_directory, basename)
open(full_filename, 'w').close()
try:
with open(full_filename, mode) as f:
yield f
finally:
shutil.rmtree(temporary_directory)
class BaseEnvVar(unittest.TestCase):
def setUp(self):
# Automatically patches out os.environ for you
# and gives you a self.environ attribute that simulates
# the environment. Also will automatically restore state
# for you in tearDown()
self.environ = {}
self.environ_patch = mock.patch('os.environ', self.environ)
self.environ_patch.start()
def tearDown(self):
self.environ_patch.stop()
class BaseSessionTest(BaseEnvVar):
"""Base class used to provide credentials.
This class can be used as a base class that want to use a real
session class but want to be completely isolated from the
external environment (including environment variables).
This class will also set credential vars so you can make fake
requests to services.
"""
def setUp(self, **environ):
super(BaseSessionTest, self).setUp()
self.environ['AWS_ACCESS_KEY_ID'] = 'access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
self.environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
self.environ.update(environ)
self.session = create_session()
self.session.config_filename = 'no-exist-foo'
@skip_unless_has_memory_collection
class BaseClientDriverTest(unittest.TestCase):
INJECT_DUMMY_CREDS = False
def setUp(self):
self.driver = ClientDriver()
env = None
if self.INJECT_DUMMY_CREDS:
env = {'AWS_ACCESS_KEY_ID': 'foo',
'AWS_SECRET_ACCESS_KEY': 'bar'}
self.driver.start(env=env)
def cmd(self, *args):
self.driver.cmd(*args)
def send_cmd(self, *args):
self.driver.send_cmd(*args)
def record_memory(self):
self.driver.record_memory()
@property
def memory_samples(self):
return self.driver.memory_samples
def tearDown(self):
self.driver.stop()
class ClientDriver(object):
CLIENT_SERVER = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'cmd-runner'
)
def __init__(self):
self._popen = None
self.memory_samples = []
def _get_memory_with_ps(self, pid):
# It would be better to eventually switch to psutil,
# which should allow us to test on windows, but for now
# we'll just use ps and run on POSIX platforms.
command_list = ['ps', '-p', str(pid), '-o', 'rss']
p = Popen(command_list, stdout=PIPE)
stdout = p.communicate()[0]
if not p.returncode == 0:
raise RuntimeError("Could not retrieve memory")
else:
# Get the RSS from output that looks like this:
# RSS
# 4496
return int(stdout.splitlines()[1].split()[0]) * 1024
def record_memory(self):
mem = self._get_memory_with_ps(self._popen.pid)
self.memory_samples.append(mem)
def start(self, env=None):
"""Start up the command runner process."""
self._popen = Popen([sys.executable, self.CLIENT_SERVER],
stdout=PIPE, stdin=PIPE, env=env)
def stop(self):
"""Shutdown the command runner process."""
self.cmd('exit')
self._popen.wait()
def send_cmd(self, *cmd):
"""Send a command and return immediately.
This is a lower level method than cmd().
This method will instruct the cmd-runner process
to execute a command, but this method will
immediately return. You will need to use
``is_cmd_finished()`` to check that the command
is finished.
This method is useful if you want to record attributes
about the process while an operation is occurring. For
example, if you want to instruct the cmd-runner process
to upload a 1GB file to S3 and you'd like to record
the memory during the upload process, you can use
send_cmd() instead of cmd().
"""
cmd_str = ' '.join(cmd) + '\n'
cmd_bytes = cmd_str.encode('utf-8')
self._popen.stdin.write(cmd_bytes)
self._popen.stdin.flush()
def is_cmd_finished(self):
rlist = [self._popen.stdout.fileno()]
result = select.select(rlist, [], [], 0.01)
if result[0]:
return True
return False
def cmd(self, *cmd):
"""Send a command and block until it finishes.
This method will send a command to the cmd-runner process
to run. It will block until the cmd-runner process is
finished executing the command and sends back a status
response.
"""
self.send_cmd(*cmd)
result = self._popen.stdout.readline().strip()
if result != b'OK':
raise RuntimeError(
"Error from command '%s': %s" % (cmd, result))
# This is added to this file because it's used in both
# the functional and unit tests for cred refresh.
class IntegerRefresher(credentials.RefreshableCredentials):
"""Refreshable credentials to help with testing.
This class makes testing refreshable credentials easier.
It has the following functionality:
* A counter, self.refresh_counter, to indicate how many
times refresh was called.
* A way to specify how many seconds to make credentials
valid.
* Configurable advisory/mandatory refresh.
* An easy way to check consistency. Each time creds are
refreshed, all the cred values are set to the next
incrementing integer. Frozen credentials should always
have this value.
"""
_advisory_refresh_timeout = 2
_mandatory_refresh_timeout = 1
_credentials_expire = 3
def __init__(self, creds_last_for=_credentials_expire,
advisory_refresh=_advisory_refresh_timeout,
mandatory_refresh=_mandatory_refresh_timeout,
refresh_function=None):
expires_in = (
self._current_datetime() +
datetime.timedelta(seconds=creds_last_for))
if refresh_function is None:
refresh_function = self._do_refresh
super(IntegerRefresher, self).__init__(
'0', '0', '0', expires_in,
refresh_function, 'INTREFRESH')
self.creds_last_for = creds_last_for
self.refresh_counter = 0
self._advisory_refresh_timeout = advisory_refresh
self._mandatory_refresh_timeout = mandatory_refresh
def _do_refresh(self):
self.refresh_counter += 1
current = int(self._access_key)
next_id = str(current + 1)
return {
'access_key': next_id,
'secret_key': next_id,
'token': next_id,
'expiry_time': self._seconds_later(self.creds_last_for),
}
def _seconds_later(self, num_seconds):
# We need to guarantee at *least* num_seconds.
# Because this doesn't handle subsecond precision
# we'll round up to the next second.
num_seconds += 1
t = self._current_datetime() + datetime.timedelta(seconds=num_seconds)
return self._to_timestamp(t)
def _to_timestamp(self, datetime_obj):
obj = utils.parse_to_aware_datetime(datetime_obj)
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
def _current_timestamp(self):
return self._to_timestamp(self._current_datetime())
def _current_datetime(self):
return datetime.datetime.now(tzlocal())
def _urlparse(url):
if isinstance(url, six.binary_type):
# Not really necessary, but it helps to reduce noise on Python 2.x
url = url.decode('utf8')
return urlparse(url)
def assert_url_equal(url1, url2):
parts1 = _urlparse(url1)
parts2 = _urlparse(url2)
# Because the query string ordering isn't relevant, we have to parse
# every single part manually and then handle the query string.
assert_equal(parts1.scheme, parts2.scheme)
assert_equal(parts1.netloc, parts2.netloc)
assert_equal(parts1.path, parts2.path)
assert_equal(parts1.params, parts2.params)
assert_equal(parts1.fragment, parts2.fragment)
assert_equal(parts1.username, parts2.username)
assert_equal(parts1.password, parts2.password)
assert_equal(parts1.hostname, parts2.hostname)
assert_equal(parts1.port, parts2.port)
assert_equal(parse_qs(parts1.query), parse_qs(parts2.query))
class HTTPStubberException(Exception):
pass
class RawResponse(BytesIO):
# TODO: There's a few objects similar to this in various tests, let's
# try and consolidate to this one in a future commit.
def stream(self, **kwargs):
contents = self.read()
while contents:
yield contents
contents = self.read()
class BaseHTTPStubber(object):
def __init__(self, obj_with_event_emitter, strict=True):
self.reset()
self._strict = strict
self._obj_with_event_emitter = obj_with_event_emitter
def reset(self):
self.requests = []
self.responses = []
def add_response(self, url='https://example.com', status=200, headers=None,
body=b''):
if headers is None:
headers = {}
raw = RawResponse(body)
response = AWSResponse(url, status, headers, raw)
self.responses.append(response)
@property
def _events(self):
raise NotImplementedError('_events')
def start(self):
self._events.register('before-send', self)
def stop(self):
self._events.unregister('before-send', self)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.stop()
def __call__(self, request, **kwargs):
self.requests.append(request)
if self.responses:
response = self.responses.pop(0)
if isinstance(response, Exception):
raise response
else:
return response
elif self._strict:
raise HTTPStubberException('Insufficient responses')
else:
return None
class ClientHTTPStubber(BaseHTTPStubber):
@property
def _events(self):
return self._obj_with_event_emitter.meta.events
class SessionHTTPStubber(BaseHTTPStubber):
@property
def _events(self):
return self._obj_with_event_emitter.get_component('event_emitter')
class ConsistencyWaiterException(Exception):
pass
class ConsistencyWaiter(object):
"""
A waiter class for some check to reach a consistent state.
:type min_successes: int
:param min_successes: The minimum number of successful check calls to
treat the check as stable. Default of 1 success.
:type max_attempts: int
:param min_successes: The maximum number of times to attempt calling
the check. Default of 20 attempts.
:type delay: int
:param delay: The number of seconds to delay the next API call after a
failed check call. Default of 5 seconds.
"""
def __init__(self, min_successes=1, max_attempts=20, delay=5,
delay_initial_poll=False):
self.min_successes = min_successes
self.max_attempts = max_attempts
self.delay = delay
self.delay_initial_poll = delay_initial_poll
def wait(self, check, *args, **kwargs):
"""
Wait until the check succeeds the configured number of times
:type check: callable
:param check: A callable that returns True or False to indicate
if the check succeeded or failed.
:type args: list
:param args: Any ordered arguments to be passed to the check.
:type kwargs: dict
:param kwargs: Any keyword arguments to be passed to the check.
"""
attempts = 0
successes = 0
if self.delay_initial_poll:
time.sleep(self.delay)
while attempts < self.max_attempts:
attempts += 1
if check(*args, **kwargs):
successes += 1
if successes >= self.min_successes:
return
else:
time.sleep(self.delay)
fail_msg = self._fail_message(attempts, successes)
raise ConsistencyWaiterException(fail_msg)
def _fail_message(self, attempts, successes):
format_args = (attempts, successes)
return 'Failed after %s attempts, only had %s successes' % format_args
class StubbedSession(botocore.session.Session):
def __init__(self, *args, **kwargs):
super(StubbedSession, self).__init__(*args, **kwargs)
self._cached_clients = {}
self._client_stubs = {}
def create_client(self, service_name, *args, **kwargs):
if service_name not in self._cached_clients:
|
return self._cached_clients[service_name]
def _create_stubbed_client(self, service_name, *args, **kwargs):
client = super(StubbedSession, self).create_client(
service_name, *args, **kwargs)
stubber = Stubber(client)
self._client_stubs[service_name] = stubber
return client
def stub(self, service_name, *args, **kwargs):
if service_name not in self._client_stubs:
self.create_client(service_name, *args, **kwargs)
return self._client_stubs[service_name]
def activate_stubs(self):
for stub in self._client_stubs.values():
stub.activate()
def verify_stubs(self):
for stub in self._client_stubs.values():
stub.assert_no_pending_responses()
|
client = self._create_stubbed_client(service_name, *args, **kwargs)
self._cached_clients[service_name] = client
|
conditional_block
|
base.py
|
"""The base command."""
from datetime import datetime
from json import dumps
from watches.util import ESClientProducer
class Base(object):
"""A base command."""
TEXT_PLAIN = 'plain/text'
JSON_APPLICATION = 'application/json'
TRANSFORM_PARAM = '--transform'
TIMESTAMP_PARAM = '--timestamp'
TRANSFORM_VALUE_NESTED = 'nested'
TIMESTAMP_KEY = 'timestamp'
_ALL_KEYWORD = '_all'
_ALL_INDICES_PLACEHOLDER = 'indices_summary'
def __init__(self, options, *args, **kwargs):
self.options = options
self.args = args
self.kwargs = kwargs
if self.options["--verbose"]:
print('Supplied options:', dumps(self.options, indent=2, sort_keys=True))
self.es = ESClientProducer.create_client(self.options)
def run(self):
# Not sure if this is the best way to convert localtime to UTC in ISO 8601 format
ts = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
data = self.getData()
# Treat JSON_APPLICATION response differently than TEXT_PLAIN
# JSON data can be injected timestamp and formatted
if self.JSON_APPLICATION == self.getResponseContentType():
if self.options[self.TIMESTAMP_PARAM]:
data[self.TIMESTAMP_KEY] = ts
if self.options[self.TRANSFORM_PARAM]:
data = self.transformData(data)
self.printData(data)
def printData(self, data):
"""Print the data to the output. Depending on content type the data can be formatted differently.
Commands can also override this method is special treatment is needed, for example "just_*" commands.
"""
if self.JSON_APPLICATION == self.getResponseContentType():
if self.options["-l"]:
print(dumps(data, default=lambda x: str(x)))
else:
print(dumps(data, indent=2, sort_keys=False, default=lambda x: str(x)))
else:
print(data)
def getData(self):
raise NotImplementedError('Method getData() not implemented')
def getResponseContentType(self):
"""Response MIME type. By default we assume JSON, make sure to override if needed."""
return self.JSON_APPLICATION
def transformData(self, data):
"""
Data can be transformed before sending to client.
Currently, the only transformation type implemented is 'nested'.
:param data:
:return:
"""
transform = self.options[self.TRANSFORM_PARAM]
if transform:
if transform == self.TRANSFORM_VALUE_NESTED:
return self.transformNestedData(data)
else:
raise RuntimeError('Unsupported transform type')
else:
return data
def transformNestedData(self, data):
"""
If subclass supports 'nested' transformation then it needs to implement
this method and it can use and override provided helper methods.
By default the data is returned unchanged.
:param data:
:return:
"""
return data
def nestedNodes(self, nodes):
"""
Helper method to transform nodes object.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
nodesArray = []
for key in nodes:
n = nodes[key]
n['node'] = key
nodesArray.append(n)
return nodesArray
return nodes
def nestedNodesShardsArray(self, nodes):
"""
Helper method to transform nodes shards array.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
shardsArray = []
for node in nodes:
if isinstance(nodes[node], list):
for shard in nodes[node]:
# shard['node'] = node
# node value ^^ is already there in the dict
shardsArray.append(shard)
else:
raise RuntimeError('shards not in expected format')
else:
raise RuntimeError('shards not in expected format')
return shardsArray
def nestedIndices(self, indices):
"""
Helper method to transform indices object.
Subclass can override this if the default behaviour does not apply.
:param indices:
:return:
"""
if isinstance(indices, dict):
indicesArray = []
for key in indices:
i = indices[key]
i['index'] = key
indicesArray.append(i)
return indicesArray
else:
return indices
def nestedShards(self, shards):
"""
Helper method to transform shards object.
Subclass can override this if the default behaviour does not apply.
:param shards:
:return:
"""
if isinstance(shards, dict):
|
s = shards[key]
# convert shard id to number (this is how other admin REST APIs represent it)
s['shard'] = int(key)
shardsArray.append(s)
return shardsArray
else:
return shards
def nestedShardsArray(self, shards):
"""
Helper method to transform shards array.
This is useful in case REST API returns shards data in an array.
:param shards:
:return:
"""
shardsArray = []
if isinstance(shards, dict):
for key in shards:
if isinstance(shards[key], list):
for shard in shards[key]:
shard['shard'] = int(key)
shardsArray.append(shard)
else:
raise RuntimeError('shards not in expected format')
else:
raise RuntimeError('shards not in expected format')
return shardsArray
def nestedIndicesAndShards(self, indices):
"""
Helper method to transform indices and shards.
This method is designed for cases where index contains 'shards' key as the top level field.
:param indices:
:return:
"""
indices = self.nestedIndices(indices)
for index in indices:
if isinstance(index, dict):
if 'shards' in index:
index['shards'] = self.nestedShards(index['shards'])
return indices
def check_filter_path(self, args):
if self.options['--filter_path'] and self.options["--filter_path"] is not None and len(self.options["--filter_path"]) > 0:
args.update({
'filter_path': self.options['--filter_path']
})
|
shardsArray = []
for key in shards:
|
random_line_split
|
base.py
|
"""The base command."""
from datetime import datetime
from json import dumps
from watches.util import ESClientProducer
class Base(object):
"""A base command."""
TEXT_PLAIN = 'plain/text'
JSON_APPLICATION = 'application/json'
TRANSFORM_PARAM = '--transform'
TIMESTAMP_PARAM = '--timestamp'
TRANSFORM_VALUE_NESTED = 'nested'
TIMESTAMP_KEY = 'timestamp'
_ALL_KEYWORD = '_all'
_ALL_INDICES_PLACEHOLDER = 'indices_summary'
def __init__(self, options, *args, **kwargs):
self.options = options
self.args = args
self.kwargs = kwargs
if self.options["--verbose"]:
print('Supplied options:', dumps(self.options, indent=2, sort_keys=True))
self.es = ESClientProducer.create_client(self.options)
def run(self):
# Not sure if this is the best way to convert localtime to UTC in ISO 8601 format
ts = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
data = self.getData()
# Treat JSON_APPLICATION response differently than TEXT_PLAIN
# JSON data can be injected timestamp and formatted
if self.JSON_APPLICATION == self.getResponseContentType():
if self.options[self.TIMESTAMP_PARAM]:
data[self.TIMESTAMP_KEY] = ts
if self.options[self.TRANSFORM_PARAM]:
data = self.transformData(data)
self.printData(data)
def printData(self, data):
"""Print the data to the output. Depending on content type the data can be formatted differently.
Commands can also override this method is special treatment is needed, for example "just_*" commands.
"""
if self.JSON_APPLICATION == self.getResponseContentType():
if self.options["-l"]:
print(dumps(data, default=lambda x: str(x)))
else:
print(dumps(data, indent=2, sort_keys=False, default=lambda x: str(x)))
else:
print(data)
def getData(self):
raise NotImplementedError('Method getData() not implemented')
def getResponseContentType(self):
"""Response MIME type. By default we assume JSON, make sure to override if needed."""
return self.JSON_APPLICATION
def transformData(self, data):
"""
Data can be transformed before sending to client.
Currently, the only transformation type implemented is 'nested'.
:param data:
:return:
"""
transform = self.options[self.TRANSFORM_PARAM]
if transform:
if transform == self.TRANSFORM_VALUE_NESTED:
return self.transformNestedData(data)
else:
raise RuntimeError('Unsupported transform type')
else:
return data
def transformNestedData(self, data):
"""
If subclass supports 'nested' transformation then it needs to implement
this method and it can use and override provided helper methods.
By default the data is returned unchanged.
:param data:
:return:
"""
return data
def nestedNodes(self, nodes):
"""
Helper method to transform nodes object.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
|
return nodes
def nestedNodesShardsArray(self, nodes):
"""
Helper method to transform nodes shards array.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
shardsArray = []
for node in nodes:
if isinstance(nodes[node], list):
for shard in nodes[node]:
# shard['node'] = node
# node value ^^ is already there in the dict
shardsArray.append(shard)
else:
raise RuntimeError('shards not in expected format')
else:
raise RuntimeError('shards not in expected format')
return shardsArray
def nestedIndices(self, indices):
"""
Helper method to transform indices object.
Subclass can override this if the default behaviour does not apply.
:param indices:
:return:
"""
if isinstance(indices, dict):
indicesArray = []
for key in indices:
i = indices[key]
i['index'] = key
indicesArray.append(i)
return indicesArray
else:
return indices
def nestedShards(self, shards):
"""
Helper method to transform shards object.
Subclass can override this if the default behaviour does not apply.
:param shards:
:return:
"""
if isinstance(shards, dict):
shardsArray = []
for key in shards:
s = shards[key]
# convert shard id to number (this is how other admin REST APIs represent it)
s['shard'] = int(key)
shardsArray.append(s)
return shardsArray
else:
return shards
def nestedShardsArray(self, shards):
"""
Helper method to transform shards array.
This is useful in case REST API returns shards data in an array.
:param shards:
:return:
"""
shardsArray = []
if isinstance(shards, dict):
for key in shards:
if isinstance(shards[key], list):
for shard in shards[key]:
shard['shard'] = int(key)
shardsArray.append(shard)
else:
raise RuntimeError('shards not in expected format')
else:
raise RuntimeError('shards not in expected format')
return shardsArray
def nestedIndicesAndShards(self, indices):
"""
Helper method to transform indices and shards.
This method is designed for cases where index contains 'shards' key as the top level field.
:param indices:
:return:
"""
indices = self.nestedIndices(indices)
for index in indices:
if isinstance(index, dict):
if 'shards' in index:
index['shards'] = self.nestedShards(index['shards'])
return indices
def check_filter_path(self, args):
if self.options['--filter_path'] and self.options["--filter_path"] is not None and len(self.options["--filter_path"]) > 0:
args.update({
'filter_path': self.options['--filter_path']
})
|
nodesArray = []
for key in nodes:
n = nodes[key]
n['node'] = key
nodesArray.append(n)
return nodesArray
|
conditional_block
|
base.py
|
"""The base command."""
from datetime import datetime
from json import dumps
from watches.util import ESClientProducer
class Base(object):
"""A base command."""
TEXT_PLAIN = 'plain/text'
JSON_APPLICATION = 'application/json'
TRANSFORM_PARAM = '--transform'
TIMESTAMP_PARAM = '--timestamp'
TRANSFORM_VALUE_NESTED = 'nested'
TIMESTAMP_KEY = 'timestamp'
_ALL_KEYWORD = '_all'
_ALL_INDICES_PLACEHOLDER = 'indices_summary'
def __init__(self, options, *args, **kwargs):
self.options = options
self.args = args
self.kwargs = kwargs
if self.options["--verbose"]:
print('Supplied options:', dumps(self.options, indent=2, sort_keys=True))
self.es = ESClientProducer.create_client(self.options)
def run(self):
# Not sure if this is the best way to convert localtime to UTC in ISO 8601 format
ts = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
data = self.getData()
# Treat JSON_APPLICATION response differently than TEXT_PLAIN
# JSON data can be injected timestamp and formatted
if self.JSON_APPLICATION == self.getResponseContentType():
if self.options[self.TIMESTAMP_PARAM]:
data[self.TIMESTAMP_KEY] = ts
if self.options[self.TRANSFORM_PARAM]:
data = self.transformData(data)
self.printData(data)
def printData(self, data):
"""Print the data to the output. Depending on content type the data can be formatted differently.
Commands can also override this method is special treatment is needed, for example "just_*" commands.
"""
if self.JSON_APPLICATION == self.getResponseContentType():
if self.options["-l"]:
print(dumps(data, default=lambda x: str(x)))
else:
print(dumps(data, indent=2, sort_keys=False, default=lambda x: str(x)))
else:
print(data)
def getData(self):
|
def getResponseContentType(self):
"""Response MIME type. By default we assume JSON, make sure to override if needed."""
return self.JSON_APPLICATION
def transformData(self, data):
"""
Data can be transformed before sending to client.
Currently, the only transformation type implemented is 'nested'.
:param data:
:return:
"""
transform = self.options[self.TRANSFORM_PARAM]
if transform:
if transform == self.TRANSFORM_VALUE_NESTED:
return self.transformNestedData(data)
else:
raise RuntimeError('Unsupported transform type')
else:
return data
def transformNestedData(self, data):
"""
If subclass supports 'nested' transformation then it needs to implement
this method and it can use and override provided helper methods.
By default the data is returned unchanged.
:param data:
:return:
"""
return data
def nestedNodes(self, nodes):
"""
Helper method to transform nodes object.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
nodesArray = []
for key in nodes:
n = nodes[key]
n['node'] = key
nodesArray.append(n)
return nodesArray
return nodes
def nestedNodesShardsArray(self, nodes):
"""
Helper method to transform nodes shards array.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
shardsArray = []
for node in nodes:
if isinstance(nodes[node], list):
for shard in nodes[node]:
# shard['node'] = node
# node value ^^ is already there in the dict
shardsArray.append(shard)
else:
raise RuntimeError('shards not in expected format')
else:
raise RuntimeError('shards not in expected format')
return shardsArray
def nestedIndices(self, indices):
"""
Helper method to transform indices object.
Subclass can override this if the default behaviour does not apply.
:param indices:
:return:
"""
if isinstance(indices, dict):
indicesArray = []
for key in indices:
i = indices[key]
i['index'] = key
indicesArray.append(i)
return indicesArray
else:
return indices
def nestedShards(self, shards):
"""
Helper method to transform shards object.
Subclass can override this if the default behaviour does not apply.
:param shards:
:return:
"""
if isinstance(shards, dict):
shardsArray = []
for key in shards:
s = shards[key]
# convert shard id to number (this is how other admin REST APIs represent it)
s['shard'] = int(key)
shardsArray.append(s)
return shardsArray
else:
return shards
def nestedShardsArray(self, shards):
"""
Helper method to transform shards array.
This is useful in case REST API returns shards data in an array.
:param shards:
:return:
"""
shardsArray = []
if isinstance(shards, dict):
for key in shards:
if isinstance(shards[key], list):
for shard in shards[key]:
shard['shard'] = int(key)
shardsArray.append(shard)
else:
raise RuntimeError('shards not in expected format')
else:
raise RuntimeError('shards not in expected format')
return shardsArray
def nestedIndicesAndShards(self, indices):
"""
Helper method to transform indices and shards.
This method is designed for cases where index contains 'shards' key as the top level field.
:param indices:
:return:
"""
indices = self.nestedIndices(indices)
for index in indices:
if isinstance(index, dict):
if 'shards' in index:
index['shards'] = self.nestedShards(index['shards'])
return indices
def check_filter_path(self, args):
if self.options['--filter_path'] and self.options["--filter_path"] is not None and len(self.options["--filter_path"]) > 0:
args.update({
'filter_path': self.options['--filter_path']
})
|
raise NotImplementedError('Method getData() not implemented')
|
identifier_body
|
base.py
|
"""The base command."""
from datetime import datetime
from json import dumps
from watches.util import ESClientProducer
class Base(object):
"""A base command."""
TEXT_PLAIN = 'plain/text'
JSON_APPLICATION = 'application/json'
TRANSFORM_PARAM = '--transform'
TIMESTAMP_PARAM = '--timestamp'
TRANSFORM_VALUE_NESTED = 'nested'
TIMESTAMP_KEY = 'timestamp'
_ALL_KEYWORD = '_all'
_ALL_INDICES_PLACEHOLDER = 'indices_summary'
def __init__(self, options, *args, **kwargs):
self.options = options
self.args = args
self.kwargs = kwargs
if self.options["--verbose"]:
print('Supplied options:', dumps(self.options, indent=2, sort_keys=True))
self.es = ESClientProducer.create_client(self.options)
def run(self):
# Not sure if this is the best way to convert localtime to UTC in ISO 8601 format
ts = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
data = self.getData()
# Treat JSON_APPLICATION response differently than TEXT_PLAIN
# JSON data can be injected timestamp and formatted
if self.JSON_APPLICATION == self.getResponseContentType():
if self.options[self.TIMESTAMP_PARAM]:
data[self.TIMESTAMP_KEY] = ts
if self.options[self.TRANSFORM_PARAM]:
data = self.transformData(data)
self.printData(data)
def printData(self, data):
"""Print the data to the output. Depending on content type the data can be formatted differently.
Commands can also override this method is special treatment is needed, for example "just_*" commands.
"""
if self.JSON_APPLICATION == self.getResponseContentType():
if self.options["-l"]:
print(dumps(data, default=lambda x: str(x)))
else:
print(dumps(data, indent=2, sort_keys=False, default=lambda x: str(x)))
else:
print(data)
def getData(self):
raise NotImplementedError('Method getData() not implemented')
def getResponseContentType(self):
"""Response MIME type. By default we assume JSON, make sure to override if needed."""
return self.JSON_APPLICATION
def transformData(self, data):
"""
Data can be transformed before sending to client.
Currently, the only transformation type implemented is 'nested'.
:param data:
:return:
"""
transform = self.options[self.TRANSFORM_PARAM]
if transform:
if transform == self.TRANSFORM_VALUE_NESTED:
return self.transformNestedData(data)
else:
raise RuntimeError('Unsupported transform type')
else:
return data
def transformNestedData(self, data):
"""
If subclass supports 'nested' transformation then it needs to implement
this method and it can use and override provided helper methods.
By default the data is returned unchanged.
:param data:
:return:
"""
return data
def nestedNodes(self, nodes):
"""
Helper method to transform nodes object.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
nodesArray = []
for key in nodes:
n = nodes[key]
n['node'] = key
nodesArray.append(n)
return nodesArray
return nodes
def nestedNodesShardsArray(self, nodes):
"""
Helper method to transform nodes shards array.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
shardsArray = []
for node in nodes:
if isinstance(nodes[node], list):
for shard in nodes[node]:
# shard['node'] = node
# node value ^^ is already there in the dict
shardsArray.append(shard)
else:
raise RuntimeError('shards not in expected format')
else:
raise RuntimeError('shards not in expected format')
return shardsArray
def nestedIndices(self, indices):
"""
Helper method to transform indices object.
Subclass can override this if the default behaviour does not apply.
:param indices:
:return:
"""
if isinstance(indices, dict):
indicesArray = []
for key in indices:
i = indices[key]
i['index'] = key
indicesArray.append(i)
return indicesArray
else:
return indices
def nestedShards(self, shards):
"""
Helper method to transform shards object.
Subclass can override this if the default behaviour does not apply.
:param shards:
:return:
"""
if isinstance(shards, dict):
shardsArray = []
for key in shards:
s = shards[key]
# convert shard id to number (this is how other admin REST APIs represent it)
s['shard'] = int(key)
shardsArray.append(s)
return shardsArray
else:
return shards
def
|
(self, shards):
"""
Helper method to transform shards array.
This is useful in case REST API returns shards data in an array.
:param shards:
:return:
"""
shardsArray = []
if isinstance(shards, dict):
for key in shards:
if isinstance(shards[key], list):
for shard in shards[key]:
shard['shard'] = int(key)
shardsArray.append(shard)
else:
raise RuntimeError('shards not in expected format')
else:
raise RuntimeError('shards not in expected format')
return shardsArray
def nestedIndicesAndShards(self, indices):
"""
Helper method to transform indices and shards.
This method is designed for cases where index contains 'shards' key as the top level field.
:param indices:
:return:
"""
indices = self.nestedIndices(indices)
for index in indices:
if isinstance(index, dict):
if 'shards' in index:
index['shards'] = self.nestedShards(index['shards'])
return indices
def check_filter_path(self, args):
if self.options['--filter_path'] and self.options["--filter_path"] is not None and len(self.options["--filter_path"]) > 0:
args.update({
'filter_path': self.options['--filter_path']
})
|
nestedShardsArray
|
identifier_name
|
itunes.py
|
# Support for the iTunes format
# Copyright 2010-2015 Kurt McKee <[email protected]>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import, unicode_literals
from ..util import FeedParserDict
class Namespace(object):
supported_namespaces = {
# Canonical namespace
'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
# Extra namespace
'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
}
def _start_itunes_author(self, attrsD):
self._start_author(attrsD)
def _end_itunes_author(self):
self._end_author()
def _end_itunes_category(self):
self._end_category()
def _start_itunes_name(self, attrsD):
self._start_name(attrsD)
def _end_itunes_name(self):
self._end_name()
def _start_itunes_email(self, attrsD):
self._start_email(attrsD)
def _end_itunes_email(self):
self._end_email()
def _start_itunes_subtitle(self, attrsD):
self._start_subtitle(attrsD)
def _end_itunes_subtitle(self):
self._end_subtitle()
def _start_itunes_summary(self, attrsD):
self._start_summary(attrsD)
def _end_itunes_summary(self):
self._end_summary()
def _start_itunes_owner(self, attrsD):
|
def _end_itunes_owner(self):
self.pop('publisher')
self.inpublisher = 0
self._sync_author_detail('publisher')
def _end_itunes_keywords(self):
for term in self.pop('itunes_keywords').split(','):
if term.strip():
self._addTag(term.strip(), 'http://www.itunes.com/', None)
def _start_itunes_category(self, attrsD):
self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
self.push('category', 1)
def _start_itunes_image(self, attrsD):
self.push('itunes_image', 0)
if attrsD.get('href'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
elif attrsD.get('url'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('url')})
_start_itunes_link = _start_itunes_image
def _end_itunes_block(self):
value = self.pop('itunes_block', 0)
self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
def _end_itunes_explicit(self):
value = self.pop('itunes_explicit', 0)
# Convert 'yes' -> True, 'clean' to False, and any other value to None
# False and None both evaluate as False, so the difference can be ignored
# by applications that only need to know if the content is explicit.
self._getContext()['itunes_explicit'] = (None, False, True)[(value == 'yes' and 2) or value == 'clean' or 0]
|
self.inpublisher = 1
self.push('publisher', 0)
|
identifier_body
|
itunes.py
|
# Support for the iTunes format
# Copyright 2010-2015 Kurt McKee <[email protected]>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import, unicode_literals
from ..util import FeedParserDict
class Namespace(object):
supported_namespaces = {
# Canonical namespace
'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
# Extra namespace
'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
}
def _start_itunes_author(self, attrsD):
self._start_author(attrsD)
def _end_itunes_author(self):
self._end_author()
def _end_itunes_category(self):
self._end_category()
def _start_itunes_name(self, attrsD):
self._start_name(attrsD)
def _end_itunes_name(self):
self._end_name()
def _start_itunes_email(self, attrsD):
self._start_email(attrsD)
def _end_itunes_email(self):
self._end_email()
def _start_itunes_subtitle(self, attrsD):
self._start_subtitle(attrsD)
def _end_itunes_subtitle(self):
self._end_subtitle()
def _start_itunes_summary(self, attrsD):
self._start_summary(attrsD)
def _end_itunes_summary(self):
self._end_summary()
def _start_itunes_owner(self, attrsD):
self.inpublisher = 1
self.push('publisher', 0)
def _end_itunes_owner(self):
self.pop('publisher')
self.inpublisher = 0
|
self._addTag(term.strip(), 'http://www.itunes.com/', None)
def _start_itunes_category(self, attrsD):
self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
self.push('category', 1)
def _start_itunes_image(self, attrsD):
self.push('itunes_image', 0)
if attrsD.get('href'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
elif attrsD.get('url'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('url')})
_start_itunes_link = _start_itunes_image
def _end_itunes_block(self):
value = self.pop('itunes_block', 0)
self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
def _end_itunes_explicit(self):
value = self.pop('itunes_explicit', 0)
# Convert 'yes' -> True, 'clean' to False, and any other value to None
# False and None both evaluate as False, so the difference can be ignored
# by applications that only need to know if the content is explicit.
self._getContext()['itunes_explicit'] = (None, False, True)[(value == 'yes' and 2) or value == 'clean' or 0]
|
self._sync_author_detail('publisher')
def _end_itunes_keywords(self):
for term in self.pop('itunes_keywords').split(','):
if term.strip():
|
random_line_split
|
itunes.py
|
# Support for the iTunes format
# Copyright 2010-2015 Kurt McKee <[email protected]>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import, unicode_literals
from ..util import FeedParserDict
class Namespace(object):
supported_namespaces = {
# Canonical namespace
'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
# Extra namespace
'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
}
def _start_itunes_author(self, attrsD):
self._start_author(attrsD)
def _end_itunes_author(self):
self._end_author()
def _end_itunes_category(self):
self._end_category()
def
|
(self, attrsD):
self._start_name(attrsD)
def _end_itunes_name(self):
self._end_name()
def _start_itunes_email(self, attrsD):
self._start_email(attrsD)
def _end_itunes_email(self):
self._end_email()
def _start_itunes_subtitle(self, attrsD):
self._start_subtitle(attrsD)
def _end_itunes_subtitle(self):
self._end_subtitle()
def _start_itunes_summary(self, attrsD):
self._start_summary(attrsD)
def _end_itunes_summary(self):
self._end_summary()
def _start_itunes_owner(self, attrsD):
self.inpublisher = 1
self.push('publisher', 0)
def _end_itunes_owner(self):
self.pop('publisher')
self.inpublisher = 0
self._sync_author_detail('publisher')
def _end_itunes_keywords(self):
for term in self.pop('itunes_keywords').split(','):
if term.strip():
self._addTag(term.strip(), 'http://www.itunes.com/', None)
def _start_itunes_category(self, attrsD):
self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
self.push('category', 1)
def _start_itunes_image(self, attrsD):
self.push('itunes_image', 0)
if attrsD.get('href'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
elif attrsD.get('url'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('url')})
_start_itunes_link = _start_itunes_image
def _end_itunes_block(self):
value = self.pop('itunes_block', 0)
self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
def _end_itunes_explicit(self):
value = self.pop('itunes_explicit', 0)
# Convert 'yes' -> True, 'clean' to False, and any other value to None
# False and None both evaluate as False, so the difference can be ignored
# by applications that only need to know if the content is explicit.
self._getContext()['itunes_explicit'] = (None, False, True)[(value == 'yes' and 2) or value == 'clean' or 0]
|
_start_itunes_name
|
identifier_name
|
itunes.py
|
# Support for the iTunes format
# Copyright 2010-2015 Kurt McKee <[email protected]>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import, unicode_literals
from ..util import FeedParserDict
class Namespace(object):
supported_namespaces = {
# Canonical namespace
'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
# Extra namespace
'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
}
def _start_itunes_author(self, attrsD):
self._start_author(attrsD)
def _end_itunes_author(self):
self._end_author()
def _end_itunes_category(self):
self._end_category()
def _start_itunes_name(self, attrsD):
self._start_name(attrsD)
def _end_itunes_name(self):
self._end_name()
def _start_itunes_email(self, attrsD):
self._start_email(attrsD)
def _end_itunes_email(self):
self._end_email()
def _start_itunes_subtitle(self, attrsD):
self._start_subtitle(attrsD)
def _end_itunes_subtitle(self):
self._end_subtitle()
def _start_itunes_summary(self, attrsD):
self._start_summary(attrsD)
def _end_itunes_summary(self):
self._end_summary()
def _start_itunes_owner(self, attrsD):
self.inpublisher = 1
self.push('publisher', 0)
def _end_itunes_owner(self):
self.pop('publisher')
self.inpublisher = 0
self._sync_author_detail('publisher')
def _end_itunes_keywords(self):
for term in self.pop('itunes_keywords').split(','):
if term.strip():
|
def _start_itunes_category(self, attrsD):
self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
self.push('category', 1)
def _start_itunes_image(self, attrsD):
self.push('itunes_image', 0)
if attrsD.get('href'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
elif attrsD.get('url'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('url')})
_start_itunes_link = _start_itunes_image
def _end_itunes_block(self):
value = self.pop('itunes_block', 0)
self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
def _end_itunes_explicit(self):
value = self.pop('itunes_explicit', 0)
# Convert 'yes' -> True, 'clean' to False, and any other value to None
# False and None both evaluate as False, so the difference can be ignored
# by applications that only need to know if the content is explicit.
self._getContext()['itunes_explicit'] = (None, False, True)[(value == 'yes' and 2) or value == 'clean' or 0]
|
self._addTag(term.strip(), 'http://www.itunes.com/', None)
|
conditional_block
|
mod.rs
|
//! This module contains type definition for ECMAScript values.
//! According to the ECMA-262 specification, there are six "types"
//! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`,
//! and `Object`. Four of these are value types and do not need
//! heap allocation, while `String` and `Object` have to be allocated
//! on the heap.
//!
//! ## Undefined
//! The undefined type is a type with exactly one value: `undefined`.
//! It is the value of any unassigned variable.
//!
//! ## Null
//! The null type if also a type with exactly one value: `null`.
//!
//! ## Boolean
//! The boolean type has exactly two values: `true` and `false`.
//!
//! ## String
//! The string type is defined by the spec to be the set of
//! all finite sequences of 16-bit integers. Unlike Rust strings,
//! ECMAScript strings can be indexed, which returns the n-th
//! 16-bit integer that composes this string.
//!
//! When a string contains textual data, it's assumed by the
//! implementation and the spec that each 16-bit integer is a
//! valid UTF-16 code unit.
//!
//! ## Number
//! The number type is defined by the spec as a 64-bit floating
//! point number. As such, there exist many ways to represent a
//! floating point `NaN`, as well as exactly one `Infinity` and
//! `-Infinity`.
//!
//! ECMAScript acknowledges the existence of both a positive
//! zero and negative zero.
//!
//! Some ECMAScript operations work on 32-bit integers explicitly.
//! In this case, the implementation will convert a Number value
//! into an integer using the internal *ToInt32* and *ToUInt32* conversion
//! functions to convert the numeric value.
//!
//! ## Object
//! You could write books about this type, so I'll keep this brief.
//! An object is a collection of properties. Every property is one
//! of three types:
//! * A **named data property**, which associates a *name* with an
//! ECMAScript language value and a set of attributes.
//! * A **named accessor property**, which associates a *name* with
//! one or two *acessor functions* (getter/setter), along with a
//! set of attributes.
//! * An **internal property**, which isn't exposed to ECMAScript and
//! is used for specification and implementation purposes.
pub mod object;
pub mod activation;
pub mod property;
pub mod function;
use super::heap::{self, RootedPtr, ToHeapObject, HeapObject, Trace};
use std::vec::IntoIter;
use std::default::Default;
//pub use self::object::Object;
//pub use self::activation::Activation;
pub type RootedValue = RootedPtr<Value>;
#[derive(Copy, Clone)]
pub enum Value {
// `undefined`, the sentinel of ECMAScript
Undefined,
// `null`, the value of the null object
Null,
// numbers
Number(heap::NumberPtr),
// booleans
Boolean(heap::BooleanPtr),
// strings
String(heap::StringPtr),
// objects
Object(heap::ObjectPtr),
}
impl ToHeapObject for Value {
fn to_heap_object(&self) -> Option<HeapObject> {
match *self {
Value::Null | Value::Undefined => None,
Value::Number(ptr) => ptr.to_heap_object(),
Value::Boolean(ptr) => ptr.to_heap_object(),
Value::String(ptr) => ptr.to_heap_object(),
Value::Object(ptr) => ptr.to_heap_object(),
}
}
}
impl Trace for Value {
fn trace(&self) -> IntoIter<HeapObject> {
if let Some(heap_obj) = self.to_heap_object() {
heap_obj.trace()
} else {
vec![].into_iter()
}
}
}
impl Default for Value {
fn default() -> Value {
Value::Undefined
}
}
impl Value {
pub fn undefined() -> Value {
Value::Undefined
}
pub fn
|
() -> Value {
Value::Null
}
pub fn number(ptr: heap::NumberPtr) -> Value {
Value::Number(ptr)
}
pub fn boolean(ptr: heap::BooleanPtr) -> Value {
Value::Boolean(ptr)
}
pub fn string(ptr: heap::StringPtr) -> Value {
Value::String(ptr)
}
pub fn object(ptr: heap::ObjectPtr) -> Value {
Value::Object(ptr)
}
pub fn is_undefined(&self) -> bool {
if let Value::Undefined = *self {
true
} else {
false
}
}
pub fn is_null(&self) -> bool {
if let Value::Null = *self {
true
} else {
false
}
}
pub fn is_string(&self) -> bool {
if let Value::String(_) = *self {
true
} else {
false
}
}
pub fn is_object(&self) -> bool {
if let Value::Object(_) = *self {
true
} else {
false
}
}
pub fn unwrap_object(&self) -> heap::ObjectPtr {
if let Value::Object(ptr) = *self {
return ptr;
}
panic!("unwrap_object called on non-object value");
}
pub fn same_value(&self, _: Value) -> bool {
// TODO
unimplemented!()
}
}
pub trait IntoRootedValue {
fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue;
}
macro_rules! into_rooted_value_impl {
($rooted_ty:ty, $name:path) => {
impl IntoRootedValue for $rooted_ty {
fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue {
let ptr = self.into_inner();
heap.root_value($name(ptr))
}
}
}
}
into_rooted_value_impl!(heap::RootedBooleanPtr, Value::Boolean);
into_rooted_value_impl!(heap::RootedNumberPtr, Value::Number);
into_rooted_value_impl!(heap::RootedObjectPtr, Value::Object);
into_rooted_value_impl!(heap::RootedStringPtr, Value::String);
#[derive(Debug)]
pub struct Exception;
pub type EvalResult<T> = Result<T, Exception>;
pub type EvalValue = Result<RootedValue, Exception>;
|
null
|
identifier_name
|
mod.rs
|
//! This module contains type definition for ECMAScript values.
//! According to the ECMA-262 specification, there are six "types"
//! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`,
//! and `Object`. Four of these are value types and do not need
//! heap allocation, while `String` and `Object` have to be allocated
//! on the heap.
//!
//! ## Undefined
//! The undefined type is a type with exactly one value: `undefined`.
//! It is the value of any unassigned variable.
//!
//! ## Null
//! The null type if also a type with exactly one value: `null`.
//!
//! ## Boolean
//! The boolean type has exactly two values: `true` and `false`.
//!
//! ## String
//! The string type is defined by the spec to be the set of
//! all finite sequences of 16-bit integers. Unlike Rust strings,
//! ECMAScript strings can be indexed, which returns the n-th
//! 16-bit integer that composes this string.
//!
//! When a string contains textual data, it's assumed by the
//! implementation and the spec that each 16-bit integer is a
//! valid UTF-16 code unit.
//!
//! ## Number
//! The number type is defined by the spec as a 64-bit floating
//! point number. As such, there exist many ways to represent a
//! floating point `NaN`, as well as exactly one `Infinity` and
//! `-Infinity`.
//!
//! ECMAScript acknowledges the existence of both a positive
//! zero and negative zero.
//!
//! Some ECMAScript operations work on 32-bit integers explicitly.
//! In this case, the implementation will convert a Number value
//! into an integer using the internal *ToInt32* and *ToUInt32* conversion
//! functions to convert the numeric value.
//!
//! ## Object
//! You could write books about this type, so I'll keep this brief.
//! An object is a collection of properties. Every property is one
//! of three types:
//! * A **named data property**, which associates a *name* with an
//! ECMAScript language value and a set of attributes.
//! * A **named accessor property**, which associates a *name* with
//! one or two *acessor functions* (getter/setter), along with a
//! set of attributes.
//! * An **internal property**, which isn't exposed to ECMAScript and
//! is used for specification and implementation purposes.
pub mod object;
pub mod activation;
pub mod property;
pub mod function;
use super::heap::{self, RootedPtr, ToHeapObject, HeapObject, Trace};
use std::vec::IntoIter;
use std::default::Default;
//pub use self::object::Object;
//pub use self::activation::Activation;
pub type RootedValue = RootedPtr<Value>;
#[derive(Copy, Clone)]
pub enum Value {
// `undefined`, the sentinel of ECMAScript
Undefined,
// `null`, the value of the null object
Null,
// numbers
Number(heap::NumberPtr),
// booleans
Boolean(heap::BooleanPtr),
// strings
String(heap::StringPtr),
// objects
Object(heap::ObjectPtr),
}
impl ToHeapObject for Value {
fn to_heap_object(&self) -> Option<HeapObject> {
match *self {
Value::Null | Value::Undefined => None,
Value::Number(ptr) => ptr.to_heap_object(),
Value::Boolean(ptr) => ptr.to_heap_object(),
Value::String(ptr) => ptr.to_heap_object(),
Value::Object(ptr) => ptr.to_heap_object(),
}
}
}
impl Trace for Value {
fn trace(&self) -> IntoIter<HeapObject> {
if let Some(heap_obj) = self.to_heap_object() {
heap_obj.trace()
} else {
vec![].into_iter()
}
}
}
impl Default for Value {
fn default() -> Value
|
}
impl Value {
pub fn undefined() -> Value {
Value::Undefined
}
pub fn null() -> Value {
Value::Null
}
pub fn number(ptr: heap::NumberPtr) -> Value {
Value::Number(ptr)
}
pub fn boolean(ptr: heap::BooleanPtr) -> Value {
Value::Boolean(ptr)
}
pub fn string(ptr: heap::StringPtr) -> Value {
Value::String(ptr)
}
pub fn object(ptr: heap::ObjectPtr) -> Value {
Value::Object(ptr)
}
pub fn is_undefined(&self) -> bool {
if let Value::Undefined = *self {
true
} else {
false
}
}
pub fn is_null(&self) -> bool {
if let Value::Null = *self {
true
} else {
false
}
}
pub fn is_string(&self) -> bool {
if let Value::String(_) = *self {
true
} else {
false
}
}
pub fn is_object(&self) -> bool {
if let Value::Object(_) = *self {
true
} else {
false
}
}
pub fn unwrap_object(&self) -> heap::ObjectPtr {
if let Value::Object(ptr) = *self {
return ptr;
}
panic!("unwrap_object called on non-object value");
}
pub fn same_value(&self, _: Value) -> bool {
// TODO
unimplemented!()
}
}
pub trait IntoRootedValue {
fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue;
}
macro_rules! into_rooted_value_impl {
($rooted_ty:ty, $name:path) => {
impl IntoRootedValue for $rooted_ty {
fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue {
let ptr = self.into_inner();
heap.root_value($name(ptr))
}
}
}
}
into_rooted_value_impl!(heap::RootedBooleanPtr, Value::Boolean);
into_rooted_value_impl!(heap::RootedNumberPtr, Value::Number);
into_rooted_value_impl!(heap::RootedObjectPtr, Value::Object);
into_rooted_value_impl!(heap::RootedStringPtr, Value::String);
#[derive(Debug)]
pub struct Exception;
pub type EvalResult<T> = Result<T, Exception>;
pub type EvalValue = Result<RootedValue, Exception>;
|
{
Value::Undefined
}
|
identifier_body
|
mod.rs
|
//! This module contains type definition for ECMAScript values.
//! According to the ECMA-262 specification, there are six "types"
//! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`,
//! and `Object`. Four of these are value types and do not need
//! heap allocation, while `String` and `Object` have to be allocated
//! on the heap.
//!
//! ## Undefined
//! The undefined type is a type with exactly one value: `undefined`.
//! It is the value of any unassigned variable.
//!
//! ## Null
//! The null type if also a type with exactly one value: `null`.
//!
//! ## Boolean
//! The boolean type has exactly two values: `true` and `false`.
//!
//! ## String
//! The string type is defined by the spec to be the set of
//! all finite sequences of 16-bit integers. Unlike Rust strings,
//! ECMAScript strings can be indexed, which returns the n-th
//! 16-bit integer that composes this string.
//!
//! When a string contains textual data, it's assumed by the
//! implementation and the spec that each 16-bit integer is a
//! valid UTF-16 code unit.
//!
//! ## Number
//! The number type is defined by the spec as a 64-bit floating
//! point number. As such, there exist many ways to represent a
//! floating point `NaN`, as well as exactly one `Infinity` and
//! `-Infinity`.
//!
//! ECMAScript acknowledges the existence of both a positive
//! zero and negative zero.
//!
//! Some ECMAScript operations work on 32-bit integers explicitly.
//! In this case, the implementation will convert a Number value
//! into an integer using the internal *ToInt32* and *ToUInt32* conversion
//! functions to convert the numeric value.
//!
//! ## Object
//! You could write books about this type, so I'll keep this brief.
//! An object is a collection of properties. Every property is one
//! of three types:
//! * A **named data property**, which associates a *name* with an
//! ECMAScript language value and a set of attributes.
//! * A **named accessor property**, which associates a *name* with
//! one or two *acessor functions* (getter/setter), along with a
//! set of attributes.
//! * An **internal property**, which isn't exposed to ECMAScript and
//! is used for specification and implementation purposes.
pub mod object;
pub mod activation;
pub mod property;
pub mod function;
use super::heap::{self, RootedPtr, ToHeapObject, HeapObject, Trace};
use std::vec::IntoIter;
use std::default::Default;
//pub use self::object::Object;
//pub use self::activation::Activation;
pub type RootedValue = RootedPtr<Value>;
#[derive(Copy, Clone)]
pub enum Value {
// `undefined`, the sentinel of ECMAScript
Undefined,
// `null`, the value of the null object
Null,
// numbers
Number(heap::NumberPtr),
// booleans
Boolean(heap::BooleanPtr),
// strings
String(heap::StringPtr),
// objects
Object(heap::ObjectPtr),
}
impl ToHeapObject for Value {
fn to_heap_object(&self) -> Option<HeapObject> {
match *self {
Value::Null | Value::Undefined => None,
Value::Number(ptr) => ptr.to_heap_object(),
Value::Boolean(ptr) => ptr.to_heap_object(),
Value::String(ptr) => ptr.to_heap_object(),
Value::Object(ptr) => ptr.to_heap_object(),
}
}
}
impl Trace for Value {
fn trace(&self) -> IntoIter<HeapObject> {
if let Some(heap_obj) = self.to_heap_object() {
heap_obj.trace()
|
} else {
vec![].into_iter()
}
}
}
impl Default for Value {
fn default() -> Value {
Value::Undefined
}
}
impl Value {
pub fn undefined() -> Value {
Value::Undefined
}
pub fn null() -> Value {
Value::Null
}
pub fn number(ptr: heap::NumberPtr) -> Value {
Value::Number(ptr)
}
pub fn boolean(ptr: heap::BooleanPtr) -> Value {
Value::Boolean(ptr)
}
pub fn string(ptr: heap::StringPtr) -> Value {
Value::String(ptr)
}
pub fn object(ptr: heap::ObjectPtr) -> Value {
Value::Object(ptr)
}
pub fn is_undefined(&self) -> bool {
if let Value::Undefined = *self {
true
} else {
false
}
}
pub fn is_null(&self) -> bool {
if let Value::Null = *self {
true
} else {
false
}
}
pub fn is_string(&self) -> bool {
if let Value::String(_) = *self {
true
} else {
false
}
}
pub fn is_object(&self) -> bool {
if let Value::Object(_) = *self {
true
} else {
false
}
}
pub fn unwrap_object(&self) -> heap::ObjectPtr {
if let Value::Object(ptr) = *self {
return ptr;
}
panic!("unwrap_object called on non-object value");
}
pub fn same_value(&self, _: Value) -> bool {
// TODO
unimplemented!()
}
}
pub trait IntoRootedValue {
fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue;
}
macro_rules! into_rooted_value_impl {
($rooted_ty:ty, $name:path) => {
impl IntoRootedValue for $rooted_ty {
fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue {
let ptr = self.into_inner();
heap.root_value($name(ptr))
}
}
}
}
into_rooted_value_impl!(heap::RootedBooleanPtr, Value::Boolean);
into_rooted_value_impl!(heap::RootedNumberPtr, Value::Number);
into_rooted_value_impl!(heap::RootedObjectPtr, Value::Object);
into_rooted_value_impl!(heap::RootedStringPtr, Value::String);
#[derive(Debug)]
pub struct Exception;
pub type EvalResult<T> = Result<T, Exception>;
pub type EvalValue = Result<RootedValue, Exception>;
|
random_line_split
|
|
mod.rs
|
//! This module contains type definition for ECMAScript values.
//! According to the ECMA-262 specification, there are six "types"
//! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`,
//! and `Object`. Four of these are value types and do not need
//! heap allocation, while `String` and `Object` have to be allocated
//! on the heap.
//!
//! ## Undefined
//! The undefined type is a type with exactly one value: `undefined`.
//! It is the value of any unassigned variable.
//!
//! ## Null
//! The null type if also a type with exactly one value: `null`.
//!
//! ## Boolean
//! The boolean type has exactly two values: `true` and `false`.
//!
//! ## String
//! The string type is defined by the spec to be the set of
//! all finite sequences of 16-bit integers. Unlike Rust strings,
//! ECMAScript strings can be indexed, which returns the n-th
//! 16-bit integer that composes this string.
//!
//! When a string contains textual data, it's assumed by the
//! implementation and the spec that each 16-bit integer is a
//! valid UTF-16 code unit.
//!
//! ## Number
//! The number type is defined by the spec as a 64-bit floating
//! point number. As such, there exist many ways to represent a
//! floating point `NaN`, as well as exactly one `Infinity` and
//! `-Infinity`.
//!
//! ECMAScript acknowledges the existence of both a positive
//! zero and negative zero.
//!
//! Some ECMAScript operations work on 32-bit integers explicitly.
//! In this case, the implementation will convert a Number value
//! into an integer using the internal *ToInt32* and *ToUInt32* conversion
//! functions to convert the numeric value.
//!
//! ## Object
//! You could write books about this type, so I'll keep this brief.
//! An object is a collection of properties. Every property is one
//! of three types:
//! * A **named data property**, which associates a *name* with an
//! ECMAScript language value and a set of attributes.
//! * A **named accessor property**, which associates a *name* with
//! one or two *acessor functions* (getter/setter), along with a
//! set of attributes.
//! * An **internal property**, which isn't exposed to ECMAScript and
//! is used for specification and implementation purposes.
pub mod object;
pub mod activation;
pub mod property;
pub mod function;
use super::heap::{self, RootedPtr, ToHeapObject, HeapObject, Trace};
use std::vec::IntoIter;
use std::default::Default;
//pub use self::object::Object;
//pub use self::activation::Activation;
pub type RootedValue = RootedPtr<Value>;
#[derive(Copy, Clone)]
pub enum Value {
// `undefined`, the sentinel of ECMAScript
Undefined,
// `null`, the value of the null object
Null,
// numbers
Number(heap::NumberPtr),
// booleans
Boolean(heap::BooleanPtr),
// strings
String(heap::StringPtr),
// objects
Object(heap::ObjectPtr),
}
impl ToHeapObject for Value {
fn to_heap_object(&self) -> Option<HeapObject> {
match *self {
Value::Null | Value::Undefined => None,
Value::Number(ptr) => ptr.to_heap_object(),
Value::Boolean(ptr) => ptr.to_heap_object(),
Value::String(ptr) => ptr.to_heap_object(),
Value::Object(ptr) => ptr.to_heap_object(),
}
}
}
impl Trace for Value {
fn trace(&self) -> IntoIter<HeapObject> {
if let Some(heap_obj) = self.to_heap_object() {
heap_obj.trace()
} else
|
}
}
impl Default for Value {
fn default() -> Value {
Value::Undefined
}
}
impl Value {
pub fn undefined() -> Value {
Value::Undefined
}
pub fn null() -> Value {
Value::Null
}
pub fn number(ptr: heap::NumberPtr) -> Value {
Value::Number(ptr)
}
pub fn boolean(ptr: heap::BooleanPtr) -> Value {
Value::Boolean(ptr)
}
pub fn string(ptr: heap::StringPtr) -> Value {
Value::String(ptr)
}
pub fn object(ptr: heap::ObjectPtr) -> Value {
Value::Object(ptr)
}
pub fn is_undefined(&self) -> bool {
if let Value::Undefined = *self {
true
} else {
false
}
}
pub fn is_null(&self) -> bool {
if let Value::Null = *self {
true
} else {
false
}
}
pub fn is_string(&self) -> bool {
if let Value::String(_) = *self {
true
} else {
false
}
}
pub fn is_object(&self) -> bool {
if let Value::Object(_) = *self {
true
} else {
false
}
}
pub fn unwrap_object(&self) -> heap::ObjectPtr {
if let Value::Object(ptr) = *self {
return ptr;
}
panic!("unwrap_object called on non-object value");
}
pub fn same_value(&self, _: Value) -> bool {
// TODO
unimplemented!()
}
}
pub trait IntoRootedValue {
fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue;
}
macro_rules! into_rooted_value_impl {
($rooted_ty:ty, $name:path) => {
impl IntoRootedValue for $rooted_ty {
fn into_rooted_value(self, heap: &mut heap::Heap) -> RootedValue {
let ptr = self.into_inner();
heap.root_value($name(ptr))
}
}
}
}
into_rooted_value_impl!(heap::RootedBooleanPtr, Value::Boolean);
into_rooted_value_impl!(heap::RootedNumberPtr, Value::Number);
into_rooted_value_impl!(heap::RootedObjectPtr, Value::Object);
into_rooted_value_impl!(heap::RootedStringPtr, Value::String);
#[derive(Debug)]
pub struct Exception;
pub type EvalResult<T> = Result<T, Exception>;
pub type EvalValue = Result<RootedValue, Exception>;
|
{
vec![].into_iter()
}
|
conditional_block
|
metadata.ts
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AbstractHistoryEntity} from '../common/abstract-history-entity';
import {MetadataSource} from './metadata-source';
import {MetadataColumn} from './metadata-column';
import * as _ from 'lodash';
export class Metadata extends AbstractHistoryEntity {
public id: string;
public description: string;
public name: string;
public sourceType: SourceType;
public source: MetadataSource;
public favorite: boolean;
public catalogs: any;
public tags: any;
public popularity: number;
public columns: MetadataColumn[];
public static isSourceTypeIsEngine(sourceType: SourceType)
|
public static isSourceTypeIsStaging(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.STAGING;
}
public static isSourceTypeIsJdbc(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.JDBC;
}
public static isDisableMetadataNameCharacter(name: string) {
return (/^[!@#$%^*+=()~`\{\}\[\]\-\_\;\:\'\"\,\.\/\?\<\>\|\&\\]+$/gi).test(name);
}
public static isEmptyTags(metadata: Metadata): boolean {
return _.isNil(metadata.tags) || metadata.tags.length === 0;
}
}
export enum SourceType {
ENGINE = 'ENGINE',
STAGING = 'STAGEDB',
STAGEDB = 'STAGEDB',
JDBC = 'JDBC',
ETC = 'ETC'
}
|
{
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.ENGINE;
}
|
identifier_body
|
metadata.ts
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AbstractHistoryEntity} from '../common/abstract-history-entity';
import {MetadataSource} from './metadata-source';
import {MetadataColumn} from './metadata-column';
import * as _ from 'lodash';
export class
|
extends AbstractHistoryEntity {
public id: string;
public description: string;
public name: string;
public sourceType: SourceType;
public source: MetadataSource;
public favorite: boolean;
public catalogs: any;
public tags: any;
public popularity: number;
public columns: MetadataColumn[];
public static isSourceTypeIsEngine(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.ENGINE;
}
public static isSourceTypeIsStaging(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.STAGING;
}
public static isSourceTypeIsJdbc(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.JDBC;
}
public static isDisableMetadataNameCharacter(name: string) {
return (/^[!@#$%^*+=()~`\{\}\[\]\-\_\;\:\'\"\,\.\/\?\<\>\|\&\\]+$/gi).test(name);
}
public static isEmptyTags(metadata: Metadata): boolean {
return _.isNil(metadata.tags) || metadata.tags.length === 0;
}
}
export enum SourceType {
ENGINE = 'ENGINE',
STAGING = 'STAGEDB',
STAGEDB = 'STAGEDB',
JDBC = 'JDBC',
ETC = 'ETC'
}
|
Metadata
|
identifier_name
|
metadata.ts
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AbstractHistoryEntity} from '../common/abstract-history-entity';
import {MetadataSource} from './metadata-source';
import {MetadataColumn} from './metadata-column';
import * as _ from 'lodash';
export class Metadata extends AbstractHistoryEntity {
public id: string;
public description: string;
public name: string;
public sourceType: SourceType;
public source: MetadataSource;
public favorite: boolean;
public catalogs: any;
public tags: any;
public popularity: number;
public columns: MetadataColumn[];
public static isSourceTypeIsEngine(sourceType: SourceType) {
|
public static isSourceTypeIsStaging(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.STAGING;
}
public static isSourceTypeIsJdbc(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.JDBC;
}
public static isDisableMetadataNameCharacter(name: string) {
return (/^[!@#$%^*+=()~`\{\}\[\]\-\_\;\:\'\"\,\.\/\?\<\>\|\&\\]+$/gi).test(name);
}
public static isEmptyTags(metadata: Metadata): boolean {
return _.isNil(metadata.tags) || metadata.tags.length === 0;
}
}
export enum SourceType {
ENGINE = 'ENGINE',
STAGING = 'STAGEDB',
STAGEDB = 'STAGEDB',
JDBC = 'JDBC',
ETC = 'ETC'
}
|
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.ENGINE;
}
|
random_line_split
|
markdown.ts
|
// Meteor Imports
import { Meteor } from 'meteor/meteor';
import { MeteorComponent } from 'angular2-meteor';
// Angular Imports
import { Component, Input } from '@angular/core';
import { InjectUser } from 'angular2-meteor-accounts-ui';
import { ActivatedRoute, Router } from '@angular/router';
// Angular Material Imports
import { MATERIAL_DIRECTIVES } from 'ng2-material';
// MDEditor
import { MDEditor } from '../mdeditor/mdeditor.ts';
// Roles
import { Roles } from '../../../../../collections/users.ts';
// Icons
import { MD_ICON_DIRECTIVES } from '@angular2-material/icon';
declare var Collections: any;
// Markdown Imports
/// <reference path="./marked.d.ts" />
import * as marked from 'marked';
// Define Markdown Component
@Component({
selector: 'tuxlab-markdown',
templateUrl: '/client/imports/ui/components/markdown/markdown.html',
directives: [
MATERIAL_DIRECTIVES,
MD_ICON_DIRECTIVES,
MDEditor
],
})
// Export MarkdownView Class
export class MarkdownView extends MeteorComponent{
@Input() mdData = "";
@Input() mdDataUpdate = "";
@Input() taskid: number;
courseId: string;
labId: string;
showMDE: boolean = false;
constructor(private route: ActivatedRoute, private router: Router) {
super();
}
convert(markdown: string) {
let md = marked.setOptions({});
if(typeof markdown !== "undefined" && markdown !== null) {
return md.parse(markdown);
}
else {
return "";
}
}
ngOnInit() {
this.courseId = this.router.routerState.parent(this.route).snapshot.params['courseid'];
this.labId = this.route.snapshot.params['labid'];
}
|
() {
if(typeof this.courseId !== "undefined") {
return Roles.isInstructorFor(this.courseId);
}
else {
return false;
}
}
// Toggle to show either markdown editor or task markdown
mdeToggle() {
this.showMDE = !this.showMDE;
}
// Update new markdown
updateMarkdown() {
Collections.labs.update({
_id: this.labId,
"tasks.id": this.taskid
}, {
$set: {
"tasks.$.md": this.mdData
}
});
}
// Output event from MDE
mdUpdated(md: string) {
this.mdData = md;
}
}
|
isInstruct
|
identifier_name
|
markdown.ts
|
// Meteor Imports
import { Meteor } from 'meteor/meteor';
import { MeteorComponent } from 'angular2-meteor';
// Angular Imports
import { Component, Input } from '@angular/core';
import { InjectUser } from 'angular2-meteor-accounts-ui';
import { ActivatedRoute, Router } from '@angular/router';
// Angular Material Imports
import { MATERIAL_DIRECTIVES } from 'ng2-material';
// MDEditor
import { MDEditor } from '../mdeditor/mdeditor.ts';
// Roles
import { Roles } from '../../../../../collections/users.ts';
// Icons
import { MD_ICON_DIRECTIVES } from '@angular2-material/icon';
declare var Collections: any;
// Markdown Imports
/// <reference path="./marked.d.ts" />
import * as marked from 'marked';
// Define Markdown Component
@Component({
selector: 'tuxlab-markdown',
templateUrl: '/client/imports/ui/components/markdown/markdown.html',
directives: [
MATERIAL_DIRECTIVES,
MD_ICON_DIRECTIVES,
MDEditor
],
})
// Export MarkdownView Class
export class MarkdownView extends MeteorComponent{
@Input() mdData = "";
@Input() mdDataUpdate = "";
@Input() taskid: number;
courseId: string;
labId: string;
showMDE: boolean = false;
constructor(private route: ActivatedRoute, private router: Router) {
super();
}
convert(markdown: string) {
let md = marked.setOptions({});
if(typeof markdown !== "undefined" && markdown !== null) {
return md.parse(markdown);
}
else {
|
}
ngOnInit() {
this.courseId = this.router.routerState.parent(this.route).snapshot.params['courseid'];
this.labId = this.route.snapshot.params['labid'];
}
isInstruct() {
if(typeof this.courseId !== "undefined") {
return Roles.isInstructorFor(this.courseId);
}
else {
return false;
}
}
// Toggle to show either markdown editor or task markdown
mdeToggle() {
this.showMDE = !this.showMDE;
}
// Update new markdown
updateMarkdown() {
Collections.labs.update({
_id: this.labId,
"tasks.id": this.taskid
}, {
$set: {
"tasks.$.md": this.mdData
}
});
}
// Output event from MDE
mdUpdated(md: string) {
this.mdData = md;
}
}
|
return "";
}
|
random_line_split
|
markdown.ts
|
// Meteor Imports
import { Meteor } from 'meteor/meteor';
import { MeteorComponent } from 'angular2-meteor';
// Angular Imports
import { Component, Input } from '@angular/core';
import { InjectUser } from 'angular2-meteor-accounts-ui';
import { ActivatedRoute, Router } from '@angular/router';
// Angular Material Imports
import { MATERIAL_DIRECTIVES } from 'ng2-material';
// MDEditor
import { MDEditor } from '../mdeditor/mdeditor.ts';
// Roles
import { Roles } from '../../../../../collections/users.ts';
// Icons
import { MD_ICON_DIRECTIVES } from '@angular2-material/icon';
declare var Collections: any;
// Markdown Imports
/// <reference path="./marked.d.ts" />
import * as marked from 'marked';
// Define Markdown Component
@Component({
selector: 'tuxlab-markdown',
templateUrl: '/client/imports/ui/components/markdown/markdown.html',
directives: [
MATERIAL_DIRECTIVES,
MD_ICON_DIRECTIVES,
MDEditor
],
})
// Export MarkdownView Class
export class MarkdownView extends MeteorComponent{
@Input() mdData = "";
@Input() mdDataUpdate = "";
@Input() taskid: number;
courseId: string;
labId: string;
showMDE: boolean = false;
constructor(private route: ActivatedRoute, private router: Router) {
super();
}
convert(markdown: string) {
let md = marked.setOptions({});
if(typeof markdown !== "undefined" && markdown !== null) {
return md.parse(markdown);
}
else {
return "";
}
}
ngOnInit() {
this.courseId = this.router.routerState.parent(this.route).snapshot.params['courseid'];
this.labId = this.route.snapshot.params['labid'];
}
isInstruct() {
if(typeof this.courseId !== "undefined")
|
else {
return false;
}
}
// Toggle to show either markdown editor or task markdown
mdeToggle() {
this.showMDE = !this.showMDE;
}
// Update new markdown
updateMarkdown() {
Collections.labs.update({
_id: this.labId,
"tasks.id": this.taskid
}, {
$set: {
"tasks.$.md": this.mdData
}
});
}
// Output event from MDE
mdUpdated(md: string) {
this.mdData = md;
}
}
|
{
return Roles.isInstructorFor(this.courseId);
}
|
conditional_block
|
Login.ts
|
import { Component } from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {UserPersonalData} from './UserPersonalData'
import {LoginService} from '../services/LoginService';
import {Http} from '@angular/http';
@Component({
selector: 'login',
templateUrl: './login.html',
styleUrls: ['../app.component.css']
})
export class LoginComponent {
constructor(private loginService: LoginService, private router: Router) { }
logIn(event: any, user: string, pass: string) {
event.preventDefault();
this.loginService.logIn(user, pass).subscribe(
u =>{ console.log(u);
if (this.loginService.getIsAdmin())
{this.router.navigate(['/admin']);}
else
this.router.navigate(['/userProjects']);
},
error => alert('Invalid user or password')
);
}
|
() {
this.loginService.logOut().subscribe(
response => {
this.router.navigate(['/index']);
},
error => console.log('Error when trying to log out: ' + error)
);
}
}
|
logOut
|
identifier_name
|
Login.ts
|
import { Component } from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {UserPersonalData} from './UserPersonalData'
import {LoginService} from '../services/LoginService';
import {Http} from '@angular/http';
@Component({
selector: 'login',
templateUrl: './login.html',
styleUrls: ['../app.component.css']
})
|
export class LoginComponent {
constructor(private loginService: LoginService, private router: Router) { }
logIn(event: any, user: string, pass: string) {
event.preventDefault();
this.loginService.logIn(user, pass).subscribe(
u =>{ console.log(u);
if (this.loginService.getIsAdmin())
{this.router.navigate(['/admin']);}
else
this.router.navigate(['/userProjects']);
},
error => alert('Invalid user or password')
);
}
logOut() {
this.loginService.logOut().subscribe(
response => {
this.router.navigate(['/index']);
},
error => console.log('Error when trying to log out: ' + error)
);
}
}
|
random_line_split
|
|
compiled.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.
#![allow(non_uppercase_statics)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use std::collections::HashMap;
use std::io;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin",
"no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type",
"hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above",
"memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok",
"dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff",
"prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region",
"can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch",
"cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin",
"cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling",
"no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs",
"return_does_clr_eol"];
pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
"gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon",
"nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy",
"xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"];
pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines",
"lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal",
"width_status_line", "num_labels", "label_height", "label_width", "max_attributes",
"maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity",
"dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size",
"micro_line_size", "number_of_pins", "output_res_char", "output_res_line",
"output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons",
"bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay",
"new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"];
pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
"vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv",
"spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs",
"btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"];
pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return",
"change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos",
"column_address", "command_character", "cursor_address", "cursor_down", "cursor_home",
"cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right",
"cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line",
"dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode",
"enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode",
"enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode",
"enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode",
"exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode",
"exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string",
"init_2string", "init_3string", "init_file", "insert_character", "insert_line",
"insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl",
"key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3",
"key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il",
"key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab",
"key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3",
"lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline",
"pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index",
"parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor",
"pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char",
"reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor",
"row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab",
"set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1",
"key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm",
"key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character",
"xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close",
"key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find",
"key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options",
"key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace",
"key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel",
"key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send",
"key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft",
"key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint",
"key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend",
"key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16",
"key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24",
"key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32",
"key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40",
"key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48",
"key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56",
"key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol",
"clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock",
"display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone",
"quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1",
"user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair",
"orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground",
"set_background", "change_char_pitch", "change_line_pitch", "change_res_horz",
"change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality",
"enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality",
"enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode",
"enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode",
"exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode",
"exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right",
"micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro",
"parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin",
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin",
"set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr",
"zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse",
"set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init",
"set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin",
"set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return",
"color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band",
"set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode",
"enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape",
"alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode",
"enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes",
"set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs",
"other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner",
"acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline",
"acs_plus", "memory_lock", "memory_unlock", "box_chars_1"];
pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
"_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1",
"ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc",
"dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc",
"rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip",
"kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_",
"khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_",
"_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey",
"pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind",
"ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p",
"rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln",
"rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp",
"kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl",
"krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_",
"kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT",
"kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf",
"setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq",
"snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm",
"rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub",
"mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd",
"rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm",
"setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb",
"birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch",
"rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm",
"ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2",
"OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu",
"box1"];
/// Parse a compiled terminfo entry, using long capability names if `longnames` is true
pub fn parse(file: &mut io::Reader, longnames: bool)
-> Result<Box<TermInfo>, String> {
macro_rules! try( ($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(format!("{}", e))
}
) )
let bnames;
let snames;
let nnames;
if longnames {
bnames = boolfnames;
snames = stringfnames;
nnames = numfnames;
} else {
bnames = boolnames;
snames = stringnames;
nnames = numnames;
}
// Check magic number
let magic = try!(file.read_le_u16());
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
0x011Au, magic as uint));
}
let names_bytes = try!(file.read_le_i16()) as int;
let bools_bytes = try!(file.read_le_i16()) as int;
let numbers_count = try!(file.read_le_i16()) as int;
let string_offsets_count = try!(file.read_le_i16()) as int;
let string_table_bytes = try!(file.read_le_i16()) as int;
assert!(names_bytes > 0);
if (bools_bytes as uint) > boolnames.len() {
return Err("incompatible file: more booleans than \
expected".to_string());
}
if (numbers_count as uint) > numnames.len() {
return Err("incompatible file: more numbers than \
expected".to_string());
}
if (string_offsets_count as uint) > stringnames.len() {
return Err("incompatible file: more string offsets than \
expected".to_string());
}
// don't read NUL
let bytes = try!(file.read_exact(names_bytes as uint - 1));
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.as_slice()
.split('|')
.map(|s| s.to_string())
.collect();
try!(file.read_byte()); // consume NUL
let mut bools_map = HashMap::new();
if bools_bytes != 0 {
for i in range(0, bools_bytes) {
let b = try!(file.read_byte());
if b == 1 {
bools_map.insert(bnames[i as uint].to_string(), true);
}
}
}
if (bools_bytes + names_bytes) % 2 == 1 {
try!(file.read_byte()); // compensate for padding
}
let mut numbers_map = HashMap::new();
if numbers_count != 0 {
for i in range(0, numbers_count) {
let n = try!(file.read_le_u16());
if n != 0xFFFF {
numbers_map.insert(nnames[i as uint].to_string(), n);
}
}
}
let mut string_map = HashMap::new();
if string_offsets_count != 0 {
let mut string_offsets = Vec::with_capacity(10);
for _ in range(0, string_offsets_count) {
string_offsets.push(try!(file.read_le_u16()));
}
let string_table = try!(file.read_exact(string_table_bytes as uint));
if string_table.len() != string_table_bytes as uint {
return Err("error: hit EOF before end of string \
table".to_string());
}
for (i, v) in string_offsets.iter().enumerate() {
let offset = *v;
if offset == 0xFFFF { // non-entry
continue;
}
let name = if snames[i] == "_" {
stringfnames[i]
} else {
snames[i]
};
if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct
string_map.insert(name.to_string(), Vec::new());
continue;
}
// Find the offset of the NUL we want to go to
let nulpos = string_table[offset as uint .. string_table_bytes as uint]
.iter().position(|&b| b == 0);
match nulpos {
Some(len) => {
string_map.insert(name.to_string(),
string_table[offset as uint ..
offset as uint + len].to_vec())
},
None => {
return Err("invalid file: missing NUL in \
string_table".to_string());
}
};
}
}
// And that's all there is to it
Ok(box TermInfo {
names: term_names,
bools: bools_map,
numbers: numbers_map,
strings: string_map
})
}
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo>
|
#[cfg(test)]
mod test {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn test_veclens() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
}
#[test]
#[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")]
fn test_parse() {
// FIXME #6870: Distribute a compiled file in src/tests and test there
// parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false);
}
}
|
{
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
box TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: HashMap::new(),
strings: strings
}
}
|
identifier_body
|
compiled.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.
#![allow(non_uppercase_statics)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use std::collections::HashMap;
use std::io;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin",
"no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type",
"hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above",
"memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok",
"dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff",
"prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region",
"can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch",
"cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin",
"cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling",
"no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs",
"return_does_clr_eol"];
pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
"gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon",
"nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy",
"xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"];
pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines",
"lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal",
"width_status_line", "num_labels", "label_height", "label_width", "max_attributes",
"maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity",
"dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size",
"micro_line_size", "number_of_pins", "output_res_char", "output_res_line",
"output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons",
"bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay",
"new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"];
pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
"vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv",
"spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs",
"btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"];
pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return",
"change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos",
"column_address", "command_character", "cursor_address", "cursor_down", "cursor_home",
"cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right",
"cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line",
"dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode",
"enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode",
"enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode",
"enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode",
"exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode",
"exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string",
"init_2string", "init_3string", "init_file", "insert_character", "insert_line",
"insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl",
"key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3",
"key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il",
"key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab",
"key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3",
"lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline",
"pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index",
"parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor",
"pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char",
"reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor",
"row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab",
"set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1",
"key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm",
"key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character",
"xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close",
"key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find",
"key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options",
"key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace",
"key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel",
"key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send",
"key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft",
"key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint",
"key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend",
"key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16",
"key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24",
"key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32",
"key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40",
"key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48",
"key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56",
"key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol",
"clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock",
"display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone",
"quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1",
"user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair",
"orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground",
"set_background", "change_char_pitch", "change_line_pitch", "change_res_horz",
"change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality",
"enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality",
"enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode",
"enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode",
"exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode",
"exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right",
"micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro",
"parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin",
|
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr",
"zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse",
"set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init",
"set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin",
"set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return",
"color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band",
"set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode",
"enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape",
"alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode",
"enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes",
"set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs",
"other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner",
"acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline",
"acs_plus", "memory_lock", "memory_unlock", "box_chars_1"];
pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
"_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1",
"ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc",
"dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc",
"rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip",
"kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_",
"khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_",
"_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey",
"pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind",
"ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p",
"rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln",
"rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp",
"kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl",
"krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_",
"kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT",
"kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf",
"setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq",
"snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm",
"rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub",
"mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd",
"rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm",
"setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb",
"birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch",
"rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm",
"ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2",
"OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu",
"box1"];
/// Parse a compiled terminfo entry, using long capability names if `longnames` is true
pub fn parse(file: &mut io::Reader, longnames: bool)
-> Result<Box<TermInfo>, String> {
macro_rules! try( ($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(format!("{}", e))
}
) )
let bnames;
let snames;
let nnames;
if longnames {
bnames = boolfnames;
snames = stringfnames;
nnames = numfnames;
} else {
bnames = boolnames;
snames = stringnames;
nnames = numnames;
}
// Check magic number
let magic = try!(file.read_le_u16());
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
0x011Au, magic as uint));
}
let names_bytes = try!(file.read_le_i16()) as int;
let bools_bytes = try!(file.read_le_i16()) as int;
let numbers_count = try!(file.read_le_i16()) as int;
let string_offsets_count = try!(file.read_le_i16()) as int;
let string_table_bytes = try!(file.read_le_i16()) as int;
assert!(names_bytes > 0);
if (bools_bytes as uint) > boolnames.len() {
return Err("incompatible file: more booleans than \
expected".to_string());
}
if (numbers_count as uint) > numnames.len() {
return Err("incompatible file: more numbers than \
expected".to_string());
}
if (string_offsets_count as uint) > stringnames.len() {
return Err("incompatible file: more string offsets than \
expected".to_string());
}
// don't read NUL
let bytes = try!(file.read_exact(names_bytes as uint - 1));
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.as_slice()
.split('|')
.map(|s| s.to_string())
.collect();
try!(file.read_byte()); // consume NUL
let mut bools_map = HashMap::new();
if bools_bytes != 0 {
for i in range(0, bools_bytes) {
let b = try!(file.read_byte());
if b == 1 {
bools_map.insert(bnames[i as uint].to_string(), true);
}
}
}
if (bools_bytes + names_bytes) % 2 == 1 {
try!(file.read_byte()); // compensate for padding
}
let mut numbers_map = HashMap::new();
if numbers_count != 0 {
for i in range(0, numbers_count) {
let n = try!(file.read_le_u16());
if n != 0xFFFF {
numbers_map.insert(nnames[i as uint].to_string(), n);
}
}
}
let mut string_map = HashMap::new();
if string_offsets_count != 0 {
let mut string_offsets = Vec::with_capacity(10);
for _ in range(0, string_offsets_count) {
string_offsets.push(try!(file.read_le_u16()));
}
let string_table = try!(file.read_exact(string_table_bytes as uint));
if string_table.len() != string_table_bytes as uint {
return Err("error: hit EOF before end of string \
table".to_string());
}
for (i, v) in string_offsets.iter().enumerate() {
let offset = *v;
if offset == 0xFFFF { // non-entry
continue;
}
let name = if snames[i] == "_" {
stringfnames[i]
} else {
snames[i]
};
if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct
string_map.insert(name.to_string(), Vec::new());
continue;
}
// Find the offset of the NUL we want to go to
let nulpos = string_table[offset as uint .. string_table_bytes as uint]
.iter().position(|&b| b == 0);
match nulpos {
Some(len) => {
string_map.insert(name.to_string(),
string_table[offset as uint ..
offset as uint + len].to_vec())
},
None => {
return Err("invalid file: missing NUL in \
string_table".to_string());
}
};
}
}
// And that's all there is to it
Ok(box TermInfo {
names: term_names,
bools: bools_map,
numbers: numbers_map,
strings: string_map
})
}
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo> {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
box TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: HashMap::new(),
strings: strings
}
}
#[cfg(test)]
mod test {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn test_veclens() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
}
#[test]
#[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")]
fn test_parse() {
// FIXME #6870: Distribute a compiled file in src/tests and test there
// parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false);
}
}
|
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin",
"set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
|
random_line_split
|
compiled.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.
#![allow(non_uppercase_statics)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use std::collections::HashMap;
use std::io;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin",
"no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type",
"hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above",
"memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok",
"dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff",
"prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region",
"can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch",
"cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin",
"cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling",
"no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs",
"return_does_clr_eol"];
pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
"gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon",
"nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy",
"xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"];
pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines",
"lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal",
"width_status_line", "num_labels", "label_height", "label_width", "max_attributes",
"maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity",
"dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size",
"micro_line_size", "number_of_pins", "output_res_char", "output_res_line",
"output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons",
"bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay",
"new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"];
pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
"vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv",
"spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs",
"btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"];
pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return",
"change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos",
"column_address", "command_character", "cursor_address", "cursor_down", "cursor_home",
"cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right",
"cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line",
"dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode",
"enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode",
"enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode",
"enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode",
"exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode",
"exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string",
"init_2string", "init_3string", "init_file", "insert_character", "insert_line",
"insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl",
"key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3",
"key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il",
"key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab",
"key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3",
"lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline",
"pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index",
"parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor",
"pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char",
"reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor",
"row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab",
"set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1",
"key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm",
"key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character",
"xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close",
"key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find",
"key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options",
"key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace",
"key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel",
"key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send",
"key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft",
"key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint",
"key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend",
"key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16",
"key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24",
"key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32",
"key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40",
"key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48",
"key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56",
"key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol",
"clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock",
"display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone",
"quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1",
"user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair",
"orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground",
"set_background", "change_char_pitch", "change_line_pitch", "change_res_horz",
"change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality",
"enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality",
"enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode",
"enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode",
"exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode",
"exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right",
"micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro",
"parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin",
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin",
"set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr",
"zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse",
"set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init",
"set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin",
"set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return",
"color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band",
"set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode",
"enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape",
"alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode",
"enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes",
"set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs",
"other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner",
"acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline",
"acs_plus", "memory_lock", "memory_unlock", "box_chars_1"];
pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
"_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1",
"ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc",
"dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc",
"rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip",
"kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_",
"khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_",
"_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey",
"pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind",
"ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p",
"rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln",
"rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp",
"kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl",
"krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_",
"kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT",
"kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf",
"setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq",
"snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm",
"rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub",
"mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd",
"rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm",
"setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb",
"birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch",
"rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm",
"ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2",
"OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu",
"box1"];
/// Parse a compiled terminfo entry, using long capability names if `longnames` is true
pub fn parse(file: &mut io::Reader, longnames: bool)
-> Result<Box<TermInfo>, String> {
macro_rules! try( ($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(format!("{}", e))
}
) )
let bnames;
let snames;
let nnames;
if longnames {
bnames = boolfnames;
snames = stringfnames;
nnames = numfnames;
} else {
bnames = boolnames;
snames = stringnames;
nnames = numnames;
}
// Check magic number
let magic = try!(file.read_le_u16());
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
0x011Au, magic as uint));
}
let names_bytes = try!(file.read_le_i16()) as int;
let bools_bytes = try!(file.read_le_i16()) as int;
let numbers_count = try!(file.read_le_i16()) as int;
let string_offsets_count = try!(file.read_le_i16()) as int;
let string_table_bytes = try!(file.read_le_i16()) as int;
assert!(names_bytes > 0);
if (bools_bytes as uint) > boolnames.len() {
return Err("incompatible file: more booleans than \
expected".to_string());
}
if (numbers_count as uint) > numnames.len() {
return Err("incompatible file: more numbers than \
expected".to_string());
}
if (string_offsets_count as uint) > stringnames.len() {
return Err("incompatible file: more string offsets than \
expected".to_string());
}
// don't read NUL
let bytes = try!(file.read_exact(names_bytes as uint - 1));
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.as_slice()
.split('|')
.map(|s| s.to_string())
.collect();
try!(file.read_byte()); // consume NUL
let mut bools_map = HashMap::new();
if bools_bytes != 0 {
for i in range(0, bools_bytes) {
let b = try!(file.read_byte());
if b == 1 {
bools_map.insert(bnames[i as uint].to_string(), true);
}
}
}
if (bools_bytes + names_bytes) % 2 == 1 {
try!(file.read_byte()); // compensate for padding
}
let mut numbers_map = HashMap::new();
if numbers_count != 0 {
for i in range(0, numbers_count) {
let n = try!(file.read_le_u16());
if n != 0xFFFF {
numbers_map.insert(nnames[i as uint].to_string(), n);
}
}
}
let mut string_map = HashMap::new();
if string_offsets_count != 0 {
let mut string_offsets = Vec::with_capacity(10);
for _ in range(0, string_offsets_count) {
string_offsets.push(try!(file.read_le_u16()));
}
let string_table = try!(file.read_exact(string_table_bytes as uint));
if string_table.len() != string_table_bytes as uint {
return Err("error: hit EOF before end of string \
table".to_string());
}
for (i, v) in string_offsets.iter().enumerate() {
let offset = *v;
if offset == 0xFFFF { // non-entry
continue;
}
let name = if snames[i] == "_" {
stringfnames[i]
} else {
snames[i]
};
if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct
string_map.insert(name.to_string(), Vec::new());
continue;
}
// Find the offset of the NUL we want to go to
let nulpos = string_table[offset as uint .. string_table_bytes as uint]
.iter().position(|&b| b == 0);
match nulpos {
Some(len) => {
string_map.insert(name.to_string(),
string_table[offset as uint ..
offset as uint + len].to_vec())
},
None => {
return Err("invalid file: missing NUL in \
string_table".to_string());
}
};
}
}
// And that's all there is to it
Ok(box TermInfo {
names: term_names,
bools: bools_map,
numbers: numbers_map,
strings: string_map
})
}
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo> {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
box TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: HashMap::new(),
strings: strings
}
}
#[cfg(test)]
mod test {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn
|
() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
}
#[test]
#[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")]
fn test_parse() {
// FIXME #6870: Distribute a compiled file in src/tests and test there
// parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false);
}
}
|
test_veclens
|
identifier_name
|
ForestTrustInformation.py
|
# encoding: utf-8
# module samba.dcerpc.lsa
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/lsa.so
# by generator 1.135
""" lsa DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class ForestTrustInformation(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
|
"""
S.ndr_pack(object) -> blob
NDR pack
"""
pass
def __ndr_print__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_print(object) -> None
NDR print
"""
pass
def __ndr_unpack__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_unpack(class, blob, allow_remaining=False) -> None
NDR unpack
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
entries = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
|
pass
def __ndr_pack__(self, *args, **kwargs): # real signature unknown
|
random_line_split
|
ForestTrustInformation.py
|
# encoding: utf-8
# module samba.dcerpc.lsa
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/lsa.so
# by generator 1.135
""" lsa DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class ForestTrustInformation(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
|
def __ndr_pack__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_pack(object) -> blob
NDR pack
"""
pass
def __ndr_print__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_print(object) -> None
NDR print
"""
pass
def __ndr_unpack__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_unpack(class, blob, allow_remaining=False) -> None
NDR unpack
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
entries = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
|
pass
|
identifier_body
|
ForestTrustInformation.py
|
# encoding: utf-8
# module samba.dcerpc.lsa
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/lsa.so
# by generator 1.135
""" lsa DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class ForestTrustInformation(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __ndr_pack__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_pack(object) -> blob
NDR pack
"""
pass
def
|
(self, *args, **kwargs): # real signature unknown
"""
S.ndr_print(object) -> None
NDR print
"""
pass
def __ndr_unpack__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_unpack(class, blob, allow_remaining=False) -> None
NDR unpack
"""
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
entries = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
|
__ndr_print__
|
identifier_name
|
index.ts
|
import { recordTracksEvent } from '@automattic/calypso-analytics';
import { dispatch } from '@wordpress/data';
import domReady from '@wordpress/dom-ready';
import { __ } from '@wordpress/i18n';
import { inIframe } from '../../../block-inserter-modifications/contextual-tips/utils';
import { GUTENBOARDING_LAUNCH_FLOW } from '../constants';
import 'a8c-fse-common-data-stores';
import '@wordpress/editor';
import './styles.scss';
let handled = false;
domReady( () => {
// If site launch options does not exist, stop.
const siteLaunchOptions = window.wpcomEditorSiteLaunch;
if ( ! siteLaunchOptions ) return;
// Don't proceed if this function has already run
if ( handled ) {
|
handled = true;
const awaitSettingsBar = setInterval( () => {
const settingsBar = document.querySelector( '.edit-post-header__settings' );
if ( ! settingsBar ) {
return;
}
clearInterval( awaitSettingsBar );
const body = document.querySelector( 'body' );
if ( ! body ) {
return;
}
const { launchFlow, isGutenboarding, anchorFmPodcastId } = siteLaunchOptions;
// Enable anchor-flavoured features (the launch button works immediately).
const isAnchorFm = !! anchorFmPodcastId;
// Display the Launch button only for the AnchorFM flow
if ( launchFlow !== GUTENBOARDING_LAUNCH_FLOW || ! isAnchorFm ) {
return;
}
// Wrap 'Launch' button link to control launch flow.
const launchButton = document.createElement( 'button' );
launchButton.className = 'editor-gutenberg-launch__launch-button components-button is-primary';
launchButton.addEventListener( 'click', ( e: Event ) => {
// Prevent default behaviour
e.preventDefault();
recordTracksEvent( 'calypso_newsite_editor_launch_click', {
is_new_site: !! isGutenboarding,
launch_flow: launchFlow,
is_in_iframe: inIframe(),
} );
if ( isAnchorFm ) {
dispatch( 'automattic/launch' ).enableAnchorFm();
}
const { savePost } = dispatch( 'core/editor' );
const delayedSavePost = () => setTimeout( () => savePost(), 1000 );
switch ( launchFlow ) {
case GUTENBOARDING_LAUNCH_FLOW:
// @TODO: remove this temporary solution once backend returns correct launch flow value
if ( isAnchorFm ) {
dispatch( 'automattic/launch' ).openFocusedLaunch();
break;
}
// Save post in the background while step-by-step flow opens
dispatch( 'automattic/launch' ).openSidebar();
delayedSavePost();
break;
}
} );
/*
* translators: "Launch" here refers to launching a whole site.
* Please translate differently from "Publish", which intstead
* refers to publishing a page.
*/
const textContent = document.createTextNode( __( 'Launch', 'full-site-editing' ) );
launchButton.appendChild( textContent );
body.classList.add( 'editor-gutenberg-launch__fse-overrides' );
// 'Update'/'Publish' primary button to become 'Save' tertiary button.
const saveButton = settingsBar.querySelector( '.editor-post-publish-button__button' );
// This line causes a reconciliation error in React and a page bork
// leaving it in there until we can decide on the UX for this component
// saveButton && ( saveButton.innerText = __( 'Save' ) );
// Put 'Launch' and 'Save' back on bar in desired order.
settingsBar.prepend( launchButton );
saveButton && settingsBar.prepend( saveButton );
} );
} );
|
return;
}
|
random_line_split
|
overflowing_mul.rs
|
use num::arithmetic::traits::{OverflowingMul, OverflowingMulAssign};
macro_rules! impl_overflowing_mul {
($t:ident) => {
impl OverflowingMul<$t> for $t {
type Output = $t;
#[inline]
fn overflowing_mul(self, other: $t) -> ($t, bool) {
$t::overflowing_mul(self, other)
}
}
|
/// Replaces `self` with `self * other`.
///
/// Returns a boolean indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred, then the wrapped value is assigned.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::overflowing_mul` module.
#[inline]
fn overflowing_mul_assign(&mut self, other: $t) -> bool {
let (result, overflow) = self.overflowing_mul(other);
*self = result;
overflow
}
}
};
}
apply_to_primitive_ints!(impl_overflowing_mul);
|
impl OverflowingMulAssign<$t> for $t {
|
random_line_split
|
main.rs
|
#![feature(plugin)]
#![allow(dead_code)]
#![allow(unused_variables)]
// error-chain can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate chrono;
extern crate markdown;
extern crate liquid;
extern crate walkdir;
extern crate rustc_serialize;
extern crate docopt;
extern crate inotify;
extern crate git2;
extern crate url;
use std::collections::HashMap;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::{self, File, OpenOptions};
use std::sync::mpsc::channel;
use std::thread;
use std::process::Command;
use std::default::Default;
use std::path::PathBuf;
use walkdir::WalkDir;
use liquid::Renderable;
use liquid::Context;
use liquid::Value;
use docopt::Docopt;
mod logger;
mod post;
mod site;
mod cmdline;
#[macro_use]
mod new_blog;
use logger::*;
use post::*;
use site::*;
use cmdline::{NOT_SILICA_SITE, USAGE};
use new_blog::{create_new_site, exists_config, create_new_post};
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain! { }
}
use errors::*;
#[derive(Debug, RustcDecodable)]
struct Args {
cmd_site: bool,
cmd_post: bool,
cmd_publish: bool,
cmd_serve: bool,
flag_draft: bool,
flag_version: bool,
flag_help: bool,
arg_sname: Vec<String>,
arg_pname: Vec<String>,
}
#[derive(Debug)]
pub enum State {
Metadata,
Content,
WeGood,
MarkdownParseError,
NotValidSite,
IOError,
}
enum SilicaParseError {
ConfigFile,
NotASite,
Other,
}
fn watch() {
let site = Site::new();
let (tx, rx) = channel();
thread::spawn(move || {
site.watch_changes(tx.clone());
});
println!("Watching for changes");
match rx.recv().unwrap() {
Events::Modified => {
let _ = publish("./");
serve()
}
_ => println!("I got nothing"),
}
}
fn serve() {
if !exists_config("./config.toml") {
return log_err(NOT_SILICA_SITE);
}
Command::new("pkill")
.arg("python")
.output()
.unwrap_or_else(|e| panic!("failed to run Web Server: {}", e));
let mut child = Command::new("python")
.arg("-m")
.arg("http.server")
.spawn()
.unwrap_or_else(|e| panic!("failed to run Web Server: {}", e));
// watch for file event changes
// this calls the site's watch_changes method which spawns another thread and receives a
// a signal of file changes, back to main thread, and on receiving the main thread
// does a match and calls the serve publish command again, which restarts the server.
watch();
let ecode = child.wait()
.unwrap_or_else(|e| panic!("failed to wait on child: {}", e));
println!("Child Exited with {:?}", ecode);
}
// TODO decouple roles here maybe ?
fn publish(base: &str) -> Result<()> {
assert_valid_site!();
let mut config_map = HashMap::new();
let mut posts: Vec<Post> = vec![];
let mut path_post = PathBuf::new();
path_post.push(base);
path_post.push("content");
path_post.push("posts");
let mut site = Site::new();
let has_md_ext = |ext: &walkdir::DirEntry| ext.path().extension().unwrap() == "md";
// TODO use this when we have better idea on basic properties of a Silica Site
let _site_configs = || -> Result<HashMap<String, String>> {
let lines = BufReader::new(File::open("./silica.toml").unwrap()).lines();
for line in lines {
let line_content = line.unwrap();
let v: Vec<&str> = line_content.split("=").collect();
if v.len() == 2 {
config_map.insert(v[0].trim().to_owned(), v[1].trim().to_owned());
}
}
Ok(config_map)
};
for entry in WalkDir::new(path_post) {
let entry = entry.unwrap();
if !entry.path().is_dir() && has_md_ext(&entry) {
let current_file = entry.path().to_str().unwrap();
match File::open(current_file) {
Ok(ref mut f) => {
log_info(&format!("Processing {:?}", current_file));
let mut md_string = String::new();
let _ = f.read_to_string(&mut md_string);
match parse_md(md_string) {
Ok(post) => posts.push(post),
Err(_) => bail!("Markdown Parse Error")
}
}
Err(_) => bail!("Markdown Parse Error"),
}
} else {
log_warn("Some non-markdown files discovered");
}
}
site.posts(posts);
match fs::metadata("./build") {
Ok(_) => log_warn("Exists: Ignoring folder creation"),
Err(_) => {let _ = fs::create_dir("./build");}
}
let mut index_page = String::new();
index_page.push_str("./build/");
index_page.push_str("index.html");
match File::create(&index_page) {
Ok(mut buffer) => {
let mut site_template = OpenOptions::new().read(true).open("../base/base_theme.html").unwrap();
let mut base_theme_buff: Vec<u8> = Vec::new();
site_template.read_to_end(&mut base_theme_buff).unwrap();
let base_theme_buff = String::from_utf8(base_theme_buff).unwrap();
let _ = buffer.write_all((&base_theme_buff[..]).as_bytes());
let mut liquid_posts = vec![];
if let Some(ref posts) = *site.get_posts() {
for p in posts {
liquid_posts.push(Value::Str(p.get_content()))
}
}
let template = liquid::parse(&base_theme_buff, Default::default()).unwrap();
let mut cx = Context::new();
cx.set_val("posts", Value::Array(liquid_posts));
let output = template.render(&mut cx).unwrap().unwrap();
let mut output_slice = output.as_bytes();
let _ = buffer.write_all(&mut output_slice);
}
Err(_) => bail!("Error transpiling markdown to HTML")
}
Ok(())
}
fn process_cmd(args: &Args) -> Result<()> {
if args.cmd_site {
create_new_site(args.arg_sname.first().unwrap())
} else if args.cmd_post {
let mut as_draft: bool = false;
if args.flag_draft {
as_draft = true;
}
let post_name = args.arg_pname[0].clone();
let _ = create_new_post(&post_name, as_draft);
} else if args.cmd_publish {
match publish("./") {
Err(what) => bail!("Something's wrong: {:?}", what),
Ok(_) => {
log_info("Your shiny new site lives in `build` folder.\nHave a great day.");
}
}
} else if args.cmd_serve {
serve()
} else if args.flag_help {
println!("{}", USAGE);
}
Ok(())
}
// The entry point for silica. Parses command line arguments and acts accordingly
fn main() {
let args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
if let Err(ref e) = process_cmd(&args) {
use ::std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "error: {}", e).expect(errmsg);
for e in e.iter().skip(1) {
writeln!(stderr, "caused by: {}", e).expect(errmsg);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg);
}
::std::process::exit(1);
}
}
#[cfg(test)]
mod test {
use {bootstrap, init_post};
#[test]
fn
|
() {
use std::path::Path;
use std::fs;
let site_dir = Path::new("./blog");
let site_config_file = Path::new("./blog/config.toml");
bootstrap("blog");
assert_eq!(true, site_dir.is_dir());
assert_eq!(true, site_config_file.exists());
fs::remove_dir_all("./blog").unwrap();
}
#[test]
fn test_init_post() {
use std::path::Path;
use std::fs;
init_post("intro.md", false);
let post_md = Path::new("./intro.md");
assert_eq!(true, post_md.exists());
fs::remove_file("./intro.md").unwrap();
}
}
|
test_create_site
|
identifier_name
|
main.rs
|
#![feature(plugin)]
#![allow(dead_code)]
#![allow(unused_variables)]
// error-chain can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate chrono;
extern crate markdown;
extern crate liquid;
extern crate walkdir;
extern crate rustc_serialize;
extern crate docopt;
extern crate inotify;
extern crate git2;
extern crate url;
use std::collections::HashMap;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::{self, File, OpenOptions};
use std::sync::mpsc::channel;
use std::thread;
use std::process::Command;
use std::default::Default;
use std::path::PathBuf;
use walkdir::WalkDir;
use liquid::Renderable;
use liquid::Context;
use liquid::Value;
use docopt::Docopt;
mod logger;
mod post;
mod site;
mod cmdline;
#[macro_use]
mod new_blog;
use logger::*;
use post::*;
use site::*;
use cmdline::{NOT_SILICA_SITE, USAGE};
use new_blog::{create_new_site, exists_config, create_new_post};
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain! { }
}
use errors::*;
#[derive(Debug, RustcDecodable)]
struct Args {
cmd_site: bool,
cmd_post: bool,
cmd_publish: bool,
cmd_serve: bool,
flag_draft: bool,
flag_version: bool,
flag_help: bool,
arg_sname: Vec<String>,
arg_pname: Vec<String>,
}
#[derive(Debug)]
|
Metadata,
Content,
WeGood,
MarkdownParseError,
NotValidSite,
IOError,
}
enum SilicaParseError {
ConfigFile,
NotASite,
Other,
}
fn watch() {
let site = Site::new();
let (tx, rx) = channel();
thread::spawn(move || {
site.watch_changes(tx.clone());
});
println!("Watching for changes");
match rx.recv().unwrap() {
Events::Modified => {
let _ = publish("./");
serve()
}
_ => println!("I got nothing"),
}
}
fn serve() {
if !exists_config("./config.toml") {
return log_err(NOT_SILICA_SITE);
}
Command::new("pkill")
.arg("python")
.output()
.unwrap_or_else(|e| panic!("failed to run Web Server: {}", e));
let mut child = Command::new("python")
.arg("-m")
.arg("http.server")
.spawn()
.unwrap_or_else(|e| panic!("failed to run Web Server: {}", e));
// watch for file event changes
// this calls the site's watch_changes method which spawns another thread and receives a
// a signal of file changes, back to main thread, and on receiving the main thread
// does a match and calls the serve publish command again, which restarts the server.
watch();
let ecode = child.wait()
.unwrap_or_else(|e| panic!("failed to wait on child: {}", e));
println!("Child Exited with {:?}", ecode);
}
// TODO decouple roles here maybe ?
fn publish(base: &str) -> Result<()> {
assert_valid_site!();
let mut config_map = HashMap::new();
let mut posts: Vec<Post> = vec![];
let mut path_post = PathBuf::new();
path_post.push(base);
path_post.push("content");
path_post.push("posts");
let mut site = Site::new();
let has_md_ext = |ext: &walkdir::DirEntry| ext.path().extension().unwrap() == "md";
// TODO use this when we have better idea on basic properties of a Silica Site
let _site_configs = || -> Result<HashMap<String, String>> {
let lines = BufReader::new(File::open("./silica.toml").unwrap()).lines();
for line in lines {
let line_content = line.unwrap();
let v: Vec<&str> = line_content.split("=").collect();
if v.len() == 2 {
config_map.insert(v[0].trim().to_owned(), v[1].trim().to_owned());
}
}
Ok(config_map)
};
for entry in WalkDir::new(path_post) {
let entry = entry.unwrap();
if !entry.path().is_dir() && has_md_ext(&entry) {
let current_file = entry.path().to_str().unwrap();
match File::open(current_file) {
Ok(ref mut f) => {
log_info(&format!("Processing {:?}", current_file));
let mut md_string = String::new();
let _ = f.read_to_string(&mut md_string);
match parse_md(md_string) {
Ok(post) => posts.push(post),
Err(_) => bail!("Markdown Parse Error")
}
}
Err(_) => bail!("Markdown Parse Error"),
}
} else {
log_warn("Some non-markdown files discovered");
}
}
site.posts(posts);
match fs::metadata("./build") {
Ok(_) => log_warn("Exists: Ignoring folder creation"),
Err(_) => {let _ = fs::create_dir("./build");}
}
let mut index_page = String::new();
index_page.push_str("./build/");
index_page.push_str("index.html");
match File::create(&index_page) {
Ok(mut buffer) => {
let mut site_template = OpenOptions::new().read(true).open("../base/base_theme.html").unwrap();
let mut base_theme_buff: Vec<u8> = Vec::new();
site_template.read_to_end(&mut base_theme_buff).unwrap();
let base_theme_buff = String::from_utf8(base_theme_buff).unwrap();
let _ = buffer.write_all((&base_theme_buff[..]).as_bytes());
let mut liquid_posts = vec![];
if let Some(ref posts) = *site.get_posts() {
for p in posts {
liquid_posts.push(Value::Str(p.get_content()))
}
}
let template = liquid::parse(&base_theme_buff, Default::default()).unwrap();
let mut cx = Context::new();
cx.set_val("posts", Value::Array(liquid_posts));
let output = template.render(&mut cx).unwrap().unwrap();
let mut output_slice = output.as_bytes();
let _ = buffer.write_all(&mut output_slice);
}
Err(_) => bail!("Error transpiling markdown to HTML")
}
Ok(())
}
fn process_cmd(args: &Args) -> Result<()> {
if args.cmd_site {
create_new_site(args.arg_sname.first().unwrap())
} else if args.cmd_post {
let mut as_draft: bool = false;
if args.flag_draft {
as_draft = true;
}
let post_name = args.arg_pname[0].clone();
let _ = create_new_post(&post_name, as_draft);
} else if args.cmd_publish {
match publish("./") {
Err(what) => bail!("Something's wrong: {:?}", what),
Ok(_) => {
log_info("Your shiny new site lives in `build` folder.\nHave a great day.");
}
}
} else if args.cmd_serve {
serve()
} else if args.flag_help {
println!("{}", USAGE);
}
Ok(())
}
// The entry point for silica. Parses command line arguments and acts accordingly
fn main() {
let args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
if let Err(ref e) = process_cmd(&args) {
use ::std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "error: {}", e).expect(errmsg);
for e in e.iter().skip(1) {
writeln!(stderr, "caused by: {}", e).expect(errmsg);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg);
}
::std::process::exit(1);
}
}
#[cfg(test)]
mod test {
use {bootstrap, init_post};
#[test]
fn test_create_site() {
use std::path::Path;
use std::fs;
let site_dir = Path::new("./blog");
let site_config_file = Path::new("./blog/config.toml");
bootstrap("blog");
assert_eq!(true, site_dir.is_dir());
assert_eq!(true, site_config_file.exists());
fs::remove_dir_all("./blog").unwrap();
}
#[test]
fn test_init_post() {
use std::path::Path;
use std::fs;
init_post("intro.md", false);
let post_md = Path::new("./intro.md");
assert_eq!(true, post_md.exists());
fs::remove_file("./intro.md").unwrap();
}
}
|
pub enum State {
|
random_line_split
|
main.rs
|
#![feature(plugin)]
#![allow(dead_code)]
#![allow(unused_variables)]
// error-chain can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate chrono;
extern crate markdown;
extern crate liquid;
extern crate walkdir;
extern crate rustc_serialize;
extern crate docopt;
extern crate inotify;
extern crate git2;
extern crate url;
use std::collections::HashMap;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::{self, File, OpenOptions};
use std::sync::mpsc::channel;
use std::thread;
use std::process::Command;
use std::default::Default;
use std::path::PathBuf;
use walkdir::WalkDir;
use liquid::Renderable;
use liquid::Context;
use liquid::Value;
use docopt::Docopt;
mod logger;
mod post;
mod site;
mod cmdline;
#[macro_use]
mod new_blog;
use logger::*;
use post::*;
use site::*;
use cmdline::{NOT_SILICA_SITE, USAGE};
use new_blog::{create_new_site, exists_config, create_new_post};
mod errors {
// Create the Error, ErrorKind, ResultExt, and Result types
error_chain! { }
}
use errors::*;
#[derive(Debug, RustcDecodable)]
struct Args {
cmd_site: bool,
cmd_post: bool,
cmd_publish: bool,
cmd_serve: bool,
flag_draft: bool,
flag_version: bool,
flag_help: bool,
arg_sname: Vec<String>,
arg_pname: Vec<String>,
}
#[derive(Debug)]
pub enum State {
Metadata,
Content,
WeGood,
MarkdownParseError,
NotValidSite,
IOError,
}
enum SilicaParseError {
ConfigFile,
NotASite,
Other,
}
fn watch() {
let site = Site::new();
let (tx, rx) = channel();
thread::spawn(move || {
site.watch_changes(tx.clone());
});
println!("Watching for changes");
match rx.recv().unwrap() {
Events::Modified => {
let _ = publish("./");
serve()
}
_ => println!("I got nothing"),
}
}
fn serve() {
if !exists_config("./config.toml") {
return log_err(NOT_SILICA_SITE);
}
Command::new("pkill")
.arg("python")
.output()
.unwrap_or_else(|e| panic!("failed to run Web Server: {}", e));
let mut child = Command::new("python")
.arg("-m")
.arg("http.server")
.spawn()
.unwrap_or_else(|e| panic!("failed to run Web Server: {}", e));
// watch for file event changes
// this calls the site's watch_changes method which spawns another thread and receives a
// a signal of file changes, back to main thread, and on receiving the main thread
// does a match and calls the serve publish command again, which restarts the server.
watch();
let ecode = child.wait()
.unwrap_or_else(|e| panic!("failed to wait on child: {}", e));
println!("Child Exited with {:?}", ecode);
}
// TODO decouple roles here maybe ?
fn publish(base: &str) -> Result<()> {
assert_valid_site!();
let mut config_map = HashMap::new();
let mut posts: Vec<Post> = vec![];
let mut path_post = PathBuf::new();
path_post.push(base);
path_post.push("content");
path_post.push("posts");
let mut site = Site::new();
let has_md_ext = |ext: &walkdir::DirEntry| ext.path().extension().unwrap() == "md";
// TODO use this when we have better idea on basic properties of a Silica Site
let _site_configs = || -> Result<HashMap<String, String>> {
let lines = BufReader::new(File::open("./silica.toml").unwrap()).lines();
for line in lines {
let line_content = line.unwrap();
let v: Vec<&str> = line_content.split("=").collect();
if v.len() == 2 {
config_map.insert(v[0].trim().to_owned(), v[1].trim().to_owned());
}
}
Ok(config_map)
};
for entry in WalkDir::new(path_post) {
let entry = entry.unwrap();
if !entry.path().is_dir() && has_md_ext(&entry) {
let current_file = entry.path().to_str().unwrap();
match File::open(current_file) {
Ok(ref mut f) => {
log_info(&format!("Processing {:?}", current_file));
let mut md_string = String::new();
let _ = f.read_to_string(&mut md_string);
match parse_md(md_string) {
Ok(post) => posts.push(post),
Err(_) => bail!("Markdown Parse Error")
}
}
Err(_) => bail!("Markdown Parse Error"),
}
} else {
log_warn("Some non-markdown files discovered");
}
}
site.posts(posts);
match fs::metadata("./build") {
Ok(_) => log_warn("Exists: Ignoring folder creation"),
Err(_) => {let _ = fs::create_dir("./build");}
}
let mut index_page = String::new();
index_page.push_str("./build/");
index_page.push_str("index.html");
match File::create(&index_page) {
Ok(mut buffer) => {
let mut site_template = OpenOptions::new().read(true).open("../base/base_theme.html").unwrap();
let mut base_theme_buff: Vec<u8> = Vec::new();
site_template.read_to_end(&mut base_theme_buff).unwrap();
let base_theme_buff = String::from_utf8(base_theme_buff).unwrap();
let _ = buffer.write_all((&base_theme_buff[..]).as_bytes());
let mut liquid_posts = vec![];
if let Some(ref posts) = *site.get_posts() {
for p in posts {
liquid_posts.push(Value::Str(p.get_content()))
}
}
let template = liquid::parse(&base_theme_buff, Default::default()).unwrap();
let mut cx = Context::new();
cx.set_val("posts", Value::Array(liquid_posts));
let output = template.render(&mut cx).unwrap().unwrap();
let mut output_slice = output.as_bytes();
let _ = buffer.write_all(&mut output_slice);
}
Err(_) => bail!("Error transpiling markdown to HTML")
}
Ok(())
}
fn process_cmd(args: &Args) -> Result<()> {
if args.cmd_site {
create_new_site(args.arg_sname.first().unwrap())
} else if args.cmd_post {
let mut as_draft: bool = false;
if args.flag_draft {
as_draft = true;
}
let post_name = args.arg_pname[0].clone();
let _ = create_new_post(&post_name, as_draft);
} else if args.cmd_publish {
match publish("./") {
Err(what) => bail!("Something's wrong: {:?}", what),
Ok(_) => {
log_info("Your shiny new site lives in `build` folder.\nHave a great day.");
}
}
} else if args.cmd_serve {
serve()
} else if args.flag_help
|
Ok(())
}
// The entry point for silica. Parses command line arguments and acts accordingly
fn main() {
let args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
if let Err(ref e) = process_cmd(&args) {
use ::std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "error: {}", e).expect(errmsg);
for e in e.iter().skip(1) {
writeln!(stderr, "caused by: {}", e).expect(errmsg);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg);
}
::std::process::exit(1);
}
}
#[cfg(test)]
mod test {
use {bootstrap, init_post};
#[test]
fn test_create_site() {
use std::path::Path;
use std::fs;
let site_dir = Path::new("./blog");
let site_config_file = Path::new("./blog/config.toml");
bootstrap("blog");
assert_eq!(true, site_dir.is_dir());
assert_eq!(true, site_config_file.exists());
fs::remove_dir_all("./blog").unwrap();
}
#[test]
fn test_init_post() {
use std::path::Path;
use std::fs;
init_post("intro.md", false);
let post_md = Path::new("./intro.md");
assert_eq!(true, post_md.exists());
fs::remove_file("./intro.md").unwrap();
}
}
|
{
println!("{}", USAGE);
}
|
conditional_block
|
bookshelf.js
|
'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
// All core modules required for the bookshelf instance.
const BookshelfModel = require('./model');
const BookshelfCollection = require('./collection');
const BookshelfRelation = require('./relation');
const Errors = require('./errors');
/**
* @class Bookshelf
* @classdesc
*
* The Bookshelf library is initialized by passing an initialized Knex client
* instance. The knex documentation provides a number of examples for different
* databases.
*
* @constructor
* @param {Knex} knex Knex instance.
*/
function Bookshelf(knex) {
if (!knex || knex.name !== 'knex')
|
const bookshelf = {
VERSION: require('../package.json').version
};
const Model = (bookshelf.Model = BookshelfModel.extend(
{
_builder: builderFn,
// The `Model` constructor is referenced as a property on the `Bookshelf`
// instance, mixing in the correct `builder` method, as well as the
// `relation` method, passing in the correct `Model` & `Collection`
// constructors for later reference.
_relation(type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error(
'A valid target model must be defined for the ' + _.result(this, 'tableName') + ' ' + type + ' relation'
);
}
return new Relation(type, Target, options);
}
},
{
/**
* @method Model.forge
* @belongsTo Model
* @description
*
* A simple helper function to instantiate a new Model without needing `new`.
*
* @param {Object=} attributes Initial values for this model's attributes.
* @param {Object=} options Hash of options.
* @param {string=} options.tableName Initial value for {@linkcode Model#tableName tableName}.
* @param {Boolean=} [options.hasTimestamps=false]
*
* Initial value for {@linkcode Model#hasTimestamps hasTimestamps}.
*
* @param {Boolean} [options.parse=false]
*
* Convert attributes by {@linkcode Model#parse parse} before being
* {@linkcode Model#set set} on the `model`.
*/
forge: function forge(attributes, options) {
return new this(attributes, options);
},
/**
* @method Model.collection
* @belongsTo Model
* @description
*
* A simple static helper to instantiate a new {@link Collection}, setting
* the current `model` as the collection's target.
*
* @example
*
* Customer.collection().fetch().then(function(collection) {
* // ...
* });
*
* @param {(Model[])=} models
* @param {Object=} options
* @returns {Collection}
*/
collection(models, options) {
return new bookshelf.Collection(models || [], _.extend({}, options, {model: this}));
},
/**
* @method Model.count
* @belongsTo Model
* @since 0.8.2
* @description
*
* Gets the number of matching records in the database, respecting any
* previous calls to {@link Model#query query}. If a `column` is provided,
* records with a null value in that column will be excluded from the count.
*
* @param {string} [column='*']
* Specify a column to count - rows with null values in this column will be excluded.
* @param {Object=} options
* Hash of options.
* @returns {Promise<Number>}
* A promise resolving to the number of matching rows.
*/
count(column, options) {
return this.forge().count(column, options);
},
/**
* @method Model.fetchAll
* @belongsTo Model
* @description
*
* Simple helper function for retrieving all instances of the given model.
*
* @see Model#fetchAll
* @returns {Promise<Collection>}
*/
fetchAll(options) {
return this.forge().fetchAll(options);
}
}
));
const Collection = (bookshelf.Collection = BookshelfCollection.extend(
{
_builder: builderFn
},
{
/**
* @method Collection.forge
* @belongsTo Collection
* @description
*
* A simple helper function to instantiate a new Collection without needing
* new.
*
* @param {(Object[]|Model[])=} [models]
* Set of models (or attribute hashes) with which to initialize the
* collection.
* @param {Object} options Hash of options.
*
* @example
*
* var Promise = require('bluebird');
* var Accounts = bookshelf.Collection.extend({
* model: Account
* });
*
* var accounts = Accounts.forge([
* {name: 'Person1'},
* {name: 'Person2'}
* ]);
*
* Promise.all(accounts.invokeMap('save')).then(function() {
* // collection models should now be saved...
* });
*/
forge: function forge(models, options) {
return new this(models, options);
}
}
));
// The collection also references the correct `Model`, specified above, for
// creating new `Model` instances in the collection.
Collection.prototype.model = Model;
Model.prototype.Collection = Collection;
const Relation = BookshelfRelation.extend({Model, Collection});
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes
// in the `Events` object. It also contains the version number, and a
// `Transaction` method referencing the correct version of `knex` passed into
// the object.
_.extend(bookshelf, Events, Errors, {
/**
* @method Bookshelf#transaction
* @memberOf Bookshelf
* @description
*
* An alias to `{@link http://knexjs.org/#Transactions
* Knex#transaction}`, the `transaction` object must be passed along in the
* options of any relevant Bookshelf calls, to ensure all queries are on the
* same connection. The entire transaction block is a promise that will
* resolve when the transaction is committed, or fail if the transaction is
* rolled back.
*
* When fetching inside a transaction it's possible to specify a row-level
* lock by passing the wanted lock type in the `lock` option to
* {@linkcode Model#fetch fetch}. Available options are `forUpdate` and
* `forShare`.
*
* var Promise = require('bluebird');
*
* Bookshelf.transaction(function(t) {
* return new Library({name: 'Old Books'})
* .save(null, {transacting: t})
* .tap(function(model) {
* return Promise.map([
* {title: 'Canterbury Tales'},
* {title: 'Moby Dick'},
* {title: 'Hamlet'}
* ], function(info) {
* // Some validation could take place here.
* return new Book(info).save({'shelf_id': model.id}, {transacting: t});
* });
* });
* }).then(function(library) {
* console.log(library.related('books').pluck('title'));
* }).catch(function(err) {
* console.error(err);
* });
*
* @param {Bookshelf~transactionCallback} transactionCallback
* Callback containing transaction logic. The callback should return a
* promise.
*
* @returns {Promise<mixed>}
* A promise resolving to the value returned from {@link
* Bookshelf~transactionCallback transactionCallback}.
*/
transaction() {
return this.knex.transaction.apply(this.knex, arguments);
},
/**
* @callback Bookshelf~transactionCallback
* @description
*
* A transaction block to be provided to {@link Bookshelf#transaction}.
*
* @see {@link http://knexjs.org/#Transactions Knex#transaction}
* @see Bookshelf#transaction
*
* @param {Transaction} transaction
* @returns {Promise<mixed>}
*/
/**
* @method Bookshelf#plugin
* @memberOf Bookshelf
* @description
*
* This method provides a nice, tested, standardized way of adding plugins
* to a `Bookshelf` instance, injecting the current instance into the
* plugin, which should be a `module.exports`.
*
* You can add a plugin by specifying a string with the name of the plugin
* to load. In this case it will try to find a module. It will first check
* for a match within the `bookshelf/plugins` directory. If nothing is
* found it will pass the string to `require()`, so you can either require
* an npm dependency by name or one of your own modules by relative path:
*
* bookshelf.plugin('./bookshelf-plugins/my-favourite-plugin');
* bookshelf.plugin('plugin-from-npm');
*
* There are a few built-in plugins already, along with many independently
* developed ones. See [the list of available plugins](#plugins).
*
* You can also provide an array of strings or functions, which is the same
* as calling `bookshelf.plugin()` multiple times. In this case the same
* options object will be reused:
*
* bookshelf.plugin(['registry', './my-plugins/special-parse-format']);
*
* Example plugin:
*
* // Converts all string values to lower case when setting attributes on a model
* module.exports = function(bookshelf) {
* bookshelf.Model = bookshelf.Model.extend({
* set: function(key, value, options) {
* if (!key) return this;
* if (typeof value === 'string') value = value.toLowerCase();
* return bookshelf.Model.prototype.set.call(this, key, value, options);
* }
* });
* }
*
* @param {string|array|Function} plugin
* The plugin or plugins to add. If you provide a string it can
* represent a built-in plugin, an npm package or a file somewhere on
* your project. You can also pass a function as argument to add it as a
* plugin. Finally, it's also possible to pass an array of strings or
* functions to add them all at once.
* @param {mixed} options
* This can be anything you want and it will be passed directly to the
* plugin as the second argument when loading it.
*/
plugin(plugin, options) {
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
if (!process.browser) {
require(plugin)(this, options);
}
}
} else if (Array.isArray(plugin)) {
plugin.forEach((p) => this.plugin(p, options));
} else {
plugin(this, options);
}
return this;
}
});
/**
* @member Bookshelf#knex
* @memberOf Bookshelf
* @type {Knex}
* @description
* A reference to the {@link http://knexjs.org Knex.js} instance being used by Bookshelf.
*/
bookshelf.knex = knex;
function builderFn(tableNameOrBuilder) {
let builder = null;
if (_.isString(tableNameOrBuilder)) {
builder = bookshelf.knex(tableNameOrBuilder);
} else if (tableNameOrBuilder == null) {
builder = bookshelf.knex.queryBuilder();
} else {
// Assuming here that `tableNameOrBuilder` is a QueryBuilder instance. Not
// aware of a way to check that this is the case (ie. using
// `Knex.isQueryBuilder` or equivalent).
builder = tableNameOrBuilder;
}
return builder.on('query', (data) => this.trigger('query', data));
}
// Attach `where`, `query`, and `fetchAll` as static methods.
['where', 'query'].forEach((method) => {
Model[method] = Collection[method] = function() {
const model = this.forge();
return model[method].apply(model, arguments);
};
});
return bookshelf;
}
// Constructor for a new `Bookshelf` object, it accepts an active `knex`
// instance and initializes the appropriate `Model` and `Collection`
// constructors for use in the current instance.
Bookshelf.initialize = function(knex) {
helpers.warn("Bookshelf.initialize is deprecated, pass knex directly: require('bookshelf')(knex)");
return new Bookshelf(knex);
};
module.exports = Bookshelf;
|
{
throw new Error('Invalid knex instance');
}
|
conditional_block
|
bookshelf.js
|
'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
// All core modules required for the bookshelf instance.
const BookshelfModel = require('./model');
const BookshelfCollection = require('./collection');
const BookshelfRelation = require('./relation');
const Errors = require('./errors');
/**
* @class Bookshelf
* @classdesc
*
* The Bookshelf library is initialized by passing an initialized Knex client
* instance. The knex documentation provides a number of examples for different
* databases.
*
* @constructor
* @param {Knex} knex Knex instance.
*/
function Bookshelf(knex) {
if (!knex || knex.name !== 'knex') {
throw new Error('Invalid knex instance');
}
const bookshelf = {
VERSION: require('../package.json').version
};
const Model = (bookshelf.Model = BookshelfModel.extend(
{
_builder: builderFn,
// The `Model` constructor is referenced as a property on the `Bookshelf`
// instance, mixing in the correct `builder` method, as well as the
// `relation` method, passing in the correct `Model` & `Collection`
// constructors for later reference.
|
(type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error(
'A valid target model must be defined for the ' + _.result(this, 'tableName') + ' ' + type + ' relation'
);
}
return new Relation(type, Target, options);
}
},
{
/**
* @method Model.forge
* @belongsTo Model
* @description
*
* A simple helper function to instantiate a new Model without needing `new`.
*
* @param {Object=} attributes Initial values for this model's attributes.
* @param {Object=} options Hash of options.
* @param {string=} options.tableName Initial value for {@linkcode Model#tableName tableName}.
* @param {Boolean=} [options.hasTimestamps=false]
*
* Initial value for {@linkcode Model#hasTimestamps hasTimestamps}.
*
* @param {Boolean} [options.parse=false]
*
* Convert attributes by {@linkcode Model#parse parse} before being
* {@linkcode Model#set set} on the `model`.
*/
forge: function forge(attributes, options) {
return new this(attributes, options);
},
/**
* @method Model.collection
* @belongsTo Model
* @description
*
* A simple static helper to instantiate a new {@link Collection}, setting
* the current `model` as the collection's target.
*
* @example
*
* Customer.collection().fetch().then(function(collection) {
* // ...
* });
*
* @param {(Model[])=} models
* @param {Object=} options
* @returns {Collection}
*/
collection(models, options) {
return new bookshelf.Collection(models || [], _.extend({}, options, {model: this}));
},
/**
* @method Model.count
* @belongsTo Model
* @since 0.8.2
* @description
*
* Gets the number of matching records in the database, respecting any
* previous calls to {@link Model#query query}. If a `column` is provided,
* records with a null value in that column will be excluded from the count.
*
* @param {string} [column='*']
* Specify a column to count - rows with null values in this column will be excluded.
* @param {Object=} options
* Hash of options.
* @returns {Promise<Number>}
* A promise resolving to the number of matching rows.
*/
count(column, options) {
return this.forge().count(column, options);
},
/**
* @method Model.fetchAll
* @belongsTo Model
* @description
*
* Simple helper function for retrieving all instances of the given model.
*
* @see Model#fetchAll
* @returns {Promise<Collection>}
*/
fetchAll(options) {
return this.forge().fetchAll(options);
}
}
));
const Collection = (bookshelf.Collection = BookshelfCollection.extend(
{
_builder: builderFn
},
{
/**
* @method Collection.forge
* @belongsTo Collection
* @description
*
* A simple helper function to instantiate a new Collection without needing
* new.
*
* @param {(Object[]|Model[])=} [models]
* Set of models (or attribute hashes) with which to initialize the
* collection.
* @param {Object} options Hash of options.
*
* @example
*
* var Promise = require('bluebird');
* var Accounts = bookshelf.Collection.extend({
* model: Account
* });
*
* var accounts = Accounts.forge([
* {name: 'Person1'},
* {name: 'Person2'}
* ]);
*
* Promise.all(accounts.invokeMap('save')).then(function() {
* // collection models should now be saved...
* });
*/
forge: function forge(models, options) {
return new this(models, options);
}
}
));
// The collection also references the correct `Model`, specified above, for
// creating new `Model` instances in the collection.
Collection.prototype.model = Model;
Model.prototype.Collection = Collection;
const Relation = BookshelfRelation.extend({Model, Collection});
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes
// in the `Events` object. It also contains the version number, and a
// `Transaction` method referencing the correct version of `knex` passed into
// the object.
_.extend(bookshelf, Events, Errors, {
/**
* @method Bookshelf#transaction
* @memberOf Bookshelf
* @description
*
* An alias to `{@link http://knexjs.org/#Transactions
* Knex#transaction}`, the `transaction` object must be passed along in the
* options of any relevant Bookshelf calls, to ensure all queries are on the
* same connection. The entire transaction block is a promise that will
* resolve when the transaction is committed, or fail if the transaction is
* rolled back.
*
* When fetching inside a transaction it's possible to specify a row-level
* lock by passing the wanted lock type in the `lock` option to
* {@linkcode Model#fetch fetch}. Available options are `forUpdate` and
* `forShare`.
*
* var Promise = require('bluebird');
*
* Bookshelf.transaction(function(t) {
* return new Library({name: 'Old Books'})
* .save(null, {transacting: t})
* .tap(function(model) {
* return Promise.map([
* {title: 'Canterbury Tales'},
* {title: 'Moby Dick'},
* {title: 'Hamlet'}
* ], function(info) {
* // Some validation could take place here.
* return new Book(info).save({'shelf_id': model.id}, {transacting: t});
* });
* });
* }).then(function(library) {
* console.log(library.related('books').pluck('title'));
* }).catch(function(err) {
* console.error(err);
* });
*
* @param {Bookshelf~transactionCallback} transactionCallback
* Callback containing transaction logic. The callback should return a
* promise.
*
* @returns {Promise<mixed>}
* A promise resolving to the value returned from {@link
* Bookshelf~transactionCallback transactionCallback}.
*/
transaction() {
return this.knex.transaction.apply(this.knex, arguments);
},
/**
* @callback Bookshelf~transactionCallback
* @description
*
* A transaction block to be provided to {@link Bookshelf#transaction}.
*
* @see {@link http://knexjs.org/#Transactions Knex#transaction}
* @see Bookshelf#transaction
*
* @param {Transaction} transaction
* @returns {Promise<mixed>}
*/
/**
* @method Bookshelf#plugin
* @memberOf Bookshelf
* @description
*
* This method provides a nice, tested, standardized way of adding plugins
* to a `Bookshelf` instance, injecting the current instance into the
* plugin, which should be a `module.exports`.
*
* You can add a plugin by specifying a string with the name of the plugin
* to load. In this case it will try to find a module. It will first check
* for a match within the `bookshelf/plugins` directory. If nothing is
* found it will pass the string to `require()`, so you can either require
* an npm dependency by name or one of your own modules by relative path:
*
* bookshelf.plugin('./bookshelf-plugins/my-favourite-plugin');
* bookshelf.plugin('plugin-from-npm');
*
* There are a few built-in plugins already, along with many independently
* developed ones. See [the list of available plugins](#plugins).
*
* You can also provide an array of strings or functions, which is the same
* as calling `bookshelf.plugin()` multiple times. In this case the same
* options object will be reused:
*
* bookshelf.plugin(['registry', './my-plugins/special-parse-format']);
*
* Example plugin:
*
* // Converts all string values to lower case when setting attributes on a model
* module.exports = function(bookshelf) {
* bookshelf.Model = bookshelf.Model.extend({
* set: function(key, value, options) {
* if (!key) return this;
* if (typeof value === 'string') value = value.toLowerCase();
* return bookshelf.Model.prototype.set.call(this, key, value, options);
* }
* });
* }
*
* @param {string|array|Function} plugin
* The plugin or plugins to add. If you provide a string it can
* represent a built-in plugin, an npm package or a file somewhere on
* your project. You can also pass a function as argument to add it as a
* plugin. Finally, it's also possible to pass an array of strings or
* functions to add them all at once.
* @param {mixed} options
* This can be anything you want and it will be passed directly to the
* plugin as the second argument when loading it.
*/
plugin(plugin, options) {
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
if (!process.browser) {
require(plugin)(this, options);
}
}
} else if (Array.isArray(plugin)) {
plugin.forEach((p) => this.plugin(p, options));
} else {
plugin(this, options);
}
return this;
}
});
/**
* @member Bookshelf#knex
* @memberOf Bookshelf
* @type {Knex}
* @description
* A reference to the {@link http://knexjs.org Knex.js} instance being used by Bookshelf.
*/
bookshelf.knex = knex;
function builderFn(tableNameOrBuilder) {
let builder = null;
if (_.isString(tableNameOrBuilder)) {
builder = bookshelf.knex(tableNameOrBuilder);
} else if (tableNameOrBuilder == null) {
builder = bookshelf.knex.queryBuilder();
} else {
// Assuming here that `tableNameOrBuilder` is a QueryBuilder instance. Not
// aware of a way to check that this is the case (ie. using
// `Knex.isQueryBuilder` or equivalent).
builder = tableNameOrBuilder;
}
return builder.on('query', (data) => this.trigger('query', data));
}
// Attach `where`, `query`, and `fetchAll` as static methods.
['where', 'query'].forEach((method) => {
Model[method] = Collection[method] = function() {
const model = this.forge();
return model[method].apply(model, arguments);
};
});
return bookshelf;
}
// Constructor for a new `Bookshelf` object, it accepts an active `knex`
// instance and initializes the appropriate `Model` and `Collection`
// constructors for use in the current instance.
Bookshelf.initialize = function(knex) {
helpers.warn("Bookshelf.initialize is deprecated, pass knex directly: require('bookshelf')(knex)");
return new Bookshelf(knex);
};
module.exports = Bookshelf;
|
_relation
|
identifier_name
|
bookshelf.js
|
'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
// All core modules required for the bookshelf instance.
const BookshelfModel = require('./model');
const BookshelfCollection = require('./collection');
const BookshelfRelation = require('./relation');
const Errors = require('./errors');
/**
* @class Bookshelf
* @classdesc
*
* The Bookshelf library is initialized by passing an initialized Knex client
* instance. The knex documentation provides a number of examples for different
* databases.
*
* @constructor
* @param {Knex} knex Knex instance.
*/
function Bookshelf(knex) {
if (!knex || knex.name !== 'knex') {
throw new Error('Invalid knex instance');
}
const bookshelf = {
VERSION: require('../package.json').version
};
const Model = (bookshelf.Model = BookshelfModel.extend(
{
_builder: builderFn,
// The `Model` constructor is referenced as a property on the `Bookshelf`
// instance, mixing in the correct `builder` method, as well as the
// `relation` method, passing in the correct `Model` & `Collection`
// constructors for later reference.
_relation(type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error(
'A valid target model must be defined for the ' + _.result(this, 'tableName') + ' ' + type + ' relation'
);
}
return new Relation(type, Target, options);
}
},
{
/**
* @method Model.forge
* @belongsTo Model
* @description
*
* A simple helper function to instantiate a new Model without needing `new`.
*
* @param {Object=} attributes Initial values for this model's attributes.
* @param {Object=} options Hash of options.
* @param {string=} options.tableName Initial value for {@linkcode Model#tableName tableName}.
* @param {Boolean=} [options.hasTimestamps=false]
*
* Initial value for {@linkcode Model#hasTimestamps hasTimestamps}.
*
* @param {Boolean} [options.parse=false]
*
* Convert attributes by {@linkcode Model#parse parse} before being
* {@linkcode Model#set set} on the `model`.
*/
forge: function forge(attributes, options) {
return new this(attributes, options);
},
/**
* @method Model.collection
* @belongsTo Model
* @description
*
* A simple static helper to instantiate a new {@link Collection}, setting
* the current `model` as the collection's target.
*
* @example
*
* Customer.collection().fetch().then(function(collection) {
* // ...
* });
*
* @param {(Model[])=} models
* @param {Object=} options
* @returns {Collection}
*/
collection(models, options) {
return new bookshelf.Collection(models || [], _.extend({}, options, {model: this}));
},
/**
* @method Model.count
* @belongsTo Model
* @since 0.8.2
* @description
*
* Gets the number of matching records in the database, respecting any
* previous calls to {@link Model#query query}. If a `column` is provided,
* records with a null value in that column will be excluded from the count.
*
* @param {string} [column='*']
* Specify a column to count - rows with null values in this column will be excluded.
* @param {Object=} options
* Hash of options.
* @returns {Promise<Number>}
* A promise resolving to the number of matching rows.
*/
count(column, options) {
return this.forge().count(column, options);
},
/**
* @method Model.fetchAll
* @belongsTo Model
* @description
*
* Simple helper function for retrieving all instances of the given model.
*
* @see Model#fetchAll
* @returns {Promise<Collection>}
*/
fetchAll(options) {
return this.forge().fetchAll(options);
}
}
));
const Collection = (bookshelf.Collection = BookshelfCollection.extend(
{
_builder: builderFn
},
{
/**
* @method Collection.forge
* @belongsTo Collection
* @description
*
* A simple helper function to instantiate a new Collection without needing
* new.
*
* @param {(Object[]|Model[])=} [models]
* Set of models (or attribute hashes) with which to initialize the
* collection.
* @param {Object} options Hash of options.
*
* @example
*
* var Promise = require('bluebird');
* var Accounts = bookshelf.Collection.extend({
* model: Account
* });
*
* var accounts = Accounts.forge([
* {name: 'Person1'},
* {name: 'Person2'}
* ]);
*
* Promise.all(accounts.invokeMap('save')).then(function() {
* // collection models should now be saved...
* });
*/
forge: function forge(models, options) {
return new this(models, options);
}
}
));
// The collection also references the correct `Model`, specified above, for
// creating new `Model` instances in the collection.
Collection.prototype.model = Model;
Model.prototype.Collection = Collection;
const Relation = BookshelfRelation.extend({Model, Collection});
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes
// in the `Events` object. It also contains the version number, and a
// `Transaction` method referencing the correct version of `knex` passed into
// the object.
_.extend(bookshelf, Events, Errors, {
/**
* @method Bookshelf#transaction
* @memberOf Bookshelf
* @description
*
* An alias to `{@link http://knexjs.org/#Transactions
* Knex#transaction}`, the `transaction` object must be passed along in the
* options of any relevant Bookshelf calls, to ensure all queries are on the
* same connection. The entire transaction block is a promise that will
* resolve when the transaction is committed, or fail if the transaction is
* rolled back.
*
* When fetching inside a transaction it's possible to specify a row-level
* lock by passing the wanted lock type in the `lock` option to
* {@linkcode Model#fetch fetch}. Available options are `forUpdate` and
* `forShare`.
*
* var Promise = require('bluebird');
*
* Bookshelf.transaction(function(t) {
* return new Library({name: 'Old Books'})
* .save(null, {transacting: t})
* .tap(function(model) {
* return Promise.map([
* {title: 'Canterbury Tales'},
* {title: 'Moby Dick'},
* {title: 'Hamlet'}
* ], function(info) {
* // Some validation could take place here.
* return new Book(info).save({'shelf_id': model.id}, {transacting: t});
* });
* });
|
* }).catch(function(err) {
* console.error(err);
* });
*
* @param {Bookshelf~transactionCallback} transactionCallback
* Callback containing transaction logic. The callback should return a
* promise.
*
* @returns {Promise<mixed>}
* A promise resolving to the value returned from {@link
* Bookshelf~transactionCallback transactionCallback}.
*/
transaction() {
return this.knex.transaction.apply(this.knex, arguments);
},
/**
* @callback Bookshelf~transactionCallback
* @description
*
* A transaction block to be provided to {@link Bookshelf#transaction}.
*
* @see {@link http://knexjs.org/#Transactions Knex#transaction}
* @see Bookshelf#transaction
*
* @param {Transaction} transaction
* @returns {Promise<mixed>}
*/
/**
* @method Bookshelf#plugin
* @memberOf Bookshelf
* @description
*
* This method provides a nice, tested, standardized way of adding plugins
* to a `Bookshelf` instance, injecting the current instance into the
* plugin, which should be a `module.exports`.
*
* You can add a plugin by specifying a string with the name of the plugin
* to load. In this case it will try to find a module. It will first check
* for a match within the `bookshelf/plugins` directory. If nothing is
* found it will pass the string to `require()`, so you can either require
* an npm dependency by name or one of your own modules by relative path:
*
* bookshelf.plugin('./bookshelf-plugins/my-favourite-plugin');
* bookshelf.plugin('plugin-from-npm');
*
* There are a few built-in plugins already, along with many independently
* developed ones. See [the list of available plugins](#plugins).
*
* You can also provide an array of strings or functions, which is the same
* as calling `bookshelf.plugin()` multiple times. In this case the same
* options object will be reused:
*
* bookshelf.plugin(['registry', './my-plugins/special-parse-format']);
*
* Example plugin:
*
* // Converts all string values to lower case when setting attributes on a model
* module.exports = function(bookshelf) {
* bookshelf.Model = bookshelf.Model.extend({
* set: function(key, value, options) {
* if (!key) return this;
* if (typeof value === 'string') value = value.toLowerCase();
* return bookshelf.Model.prototype.set.call(this, key, value, options);
* }
* });
* }
*
* @param {string|array|Function} plugin
* The plugin or plugins to add. If you provide a string it can
* represent a built-in plugin, an npm package or a file somewhere on
* your project. You can also pass a function as argument to add it as a
* plugin. Finally, it's also possible to pass an array of strings or
* functions to add them all at once.
* @param {mixed} options
* This can be anything you want and it will be passed directly to the
* plugin as the second argument when loading it.
*/
plugin(plugin, options) {
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
if (!process.browser) {
require(plugin)(this, options);
}
}
} else if (Array.isArray(plugin)) {
plugin.forEach((p) => this.plugin(p, options));
} else {
plugin(this, options);
}
return this;
}
});
/**
* @member Bookshelf#knex
* @memberOf Bookshelf
* @type {Knex}
* @description
* A reference to the {@link http://knexjs.org Knex.js} instance being used by Bookshelf.
*/
bookshelf.knex = knex;
function builderFn(tableNameOrBuilder) {
let builder = null;
if (_.isString(tableNameOrBuilder)) {
builder = bookshelf.knex(tableNameOrBuilder);
} else if (tableNameOrBuilder == null) {
builder = bookshelf.knex.queryBuilder();
} else {
// Assuming here that `tableNameOrBuilder` is a QueryBuilder instance. Not
// aware of a way to check that this is the case (ie. using
// `Knex.isQueryBuilder` or equivalent).
builder = tableNameOrBuilder;
}
return builder.on('query', (data) => this.trigger('query', data));
}
// Attach `where`, `query`, and `fetchAll` as static methods.
['where', 'query'].forEach((method) => {
Model[method] = Collection[method] = function() {
const model = this.forge();
return model[method].apply(model, arguments);
};
});
return bookshelf;
}
// Constructor for a new `Bookshelf` object, it accepts an active `knex`
// instance and initializes the appropriate `Model` and `Collection`
// constructors for use in the current instance.
Bookshelf.initialize = function(knex) {
helpers.warn("Bookshelf.initialize is deprecated, pass knex directly: require('bookshelf')(knex)");
return new Bookshelf(knex);
};
module.exports = Bookshelf;
|
* }).then(function(library) {
* console.log(library.related('books').pluck('title'));
|
random_line_split
|
bookshelf.js
|
'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
// All core modules required for the bookshelf instance.
const BookshelfModel = require('./model');
const BookshelfCollection = require('./collection');
const BookshelfRelation = require('./relation');
const Errors = require('./errors');
/**
* @class Bookshelf
* @classdesc
*
* The Bookshelf library is initialized by passing an initialized Knex client
* instance. The knex documentation provides a number of examples for different
* databases.
*
* @constructor
* @param {Knex} knex Knex instance.
*/
function Bookshelf(knex) {
if (!knex || knex.name !== 'knex') {
throw new Error('Invalid knex instance');
}
const bookshelf = {
VERSION: require('../package.json').version
};
const Model = (bookshelf.Model = BookshelfModel.extend(
{
_builder: builderFn,
// The `Model` constructor is referenced as a property on the `Bookshelf`
// instance, mixing in the correct `builder` method, as well as the
// `relation` method, passing in the correct `Model` & `Collection`
// constructors for later reference.
_relation(type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error(
'A valid target model must be defined for the ' + _.result(this, 'tableName') + ' ' + type + ' relation'
);
}
return new Relation(type, Target, options);
}
},
{
/**
* @method Model.forge
* @belongsTo Model
* @description
*
* A simple helper function to instantiate a new Model without needing `new`.
*
* @param {Object=} attributes Initial values for this model's attributes.
* @param {Object=} options Hash of options.
* @param {string=} options.tableName Initial value for {@linkcode Model#tableName tableName}.
* @param {Boolean=} [options.hasTimestamps=false]
*
* Initial value for {@linkcode Model#hasTimestamps hasTimestamps}.
*
* @param {Boolean} [options.parse=false]
*
* Convert attributes by {@linkcode Model#parse parse} before being
* {@linkcode Model#set set} on the `model`.
*/
forge: function forge(attributes, options) {
return new this(attributes, options);
},
/**
* @method Model.collection
* @belongsTo Model
* @description
*
* A simple static helper to instantiate a new {@link Collection}, setting
* the current `model` as the collection's target.
*
* @example
*
* Customer.collection().fetch().then(function(collection) {
* // ...
* });
*
* @param {(Model[])=} models
* @param {Object=} options
* @returns {Collection}
*/
collection(models, options) {
return new bookshelf.Collection(models || [], _.extend({}, options, {model: this}));
},
/**
* @method Model.count
* @belongsTo Model
* @since 0.8.2
* @description
*
* Gets the number of matching records in the database, respecting any
* previous calls to {@link Model#query query}. If a `column` is provided,
* records with a null value in that column will be excluded from the count.
*
* @param {string} [column='*']
* Specify a column to count - rows with null values in this column will be excluded.
* @param {Object=} options
* Hash of options.
* @returns {Promise<Number>}
* A promise resolving to the number of matching rows.
*/
count(column, options) {
return this.forge().count(column, options);
},
/**
* @method Model.fetchAll
* @belongsTo Model
* @description
*
* Simple helper function for retrieving all instances of the given model.
*
* @see Model#fetchAll
* @returns {Promise<Collection>}
*/
fetchAll(options) {
return this.forge().fetchAll(options);
}
}
));
const Collection = (bookshelf.Collection = BookshelfCollection.extend(
{
_builder: builderFn
},
{
/**
* @method Collection.forge
* @belongsTo Collection
* @description
*
* A simple helper function to instantiate a new Collection without needing
* new.
*
* @param {(Object[]|Model[])=} [models]
* Set of models (or attribute hashes) with which to initialize the
* collection.
* @param {Object} options Hash of options.
*
* @example
*
* var Promise = require('bluebird');
* var Accounts = bookshelf.Collection.extend({
* model: Account
* });
*
* var accounts = Accounts.forge([
* {name: 'Person1'},
* {name: 'Person2'}
* ]);
*
* Promise.all(accounts.invokeMap('save')).then(function() {
* // collection models should now be saved...
* });
*/
forge: function forge(models, options) {
return new this(models, options);
}
}
));
// The collection also references the correct `Model`, specified above, for
// creating new `Model` instances in the collection.
Collection.prototype.model = Model;
Model.prototype.Collection = Collection;
const Relation = BookshelfRelation.extend({Model, Collection});
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes
// in the `Events` object. It also contains the version number, and a
// `Transaction` method referencing the correct version of `knex` passed into
// the object.
_.extend(bookshelf, Events, Errors, {
/**
* @method Bookshelf#transaction
* @memberOf Bookshelf
* @description
*
* An alias to `{@link http://knexjs.org/#Transactions
* Knex#transaction}`, the `transaction` object must be passed along in the
* options of any relevant Bookshelf calls, to ensure all queries are on the
* same connection. The entire transaction block is a promise that will
* resolve when the transaction is committed, or fail if the transaction is
* rolled back.
*
* When fetching inside a transaction it's possible to specify a row-level
* lock by passing the wanted lock type in the `lock` option to
* {@linkcode Model#fetch fetch}. Available options are `forUpdate` and
* `forShare`.
*
* var Promise = require('bluebird');
*
* Bookshelf.transaction(function(t) {
* return new Library({name: 'Old Books'})
* .save(null, {transacting: t})
* .tap(function(model) {
* return Promise.map([
* {title: 'Canterbury Tales'},
* {title: 'Moby Dick'},
* {title: 'Hamlet'}
* ], function(info) {
* // Some validation could take place here.
* return new Book(info).save({'shelf_id': model.id}, {transacting: t});
* });
* });
* }).then(function(library) {
* console.log(library.related('books').pluck('title'));
* }).catch(function(err) {
* console.error(err);
* });
*
* @param {Bookshelf~transactionCallback} transactionCallback
* Callback containing transaction logic. The callback should return a
* promise.
*
* @returns {Promise<mixed>}
* A promise resolving to the value returned from {@link
* Bookshelf~transactionCallback transactionCallback}.
*/
transaction() {
return this.knex.transaction.apply(this.knex, arguments);
},
/**
* @callback Bookshelf~transactionCallback
* @description
*
* A transaction block to be provided to {@link Bookshelf#transaction}.
*
* @see {@link http://knexjs.org/#Transactions Knex#transaction}
* @see Bookshelf#transaction
*
* @param {Transaction} transaction
* @returns {Promise<mixed>}
*/
/**
* @method Bookshelf#plugin
* @memberOf Bookshelf
* @description
*
* This method provides a nice, tested, standardized way of adding plugins
* to a `Bookshelf` instance, injecting the current instance into the
* plugin, which should be a `module.exports`.
*
* You can add a plugin by specifying a string with the name of the plugin
* to load. In this case it will try to find a module. It will first check
* for a match within the `bookshelf/plugins` directory. If nothing is
* found it will pass the string to `require()`, so you can either require
* an npm dependency by name or one of your own modules by relative path:
*
* bookshelf.plugin('./bookshelf-plugins/my-favourite-plugin');
* bookshelf.plugin('plugin-from-npm');
*
* There are a few built-in plugins already, along with many independently
* developed ones. See [the list of available plugins](#plugins).
*
* You can also provide an array of strings or functions, which is the same
* as calling `bookshelf.plugin()` multiple times. In this case the same
* options object will be reused:
*
* bookshelf.plugin(['registry', './my-plugins/special-parse-format']);
*
* Example plugin:
*
* // Converts all string values to lower case when setting attributes on a model
* module.exports = function(bookshelf) {
* bookshelf.Model = bookshelf.Model.extend({
* set: function(key, value, options) {
* if (!key) return this;
* if (typeof value === 'string') value = value.toLowerCase();
* return bookshelf.Model.prototype.set.call(this, key, value, options);
* }
* });
* }
*
* @param {string|array|Function} plugin
* The plugin or plugins to add. If you provide a string it can
* represent a built-in plugin, an npm package or a file somewhere on
* your project. You can also pass a function as argument to add it as a
* plugin. Finally, it's also possible to pass an array of strings or
* functions to add them all at once.
* @param {mixed} options
* This can be anything you want and it will be passed directly to the
* plugin as the second argument when loading it.
*/
plugin(plugin, options)
|
});
/**
* @member Bookshelf#knex
* @memberOf Bookshelf
* @type {Knex}
* @description
* A reference to the {@link http://knexjs.org Knex.js} instance being used by Bookshelf.
*/
bookshelf.knex = knex;
function builderFn(tableNameOrBuilder) {
let builder = null;
if (_.isString(tableNameOrBuilder)) {
builder = bookshelf.knex(tableNameOrBuilder);
} else if (tableNameOrBuilder == null) {
builder = bookshelf.knex.queryBuilder();
} else {
// Assuming here that `tableNameOrBuilder` is a QueryBuilder instance. Not
// aware of a way to check that this is the case (ie. using
// `Knex.isQueryBuilder` or equivalent).
builder = tableNameOrBuilder;
}
return builder.on('query', (data) => this.trigger('query', data));
}
// Attach `where`, `query`, and `fetchAll` as static methods.
['where', 'query'].forEach((method) => {
Model[method] = Collection[method] = function() {
const model = this.forge();
return model[method].apply(model, arguments);
};
});
return bookshelf;
}
// Constructor for a new `Bookshelf` object, it accepts an active `knex`
// instance and initializes the appropriate `Model` and `Collection`
// constructors for use in the current instance.
Bookshelf.initialize = function(knex) {
helpers.warn("Bookshelf.initialize is deprecated, pass knex directly: require('bookshelf')(knex)");
return new Bookshelf(knex);
};
module.exports = Bookshelf;
|
{
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
if (!process.browser) {
require(plugin)(this, options);
}
}
} else if (Array.isArray(plugin)) {
plugin.forEach((p) => this.plugin(p, options));
} else {
plugin(this, options);
}
return this;
}
|
identifier_body
|
reporter.express.js
|
/*!
* Copyright(c) 2014 Jan Blaha
*/
/*globals $data */
var async = require("async"),
express = require('express'),
_ = require("underscore"),
path = require("path"),
odata_server = require('odata-server'),
q = require("q"),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
fs = require("fs"),
http = require("http"),
https = require("https"),
cluster = require("cluster"),
cors = require('cors'),
routes = require("./routes.js"),
multer = require('multer');
var useDomainMiddleware = function(reporter, req, res) {
var clusterInstance = (reporter.options.cluster && reporter.options.cluster.enabled) ? reporter.options.cluster.instance : null;
return require("./clusterDomainMiddleware.js")(clusterInstance, reporter.express.server, reporter.logger, req, res, reporter.express.app);
};
var startAsync = function(reporter, server, port) {
var defer = q.defer();
server.on('error', function (e) {
reporter.logger.error("Error when starting http server on port " + port + " " + e.stack);
defer.reject(e);
}).on("listen", function() {
defer.resolve();
});
server.listen(port, function () {
defer.resolve();
});
return defer.promise;
};
var startExpressApp = function(reporter, app, config) {
//no port, use process.env.PORT, this is used when hosted in iisnode
if (!config.httpPort && !config.httpsPort) {
reporter.express.server = http.createServer(app);
return q.ninvoke(reporter.express.server, "listen", process.env.PORT);
}
//just http port is specified, lets start server on http
if (!config.httpsPort) {
reporter.express.server = http.createServer(function(req, res) { useDomainMiddleware(reporter, req, res); });
return startAsync(reporter, reporter.express.server, config.httpPort);
}
//http and https port specified
//fist start http => https redirector
if (config.httpPort) {
http.createServer(function (req, res) {
res.writeHead(302, {
'Location': "https://" + req.headers.host.split(':')[0] + ':' + config.httpsPort + req.url
});
res.end();
}).listen(config.httpPort).on('error', function (e) {
console.error("Error when starting http server on port " + config.httpPort + " " + e.stack);
});
}
//second start https server
if (!fs.existsSync(config.certificate.key)) {
config.certificate.key = path.join(__dirname, "../../../", "certificates", "jsreport.net.key");
config.certificate.cert = path.join(__dirname, "../../../", "certificates", "jsreport.net.cert");
}
var credentials = {
key: fs.readFileSync(config.certificate.key, 'utf8'),
cert: fs.readFileSync(config.certificate.cert, 'utf8'),
rejectUnauthorized: false //support invalid certificates
};
reporter.express.server = https.createServer(credentials, function(req, res) { useDomainMiddleware(reporter, req, res); });
return startAsync(reporter, reporter.express.server, config.httpsPort);
};
var configureExpressApp = function(app, reporter, definition){
reporter.express.app = app;
app.options('*', function(req, res) {
require("cors")({
methods : ["GET", "POST", "PUT", "DELETE", "PATCH", "MERGE"],
origin: true
})(req, res);
});
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true, limit: definition.options.inputRequestLimit || "20mb"}));
app.use(bodyParser.json({
limit: definition.options.inputRequestLimit || "20mb"
}));
app.set('views', path.join(__dirname, '../public/views'));
app.engine('html', require('ejs').renderFile);
app.use(multer({ dest: reporter.options.tempDirectory}));
app.use(cors());
reporter.emit("before-express-configure", app);
routes(app, reporter);
reporter.emit("express-configure", app);
};
module.exports = function(reporter, definition) {
reporter.express = {};
var app = definition.options.app;
if (!app) {
app = express();
}
reporter.initializeListener.add(definition.name, this, function() {
function lo
|
{
if (reporter.options.httpsPort)
reporter.logger.info("jsreport server successfully started on https port: " + reporter.options.httpsPort);
if (reporter.options.httpPort)
reporter.logger.info("jsreport server successfully started on http port: " + reporter.options.httpPort);
if (!reporter.options.httpPort && !reporter.options.httpsPort && reporter.express.server)
reporter.logger.info("jsreport server successfully started on http port: " + reporter.express.server.address().port);
}
if (definition.options.app) {
reporter.logger.info("Configuring routes for existing express app.");
configureExpressApp(app, reporter, definition);
logStart();
return;
}
reporter.logger.info("Creating default express app.");
configureExpressApp(app, reporter, definition);
return startExpressApp(reporter, app, reporter.options).then(function() {
logStart();
});
});
};
|
gStart()
|
identifier_name
|
reporter.express.js
|
/*!
* Copyright(c) 2014 Jan Blaha
*/
/*globals $data */
var async = require("async"),
express = require('express'),
_ = require("underscore"),
path = require("path"),
odata_server = require('odata-server'),
q = require("q"),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
fs = require("fs"),
http = require("http"),
https = require("https"),
cluster = require("cluster"),
cors = require('cors'),
routes = require("./routes.js"),
multer = require('multer');
var useDomainMiddleware = function(reporter, req, res) {
var clusterInstance = (reporter.options.cluster && reporter.options.cluster.enabled) ? reporter.options.cluster.instance : null;
return require("./clusterDomainMiddleware.js")(clusterInstance, reporter.express.server, reporter.logger, req, res, reporter.express.app);
};
var startAsync = function(reporter, server, port) {
var defer = q.defer();
server.on('error', function (e) {
reporter.logger.error("Error when starting http server on port " + port + " " + e.stack);
defer.reject(e);
}).on("listen", function() {
defer.resolve();
});
server.listen(port, function () {
defer.resolve();
});
return defer.promise;
};
var startExpressApp = function(reporter, app, config) {
//no port, use process.env.PORT, this is used when hosted in iisnode
if (!config.httpPort && !config.httpsPort) {
reporter.express.server = http.createServer(app);
return q.ninvoke(reporter.express.server, "listen", process.env.PORT);
}
//just http port is specified, lets start server on http
if (!config.httpsPort) {
reporter.express.server = http.createServer(function(req, res) { useDomainMiddleware(reporter, req, res); });
return startAsync(reporter, reporter.express.server, config.httpPort);
}
//http and https port specified
//fist start http => https redirector
if (config.httpPort) {
http.createServer(function (req, res) {
res.writeHead(302, {
'Location': "https://" + req.headers.host.split(':')[0] + ':' + config.httpsPort + req.url
});
res.end();
}).listen(config.httpPort).on('error', function (e) {
console.error("Error when starting http server on port " + config.httpPort + " " + e.stack);
});
}
//second start https server
if (!fs.existsSync(config.certificate.key)) {
config.certificate.key = path.join(__dirname, "../../../", "certificates", "jsreport.net.key");
config.certificate.cert = path.join(__dirname, "../../../", "certificates", "jsreport.net.cert");
}
var credentials = {
key: fs.readFileSync(config.certificate.key, 'utf8'),
cert: fs.readFileSync(config.certificate.cert, 'utf8'),
rejectUnauthorized: false //support invalid certificates
};
reporter.express.server = https.createServer(credentials, function(req, res) { useDomainMiddleware(reporter, req, res); });
return startAsync(reporter, reporter.express.server, config.httpsPort);
};
var configureExpressApp = function(app, reporter, definition){
reporter.express.app = app;
app.options('*', function(req, res) {
require("cors")({
methods : ["GET", "POST", "PUT", "DELETE", "PATCH", "MERGE"],
origin: true
})(req, res);
});
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true, limit: definition.options.inputRequestLimit || "20mb"}));
app.use(bodyParser.json({
limit: definition.options.inputRequestLimit || "20mb"
}));
app.set('views', path.join(__dirname, '../public/views'));
app.engine('html', require('ejs').renderFile);
app.use(multer({ dest: reporter.options.tempDirectory}));
app.use(cors());
reporter.emit("before-express-configure", app);
routes(app, reporter);
reporter.emit("express-configure", app);
};
module.exports = function(reporter, definition) {
reporter.express = {};
var app = definition.options.app;
if (!app) {
app = express();
}
reporter.initializeListener.add(definition.name, this, function() {
function logStart() {
|
if (definition.options.app) {
reporter.logger.info("Configuring routes for existing express app.");
configureExpressApp(app, reporter, definition);
logStart();
return;
}
reporter.logger.info("Creating default express app.");
configureExpressApp(app, reporter, definition);
return startExpressApp(reporter, app, reporter.options).then(function() {
logStart();
});
});
};
|
if (reporter.options.httpsPort)
reporter.logger.info("jsreport server successfully started on https port: " + reporter.options.httpsPort);
if (reporter.options.httpPort)
reporter.logger.info("jsreport server successfully started on http port: " + reporter.options.httpPort);
if (!reporter.options.httpPort && !reporter.options.httpsPort && reporter.express.server)
reporter.logger.info("jsreport server successfully started on http port: " + reporter.express.server.address().port);
}
|
identifier_body
|
reporter.express.js
|
/*!
* Copyright(c) 2014 Jan Blaha
*/
/*globals $data */
var async = require("async"),
express = require('express'),
_ = require("underscore"),
path = require("path"),
odata_server = require('odata-server'),
q = require("q"),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
fs = require("fs"),
http = require("http"),
https = require("https"),
cluster = require("cluster"),
cors = require('cors'),
routes = require("./routes.js"),
multer = require('multer');
var useDomainMiddleware = function(reporter, req, res) {
var clusterInstance = (reporter.options.cluster && reporter.options.cluster.enabled) ? reporter.options.cluster.instance : null;
return require("./clusterDomainMiddleware.js")(clusterInstance, reporter.express.server, reporter.logger, req, res, reporter.express.app);
};
var startAsync = function(reporter, server, port) {
var defer = q.defer();
server.on('error', function (e) {
reporter.logger.error("Error when starting http server on port " + port + " " + e.stack);
defer.reject(e);
}).on("listen", function() {
defer.resolve();
});
server.listen(port, function () {
defer.resolve();
});
return defer.promise;
};
var startExpressApp = function(reporter, app, config) {
//no port, use process.env.PORT, this is used when hosted in iisnode
if (!config.httpPort && !config.httpsPort) {
reporter.express.server = http.createServer(app);
return q.ninvoke(reporter.express.server, "listen", process.env.PORT);
}
//just http port is specified, lets start server on http
if (!config.httpsPort) {
reporter.express.server = http.createServer(function(req, res) { useDomainMiddleware(reporter, req, res); });
return startAsync(reporter, reporter.express.server, config.httpPort);
}
//http and https port specified
//fist start http => https redirector
if (config.httpPort) {
http.createServer(function (req, res) {
res.writeHead(302, {
'Location': "https://" + req.headers.host.split(':')[0] + ':' + config.httpsPort + req.url
});
res.end();
}).listen(config.httpPort).on('error', function (e) {
console.error("Error when starting http server on port " + config.httpPort + " " + e.stack);
});
}
//second start https server
if (!fs.existsSync(config.certificate.key)) {
config.certificate.key = path.join(__dirname, "../../../", "certificates", "jsreport.net.key");
config.certificate.cert = path.join(__dirname, "../../../", "certificates", "jsreport.net.cert");
}
var credentials = {
key: fs.readFileSync(config.certificate.key, 'utf8'),
cert: fs.readFileSync(config.certificate.cert, 'utf8'),
rejectUnauthorized: false //support invalid certificates
};
reporter.express.server = https.createServer(credentials, function(req, res) { useDomainMiddleware(reporter, req, res); });
return startAsync(reporter, reporter.express.server, config.httpsPort);
};
var configureExpressApp = function(app, reporter, definition){
reporter.express.app = app;
app.options('*', function(req, res) {
require("cors")({
methods : ["GET", "POST", "PUT", "DELETE", "PATCH", "MERGE"],
origin: true
})(req, res);
});
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true, limit: definition.options.inputRequestLimit || "20mb"}));
app.use(bodyParser.json({
limit: definition.options.inputRequestLimit || "20mb"
}));
|
app.use(cors());
reporter.emit("before-express-configure", app);
routes(app, reporter);
reporter.emit("express-configure", app);
};
module.exports = function(reporter, definition) {
reporter.express = {};
var app = definition.options.app;
if (!app) {
app = express();
}
reporter.initializeListener.add(definition.name, this, function() {
function logStart() {
if (reporter.options.httpsPort)
reporter.logger.info("jsreport server successfully started on https port: " + reporter.options.httpsPort);
if (reporter.options.httpPort)
reporter.logger.info("jsreport server successfully started on http port: " + reporter.options.httpPort);
if (!reporter.options.httpPort && !reporter.options.httpsPort && reporter.express.server)
reporter.logger.info("jsreport server successfully started on http port: " + reporter.express.server.address().port);
}
if (definition.options.app) {
reporter.logger.info("Configuring routes for existing express app.");
configureExpressApp(app, reporter, definition);
logStart();
return;
}
reporter.logger.info("Creating default express app.");
configureExpressApp(app, reporter, definition);
return startExpressApp(reporter, app, reporter.options).then(function() {
logStart();
});
});
};
|
app.set('views', path.join(__dirname, '../public/views'));
app.engine('html', require('ejs').renderFile);
app.use(multer({ dest: reporter.options.tempDirectory}));
|
random_line_split
|
urls.py
|
"""djangochat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
|
urlpatterns = [
url(r'^', include('chatdemo.urls')),
url(r'^admin/', admin.site.urls),
]
|
random_line_split
|
|
http.py
|
# coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Protocol
from twisted.names.client import Resolver
from twisted.web import client
from twisted.web.http_headers import Headers
from twisted.web.client import (
HTTPPageGetter,
HTTPClientFactory,
_makeGetterFactory,
)
from observer.utils import wait
from observer.lib import log
class HTTPRESTGetter(HTTPPageGetter):
def handleStatus_304(self):
pass
class HTTPRESTClientFactory(HTTPClientFactory):
protocol = HTTPRESTGetter
def getPage(url, contextFactory=None, *args, **kwargs):
return _makeGetterFactory(
url,
HTTPRESTClientFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
class HTTPBodyReceiver(Protocol):
def __init__(self, deferred):
self.deferred = deferred
self.body = StringIO()
self.reason = None
def dataReceived(self, data):
self.body.write(data)
def connectionLost(self, reason):
body = self.body.getvalue()
self.reason = reason
self.deferred.callback(body)
def _cbRequest(response):
finished = Deferred()
response.deliverBody(HTTPBodyReceiver(finished))
return finished
def request(agent, url, headers=None, body=None):
log.debug('begin request ' + url)
print agent, agent.request
if body is None:
d = agent.request('GET', str(url), headers)
else:
d = agent.request('POST', str(url), headers,
client.FileBodyProducer(StringIO(body)))
d.addCallback(_cbRequest)
return d
class AdditionalHeaderAgent(object):
"""
An L{Agent} wrapper to add default headers.
@param headers: A list or tuple of (name, value) objects. The name
is which of the HTTP header to set the value for. and the value
is which to set for the named header.
"""
def __init__(self, agent, headers):
self._header_list = headers
self._agent = agent
def request(self, method, uri, headers=None, bodyProducer=None):
if headers is None:
headers = Headers()
else:
headers = headers.copy()
for name, value in self._header_list:
headers.addRawHeader(name, value)
return self._agent.request(method, uri, headers, bodyProducer)
class InfiniteLoginError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class NoAgentError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class LoginResponse(object):
def __init__(self, response, body, reason):
self.original = response
self.data = body
self.reason = reason
def __getattr__(self, name):
return getattr(self.original, name)
def deliverBody(self, protocol):
protocol.dataReceived(self.data)
protocol.connectionLost(self.reason)
class LoginAgent(object):
def __init__(self, agent, retryLimit=1):
self._agent = agent
self.loggedin = False
self.retryLimit = retryLimit
def login(self):
raise NotImplementedError("Must Implement the login method.")
def testLogin(self, content):
raise NotImplementedError("Must Implement the test login method.")
@inlineCallbacks
def request(self, method, uri, headers=None, bodyProducer=None):
retryCount = 0
while True:
if not self.loggedin:
yield self.login()
retryCount += 1
response = yield self._agent.request(method, uri,
headers, bodyProducer)
finished = Deferred()
p = HTTPBodyReceiver(finished)
response.deliverBody(p)
body = yield finished
reason = p.reason
body = yield self.testLogin(body)
if self.loggedin:
returnValue(LoginResponse(response, body, reason))
return
if bodyProducer is not None:
returnValue(None)
return
if retryCount >= self.retryLimit:
raise InfiniteLoginError("Maximum retry limit reached")
class TimedAgentPool(object):
#FIXME here the float value should be replaced by variables
def __init__(
self,
minTimeInterval=10.0,
maxTimeInterval=15.0,
loginInterval=60.0,
):
self.lastLogin = 0.0
self.agents = []
self.idleAgents = []
self.defers = []
def initAgent(self, agent):
self.agents.append(agent)
self.idleAgents.append(agent)
agent.nextAccess = 0
agent.pool = self
def addAgent(self, agent):
t = random.uniform(self.minTimeInterval,
self.maxTimeInterval)
agent.nextAccess = time.time() + t
if self.defers:
d = self.defers[0]
del self.defers[0]
task.deferLater(reactor, t, d.callback, agent)
else:
self.idleAgents.append(agent)
@inlineCallbacks
def getAgent(self):
if not self.agents:
raise NoAgentError('This pool has no agent yet.')
if not self.idleAgents:
d = Deferred()
self.defers.append(d)
agent = yield d
else:
agent = self.idleAgents[0]
del self.idleAgents[0]
now = time.time()
if now > agent.nextAccess:
|
else:
yield wait(agent.nextAccess - now)
returnValue(agent)
def removeAgent(self, agent):
self.agents.remove(agent)
class DNSCachingResolver(Resolver):
"""
subclass Resolver to add dns caching mechanism
"""
clear_interval = 1 * 60 * 60
def __init__(self, *args, **kwargs):
Resolver.__init__(self, *args, **kwargs)
self.clear_cache()
def clear_cache(self):
self.cached_url = {}
reactor.callLater(self.clear_interval, self.clear_cache)
def update_cache(self, result, name):
self.cached_url[name] = result
return result
def getHostByName(self, name, timeout=None, effort=10):
"""
@see: twisted.names.client.getHostByName
"""
# XXX - respect timeout
if name in self.cached_url:
return succeed(self.cached_url[name])
else:
return self.lookupAllRecords(
name,
timeout,
).addCallback(
self._cbRecords,
name,
effort,
).addCallback(self.update_cache, name)
|
returnValue(agent)
|
conditional_block
|
http.py
|
# coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Protocol
from twisted.names.client import Resolver
from twisted.web import client
from twisted.web.http_headers import Headers
from twisted.web.client import (
HTTPPageGetter,
HTTPClientFactory,
_makeGetterFactory,
)
from observer.utils import wait
from observer.lib import log
class HTTPRESTGetter(HTTPPageGetter):
def handleStatus_304(self):
pass
class HTTPRESTClientFactory(HTTPClientFactory):
protocol = HTTPRESTGetter
def getPage(url, contextFactory=None, *args, **kwargs):
return _makeGetterFactory(
url,
HTTPRESTClientFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
class HTTPBodyReceiver(Protocol):
def __init__(self, deferred):
self.deferred = deferred
self.body = StringIO()
self.reason = None
def dataReceived(self, data):
self.body.write(data)
def connectionLost(self, reason):
body = self.body.getvalue()
self.reason = reason
self.deferred.callback(body)
def _cbRequest(response):
finished = Deferred()
response.deliverBody(HTTPBodyReceiver(finished))
return finished
def request(agent, url, headers=None, body=None):
log.debug('begin request ' + url)
print agent, agent.request
if body is None:
d = agent.request('GET', str(url), headers)
else:
d = agent.request('POST', str(url), headers,
client.FileBodyProducer(StringIO(body)))
d.addCallback(_cbRequest)
return d
class AdditionalHeaderAgent(object):
"""
An L{Agent} wrapper to add default headers.
@param headers: A list or tuple of (name, value) objects. The name
is which of the HTTP header to set the value for. and the value
is which to set for the named header.
"""
def __init__(self, agent, headers):
self._header_list = headers
self._agent = agent
def request(self, method, uri, headers=None, bodyProducer=None):
if headers is None:
headers = Headers()
else:
headers = headers.copy()
for name, value in self._header_list:
headers.addRawHeader(name, value)
return self._agent.request(method, uri, headers, bodyProducer)
class InfiniteLoginError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class NoAgentError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class LoginResponse(object):
def __init__(self, response, body, reason):
self.original = response
self.data = body
self.reason = reason
def __getattr__(self, name):
return getattr(self.original, name)
def deliverBody(self, protocol):
protocol.dataReceived(self.data)
protocol.connectionLost(self.reason)
class
|
(object):
def __init__(self, agent, retryLimit=1):
self._agent = agent
self.loggedin = False
self.retryLimit = retryLimit
def login(self):
raise NotImplementedError("Must Implement the login method.")
def testLogin(self, content):
raise NotImplementedError("Must Implement the test login method.")
@inlineCallbacks
def request(self, method, uri, headers=None, bodyProducer=None):
retryCount = 0
while True:
if not self.loggedin:
yield self.login()
retryCount += 1
response = yield self._agent.request(method, uri,
headers, bodyProducer)
finished = Deferred()
p = HTTPBodyReceiver(finished)
response.deliverBody(p)
body = yield finished
reason = p.reason
body = yield self.testLogin(body)
if self.loggedin:
returnValue(LoginResponse(response, body, reason))
return
if bodyProducer is not None:
returnValue(None)
return
if retryCount >= self.retryLimit:
raise InfiniteLoginError("Maximum retry limit reached")
class TimedAgentPool(object):
#FIXME here the float value should be replaced by variables
def __init__(
self,
minTimeInterval=10.0,
maxTimeInterval=15.0,
loginInterval=60.0,
):
self.lastLogin = 0.0
self.agents = []
self.idleAgents = []
self.defers = []
def initAgent(self, agent):
self.agents.append(agent)
self.idleAgents.append(agent)
agent.nextAccess = 0
agent.pool = self
def addAgent(self, agent):
t = random.uniform(self.minTimeInterval,
self.maxTimeInterval)
agent.nextAccess = time.time() + t
if self.defers:
d = self.defers[0]
del self.defers[0]
task.deferLater(reactor, t, d.callback, agent)
else:
self.idleAgents.append(agent)
@inlineCallbacks
def getAgent(self):
if not self.agents:
raise NoAgentError('This pool has no agent yet.')
if not self.idleAgents:
d = Deferred()
self.defers.append(d)
agent = yield d
else:
agent = self.idleAgents[0]
del self.idleAgents[0]
now = time.time()
if now > agent.nextAccess:
returnValue(agent)
else:
yield wait(agent.nextAccess - now)
returnValue(agent)
def removeAgent(self, agent):
self.agents.remove(agent)
class DNSCachingResolver(Resolver):
"""
subclass Resolver to add dns caching mechanism
"""
clear_interval = 1 * 60 * 60
def __init__(self, *args, **kwargs):
Resolver.__init__(self, *args, **kwargs)
self.clear_cache()
def clear_cache(self):
self.cached_url = {}
reactor.callLater(self.clear_interval, self.clear_cache)
def update_cache(self, result, name):
self.cached_url[name] = result
return result
def getHostByName(self, name, timeout=None, effort=10):
"""
@see: twisted.names.client.getHostByName
"""
# XXX - respect timeout
if name in self.cached_url:
return succeed(self.cached_url[name])
else:
return self.lookupAllRecords(
name,
timeout,
).addCallback(
self._cbRecords,
name,
effort,
).addCallback(self.update_cache, name)
|
LoginAgent
|
identifier_name
|
http.py
|
# coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Protocol
from twisted.names.client import Resolver
from twisted.web import client
from twisted.web.http_headers import Headers
from twisted.web.client import (
HTTPPageGetter,
HTTPClientFactory,
_makeGetterFactory,
)
from observer.utils import wait
from observer.lib import log
class HTTPRESTGetter(HTTPPageGetter):
def handleStatus_304(self):
pass
class HTTPRESTClientFactory(HTTPClientFactory):
protocol = HTTPRESTGetter
def getPage(url, contextFactory=None, *args, **kwargs):
return _makeGetterFactory(
url,
HTTPRESTClientFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
class HTTPBodyReceiver(Protocol):
def __init__(self, deferred):
self.deferred = deferred
self.body = StringIO()
self.reason = None
def dataReceived(self, data):
self.body.write(data)
def connectionLost(self, reason):
body = self.body.getvalue()
self.reason = reason
self.deferred.callback(body)
def _cbRequest(response):
finished = Deferred()
response.deliverBody(HTTPBodyReceiver(finished))
return finished
def request(agent, url, headers=None, body=None):
log.debug('begin request ' + url)
print agent, agent.request
if body is None:
d = agent.request('GET', str(url), headers)
else:
d = agent.request('POST', str(url), headers,
client.FileBodyProducer(StringIO(body)))
d.addCallback(_cbRequest)
return d
class AdditionalHeaderAgent(object):
"""
An L{Agent} wrapper to add default headers.
@param headers: A list or tuple of (name, value) objects. The name
is which of the HTTP header to set the value for. and the value
is which to set for the named header.
"""
def __init__(self, agent, headers):
self._header_list = headers
self._agent = agent
def request(self, method, uri, headers=None, bodyProducer=None):
if headers is None:
headers = Headers()
else:
headers = headers.copy()
for name, value in self._header_list:
headers.addRawHeader(name, value)
return self._agent.request(method, uri, headers, bodyProducer)
class InfiniteLoginError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class NoAgentError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class LoginResponse(object):
def __init__(self, response, body, reason):
self.original = response
self.data = body
self.reason = reason
def __getattr__(self, name):
return getattr(self.original, name)
def deliverBody(self, protocol):
protocol.dataReceived(self.data)
protocol.connectionLost(self.reason)
class LoginAgent(object):
def __init__(self, agent, retryLimit=1):
self._agent = agent
self.loggedin = False
self.retryLimit = retryLimit
def login(self):
raise NotImplementedError("Must Implement the login method.")
def testLogin(self, content):
raise NotImplementedError("Must Implement the test login method.")
@inlineCallbacks
def request(self, method, uri, headers=None, bodyProducer=None):
retryCount = 0
while True:
if not self.loggedin:
yield self.login()
retryCount += 1
response = yield self._agent.request(method, uri,
headers, bodyProducer)
finished = Deferred()
p = HTTPBodyReceiver(finished)
response.deliverBody(p)
body = yield finished
reason = p.reason
body = yield self.testLogin(body)
if self.loggedin:
returnValue(LoginResponse(response, body, reason))
return
if bodyProducer is not None:
returnValue(None)
return
if retryCount >= self.retryLimit:
raise InfiniteLoginError("Maximum retry limit reached")
class TimedAgentPool(object):
#FIXME here the float value should be replaced by variables
def __init__(
self,
minTimeInterval=10.0,
maxTimeInterval=15.0,
loginInterval=60.0,
):
self.lastLogin = 0.0
self.agents = []
self.idleAgents = []
self.defers = []
def initAgent(self, agent):
self.agents.append(agent)
self.idleAgents.append(agent)
agent.nextAccess = 0
agent.pool = self
def addAgent(self, agent):
t = random.uniform(self.minTimeInterval,
self.maxTimeInterval)
agent.nextAccess = time.time() + t
if self.defers:
d = self.defers[0]
del self.defers[0]
task.deferLater(reactor, t, d.callback, agent)
else:
self.idleAgents.append(agent)
@inlineCallbacks
def getAgent(self):
if not self.agents:
raise NoAgentError('This pool has no agent yet.')
if not self.idleAgents:
d = Deferred()
self.defers.append(d)
agent = yield d
else:
agent = self.idleAgents[0]
del self.idleAgents[0]
now = time.time()
if now > agent.nextAccess:
returnValue(agent)
else:
yield wait(agent.nextAccess - now)
returnValue(agent)
def removeAgent(self, agent):
self.agents.remove(agent)
|
class DNSCachingResolver(Resolver):
"""
subclass Resolver to add dns caching mechanism
"""
clear_interval = 1 * 60 * 60
def __init__(self, *args, **kwargs):
Resolver.__init__(self, *args, **kwargs)
self.clear_cache()
def clear_cache(self):
self.cached_url = {}
reactor.callLater(self.clear_interval, self.clear_cache)
def update_cache(self, result, name):
self.cached_url[name] = result
return result
def getHostByName(self, name, timeout=None, effort=10):
"""
@see: twisted.names.client.getHostByName
"""
# XXX - respect timeout
if name in self.cached_url:
return succeed(self.cached_url[name])
else:
return self.lookupAllRecords(
name,
timeout,
).addCallback(
self._cbRecords,
name,
effort,
).addCallback(self.update_cache, name)
|
random_line_split
|
|
http.py
|
# coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Protocol
from twisted.names.client import Resolver
from twisted.web import client
from twisted.web.http_headers import Headers
from twisted.web.client import (
HTTPPageGetter,
HTTPClientFactory,
_makeGetterFactory,
)
from observer.utils import wait
from observer.lib import log
class HTTPRESTGetter(HTTPPageGetter):
def handleStatus_304(self):
pass
class HTTPRESTClientFactory(HTTPClientFactory):
protocol = HTTPRESTGetter
def getPage(url, contextFactory=None, *args, **kwargs):
return _makeGetterFactory(
url,
HTTPRESTClientFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
class HTTPBodyReceiver(Protocol):
def __init__(self, deferred):
self.deferred = deferred
self.body = StringIO()
self.reason = None
def dataReceived(self, data):
self.body.write(data)
def connectionLost(self, reason):
body = self.body.getvalue()
self.reason = reason
self.deferred.callback(body)
def _cbRequest(response):
finished = Deferred()
response.deliverBody(HTTPBodyReceiver(finished))
return finished
def request(agent, url, headers=None, body=None):
log.debug('begin request ' + url)
print agent, agent.request
if body is None:
d = agent.request('GET', str(url), headers)
else:
d = agent.request('POST', str(url), headers,
client.FileBodyProducer(StringIO(body)))
d.addCallback(_cbRequest)
return d
class AdditionalHeaderAgent(object):
"""
An L{Agent} wrapper to add default headers.
@param headers: A list or tuple of (name, value) objects. The name
is which of the HTTP header to set the value for. and the value
is which to set for the named header.
"""
def __init__(self, agent, headers):
self._header_list = headers
self._agent = agent
def request(self, method, uri, headers=None, bodyProducer=None):
if headers is None:
headers = Headers()
else:
headers = headers.copy()
for name, value in self._header_list:
headers.addRawHeader(name, value)
return self._agent.request(method, uri, headers, bodyProducer)
class InfiniteLoginError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class NoAgentError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class LoginResponse(object):
def __init__(self, response, body, reason):
self.original = response
self.data = body
self.reason = reason
def __getattr__(self, name):
return getattr(self.original, name)
def deliverBody(self, protocol):
protocol.dataReceived(self.data)
protocol.connectionLost(self.reason)
class LoginAgent(object):
def __init__(self, agent, retryLimit=1):
self._agent = agent
self.loggedin = False
self.retryLimit = retryLimit
def login(self):
raise NotImplementedError("Must Implement the login method.")
def testLogin(self, content):
raise NotImplementedError("Must Implement the test login method.")
@inlineCallbacks
def request(self, method, uri, headers=None, bodyProducer=None):
retryCount = 0
while True:
if not self.loggedin:
yield self.login()
retryCount += 1
response = yield self._agent.request(method, uri,
headers, bodyProducer)
finished = Deferred()
p = HTTPBodyReceiver(finished)
response.deliverBody(p)
body = yield finished
reason = p.reason
body = yield self.testLogin(body)
if self.loggedin:
returnValue(LoginResponse(response, body, reason))
return
if bodyProducer is not None:
returnValue(None)
return
if retryCount >= self.retryLimit:
raise InfiniteLoginError("Maximum retry limit reached")
class TimedAgentPool(object):
#FIXME here the float value should be replaced by variables
def __init__(
self,
minTimeInterval=10.0,
maxTimeInterval=15.0,
loginInterval=60.0,
):
self.lastLogin = 0.0
self.agents = []
self.idleAgents = []
self.defers = []
def initAgent(self, agent):
|
def addAgent(self, agent):
t = random.uniform(self.minTimeInterval,
self.maxTimeInterval)
agent.nextAccess = time.time() + t
if self.defers:
d = self.defers[0]
del self.defers[0]
task.deferLater(reactor, t, d.callback, agent)
else:
self.idleAgents.append(agent)
@inlineCallbacks
def getAgent(self):
if not self.agents:
raise NoAgentError('This pool has no agent yet.')
if not self.idleAgents:
d = Deferred()
self.defers.append(d)
agent = yield d
else:
agent = self.idleAgents[0]
del self.idleAgents[0]
now = time.time()
if now > agent.nextAccess:
returnValue(agent)
else:
yield wait(agent.nextAccess - now)
returnValue(agent)
def removeAgent(self, agent):
self.agents.remove(agent)
class DNSCachingResolver(Resolver):
"""
subclass Resolver to add dns caching mechanism
"""
clear_interval = 1 * 60 * 60
def __init__(self, *args, **kwargs):
Resolver.__init__(self, *args, **kwargs)
self.clear_cache()
def clear_cache(self):
self.cached_url = {}
reactor.callLater(self.clear_interval, self.clear_cache)
def update_cache(self, result, name):
self.cached_url[name] = result
return result
def getHostByName(self, name, timeout=None, effort=10):
"""
@see: twisted.names.client.getHostByName
"""
# XXX - respect timeout
if name in self.cached_url:
return succeed(self.cached_url[name])
else:
return self.lookupAllRecords(
name,
timeout,
).addCallback(
self._cbRecords,
name,
effort,
).addCallback(self.update_cache, name)
|
self.agents.append(agent)
self.idleAgents.append(agent)
agent.nextAccess = 0
agent.pool = self
|
identifier_body
|
test_nde_And.py
|
from unittest.mock import MagicMock, Mock
from unittest import TestCase
from PartyProblemSimulator.BooleanEquation.BooleanNode import BooleanNode
from PartyProblemSimulator.BooleanEquation.AndNode import AndNode
class aBooleanNode(BooleanNode): # pragma: no cover
""" This class is a boolean node. """
def say(self):
return type(self)
def evaluate(self, input_vector):
return True
class TestAndNode(TestCase):
""" Tests the AndNode class. """
def test_evaluation(self):
""" Test the evaluation of the and function. """
fake_true_child = Mock() # A child to return true.
fake_false_child = Mock() # A child to return false.
nde = AndNode(aBooleanNode(), aBooleanNode()) # Instantiate a node with replaceable children.
fake_true_child.evaluate = MagicMock(return_value=True)
fake_false_child.evaluate = MagicMock(return_value=False)
|
nde._lhs_child = fake_true_child
nde._rhs_child = fake_true_child
self.assertTrue(nde.evaluate({}))
# 0 AND 0
nde._lhs_child = fake_false_child
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 1 AND 0
nde._lhs_child = fake_true_child
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 0 AND 1
nde._lhs_child = fake_false_child
nde._rhs_child = fake_true_child
self.assertFalse(nde.evaluate({}))
|
# 1 AND 1
|
random_line_split
|
test_nde_And.py
|
from unittest.mock import MagicMock, Mock
from unittest import TestCase
from PartyProblemSimulator.BooleanEquation.BooleanNode import BooleanNode
from PartyProblemSimulator.BooleanEquation.AndNode import AndNode
class aBooleanNode(BooleanNode): # pragma: no cover
""" This class is a boolean node. """
def say(self):
return type(self)
def evaluate(self, input_vector):
return True
class TestAndNode(TestCase):
|
""" Tests the AndNode class. """
def test_evaluation(self):
""" Test the evaluation of the and function. """
fake_true_child = Mock() # A child to return true.
fake_false_child = Mock() # A child to return false.
nde = AndNode(aBooleanNode(), aBooleanNode()) # Instantiate a node with replaceable children.
fake_true_child.evaluate = MagicMock(return_value=True)
fake_false_child.evaluate = MagicMock(return_value=False)
# 1 AND 1
nde._lhs_child = fake_true_child
nde._rhs_child = fake_true_child
self.assertTrue(nde.evaluate({}))
# 0 AND 0
nde._lhs_child = fake_false_child
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 1 AND 0
nde._lhs_child = fake_true_child
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 0 AND 1
nde._lhs_child = fake_false_child
nde._rhs_child = fake_true_child
self.assertFalse(nde.evaluate({}))
|
identifier_body
|
|
test_nde_And.py
|
from unittest.mock import MagicMock, Mock
from unittest import TestCase
from PartyProblemSimulator.BooleanEquation.BooleanNode import BooleanNode
from PartyProblemSimulator.BooleanEquation.AndNode import AndNode
class aBooleanNode(BooleanNode): # pragma: no cover
""" This class is a boolean node. """
def say(self):
return type(self)
def evaluate(self, input_vector):
return True
class TestAndNode(TestCase):
""" Tests the AndNode class. """
def
|
(self):
""" Test the evaluation of the and function. """
fake_true_child = Mock() # A child to return true.
fake_false_child = Mock() # A child to return false.
nde = AndNode(aBooleanNode(), aBooleanNode()) # Instantiate a node with replaceable children.
fake_true_child.evaluate = MagicMock(return_value=True)
fake_false_child.evaluate = MagicMock(return_value=False)
# 1 AND 1
nde._lhs_child = fake_true_child
nde._rhs_child = fake_true_child
self.assertTrue(nde.evaluate({}))
# 0 AND 0
nde._lhs_child = fake_false_child
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 1 AND 0
nde._lhs_child = fake_true_child
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 0 AND 1
nde._lhs_child = fake_false_child
nde._rhs_child = fake_true_child
self.assertFalse(nde.evaluate({}))
|
test_evaluation
|
identifier_name
|
rustdoc.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.
//! Rustdoc - The Rust documentation generator
#[link(name = "rustdoc",
vers = "0.8-pre",
uuid = "f8abd014-b281-484d-a0c3-26e3de8e2412",
url = "https://github.com/mozilla/rust/tree/master/src/rustdoc")];
#[comment = "The Rust documentation generator"];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];
#[allow(non_implicitly_copyable_typarams)];
extern mod extra;
extern mod rustc;
extern mod syntax;
use std::io;
use std::os;
use config::Config;
use doc::Item;
use doc::ItemUtils;
pub mod pass;
pub mod config;
pub mod parse;
pub mod extract;
pub mod attr_parser;
pub mod doc;
pub mod markdown_index_pass;
pub mod markdown_pass;
pub mod markdown_writer;
pub mod fold;
pub mod path_pass;
pub mod attr_pass;
pub mod tystr_pass;
pub mod prune_hidden_pass;
pub mod desc_to_brief_pass;
pub mod text_pass;
pub mod unindent_pass;
pub mod trim_pass;
pub mod astsrv;
pub mod demo;
pub mod sort_pass;
pub mod sort_item_name_pass;
pub mod sort_item_type_pass;
pub mod page_pass;
pub mod sectionalize_pass;
pub mod escape_pass;
pub mod prune_private_pass;
pub mod util;
pub fn main() {
let args = os::args();
if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) {
config::usage();
return;
}
let config = match config::parse_config(args) {
Ok(config) => config,
Err(err) =>
|
};
run(config);
}
/// Runs rustdoc over the given file
fn run(config: Config) {
let source_file = copy config.input_crate;
// Create an AST service from the source code
do astsrv::from_file(source_file.to_str()) |srv| {
// Just time how long it takes for the AST to become available
do time(~"wait_ast") {
do astsrv::exec(srv.clone()) |_ctxt| { }
};
// Extract the initial doc tree from the AST. This contains
// just names and node ids.
let doc = time(~"extract", || {
let default_name = copy source_file;
extract::from_srv(srv.clone(), default_name.to_str())
});
// Refine and publish the document
pass::run_passes(srv, doc, ~[
// Generate type and signature strings
tystr_pass::mk_pass(),
// Record the full paths to various nodes
path_pass::mk_pass(),
// Extract the docs attributes and attach them to doc nodes
attr_pass::mk_pass(),
// Perform various text escaping
escape_pass::mk_pass(),
// Remove things marked doc(hidden)
prune_hidden_pass::mk_pass(),
// Remove things that are private
prune_private_pass::mk_pass(),
// Extract brief documentation from the full descriptions
desc_to_brief_pass::mk_pass(),
// Massage the text to remove extra indentation
unindent_pass::mk_pass(),
// Split text into multiple sections according to headers
sectionalize_pass::mk_pass(),
// Trim extra spaces from text
trim_pass::mk_pass(),
// Sort items by name
sort_item_name_pass::mk_pass(),
// Sort items again by kind
sort_item_type_pass::mk_pass(),
// Create indexes appropriate for markdown
markdown_index_pass::mk_pass(copy config),
// Break the document into pages if required by the
// output format
page_pass::mk_pass(config.output_style),
// Render
markdown_pass::mk_pass(
markdown_writer::make_writer_factory(copy config)
)
]);
}
}
pub fn time<T>(what: ~str, f: &fn() -> T) -> T {
let start = extra::time::precise_time_s();
let rv = f();
let end = extra::time::precise_time_s();
info!("time: %3.3f s %s", end - start, what);
rv
}
|
{
io::println(fmt!("error: %s", err));
return;
}
|
conditional_block
|
rustdoc.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.
//! Rustdoc - The Rust documentation generator
#[link(name = "rustdoc",
vers = "0.8-pre",
uuid = "f8abd014-b281-484d-a0c3-26e3de8e2412",
url = "https://github.com/mozilla/rust/tree/master/src/rustdoc")];
#[comment = "The Rust documentation generator"];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];
#[allow(non_implicitly_copyable_typarams)];
extern mod extra;
extern mod rustc;
extern mod syntax;
use std::io;
use std::os;
use config::Config;
use doc::Item;
use doc::ItemUtils;
pub mod pass;
pub mod config;
pub mod parse;
pub mod extract;
pub mod attr_parser;
pub mod doc;
pub mod markdown_index_pass;
pub mod markdown_pass;
pub mod markdown_writer;
pub mod fold;
pub mod path_pass;
pub mod attr_pass;
pub mod tystr_pass;
pub mod prune_hidden_pass;
pub mod desc_to_brief_pass;
pub mod text_pass;
pub mod unindent_pass;
pub mod trim_pass;
pub mod astsrv;
pub mod demo;
pub mod sort_pass;
pub mod sort_item_name_pass;
pub mod sort_item_type_pass;
pub mod page_pass;
pub mod sectionalize_pass;
pub mod escape_pass;
pub mod prune_private_pass;
pub mod util;
pub fn main() {
let args = os::args();
if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) {
config::usage();
return;
}
let config = match config::parse_config(args) {
Ok(config) => config,
Err(err) => {
io::println(fmt!("error: %s", err));
return;
}
};
run(config);
}
/// Runs rustdoc over the given file
fn run(config: Config)
|
pub fn time<T>(what: ~str, f: &fn() -> T) -> T {
let start = extra::time::precise_time_s();
let rv = f();
let end = extra::time::precise_time_s();
info!("time: %3.3f s %s", end - start, what);
rv
}
|
{
let source_file = copy config.input_crate;
// Create an AST service from the source code
do astsrv::from_file(source_file.to_str()) |srv| {
// Just time how long it takes for the AST to become available
do time(~"wait_ast") {
do astsrv::exec(srv.clone()) |_ctxt| { }
};
// Extract the initial doc tree from the AST. This contains
// just names and node ids.
let doc = time(~"extract", || {
let default_name = copy source_file;
extract::from_srv(srv.clone(), default_name.to_str())
});
// Refine and publish the document
pass::run_passes(srv, doc, ~[
// Generate type and signature strings
tystr_pass::mk_pass(),
// Record the full paths to various nodes
path_pass::mk_pass(),
// Extract the docs attributes and attach them to doc nodes
attr_pass::mk_pass(),
// Perform various text escaping
escape_pass::mk_pass(),
// Remove things marked doc(hidden)
prune_hidden_pass::mk_pass(),
// Remove things that are private
prune_private_pass::mk_pass(),
// Extract brief documentation from the full descriptions
desc_to_brief_pass::mk_pass(),
// Massage the text to remove extra indentation
unindent_pass::mk_pass(),
// Split text into multiple sections according to headers
sectionalize_pass::mk_pass(),
// Trim extra spaces from text
trim_pass::mk_pass(),
// Sort items by name
sort_item_name_pass::mk_pass(),
// Sort items again by kind
sort_item_type_pass::mk_pass(),
// Create indexes appropriate for markdown
markdown_index_pass::mk_pass(copy config),
// Break the document into pages if required by the
// output format
page_pass::mk_pass(config.output_style),
// Render
markdown_pass::mk_pass(
markdown_writer::make_writer_factory(copy config)
)
]);
}
}
|
identifier_body
|
rustdoc.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.
//! Rustdoc - The Rust documentation generator
#[link(name = "rustdoc",
vers = "0.8-pre",
uuid = "f8abd014-b281-484d-a0c3-26e3de8e2412",
url = "https://github.com/mozilla/rust/tree/master/src/rustdoc")];
#[comment = "The Rust documentation generator"];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];
#[allow(non_implicitly_copyable_typarams)];
extern mod extra;
extern mod rustc;
extern mod syntax;
use std::io;
use std::os;
use config::Config;
use doc::Item;
use doc::ItemUtils;
pub mod pass;
pub mod config;
pub mod parse;
pub mod extract;
pub mod attr_parser;
pub mod doc;
pub mod markdown_index_pass;
pub mod markdown_pass;
pub mod markdown_writer;
pub mod fold;
pub mod path_pass;
pub mod attr_pass;
pub mod tystr_pass;
pub mod prune_hidden_pass;
pub mod desc_to_brief_pass;
pub mod text_pass;
pub mod unindent_pass;
pub mod trim_pass;
pub mod astsrv;
pub mod demo;
pub mod sort_pass;
pub mod sort_item_name_pass;
pub mod sort_item_type_pass;
pub mod page_pass;
pub mod sectionalize_pass;
pub mod escape_pass;
pub mod prune_private_pass;
pub mod util;
pub fn main() {
let args = os::args();
if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) {
config::usage();
return;
}
let config = match config::parse_config(args) {
Ok(config) => config,
Err(err) => {
io::println(fmt!("error: %s", err));
return;
}
};
run(config);
}
/// Runs rustdoc over the given file
fn
|
(config: Config) {
let source_file = copy config.input_crate;
// Create an AST service from the source code
do astsrv::from_file(source_file.to_str()) |srv| {
// Just time how long it takes for the AST to become available
do time(~"wait_ast") {
do astsrv::exec(srv.clone()) |_ctxt| { }
};
// Extract the initial doc tree from the AST. This contains
// just names and node ids.
let doc = time(~"extract", || {
let default_name = copy source_file;
extract::from_srv(srv.clone(), default_name.to_str())
});
// Refine and publish the document
pass::run_passes(srv, doc, ~[
// Generate type and signature strings
tystr_pass::mk_pass(),
// Record the full paths to various nodes
path_pass::mk_pass(),
// Extract the docs attributes and attach them to doc nodes
attr_pass::mk_pass(),
// Perform various text escaping
escape_pass::mk_pass(),
// Remove things marked doc(hidden)
prune_hidden_pass::mk_pass(),
// Remove things that are private
prune_private_pass::mk_pass(),
// Extract brief documentation from the full descriptions
desc_to_brief_pass::mk_pass(),
// Massage the text to remove extra indentation
unindent_pass::mk_pass(),
// Split text into multiple sections according to headers
sectionalize_pass::mk_pass(),
// Trim extra spaces from text
trim_pass::mk_pass(),
// Sort items by name
sort_item_name_pass::mk_pass(),
// Sort items again by kind
sort_item_type_pass::mk_pass(),
// Create indexes appropriate for markdown
markdown_index_pass::mk_pass(copy config),
// Break the document into pages if required by the
// output format
page_pass::mk_pass(config.output_style),
// Render
markdown_pass::mk_pass(
markdown_writer::make_writer_factory(copy config)
)
]);
}
}
pub fn time<T>(what: ~str, f: &fn() -> T) -> T {
let start = extra::time::precise_time_s();
let rv = f();
let end = extra::time::precise_time_s();
info!("time: %3.3f s %s", end - start, what);
rv
}
|
run
|
identifier_name
|
rustdoc.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.
//! Rustdoc - The Rust documentation generator
#[link(name = "rustdoc",
vers = "0.8-pre",
uuid = "f8abd014-b281-484d-a0c3-26e3de8e2412",
url = "https://github.com/mozilla/rust/tree/master/src/rustdoc")];
#[comment = "The Rust documentation generator"];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];
#[allow(non_implicitly_copyable_typarams)];
extern mod extra;
extern mod rustc;
extern mod syntax;
use std::io;
use std::os;
use config::Config;
use doc::Item;
use doc::ItemUtils;
pub mod pass;
pub mod config;
pub mod parse;
pub mod extract;
pub mod attr_parser;
pub mod doc;
pub mod markdown_index_pass;
pub mod markdown_pass;
pub mod markdown_writer;
pub mod fold;
pub mod path_pass;
pub mod attr_pass;
pub mod tystr_pass;
pub mod prune_hidden_pass;
pub mod desc_to_brief_pass;
pub mod text_pass;
pub mod unindent_pass;
pub mod trim_pass;
pub mod astsrv;
pub mod demo;
pub mod sort_pass;
pub mod sort_item_name_pass;
pub mod sort_item_type_pass;
pub mod page_pass;
pub mod sectionalize_pass;
pub mod escape_pass;
pub mod prune_private_pass;
pub mod util;
pub fn main() {
|
config::usage();
return;
}
let config = match config::parse_config(args) {
Ok(config) => config,
Err(err) => {
io::println(fmt!("error: %s", err));
return;
}
};
run(config);
}
/// Runs rustdoc over the given file
fn run(config: Config) {
let source_file = copy config.input_crate;
// Create an AST service from the source code
do astsrv::from_file(source_file.to_str()) |srv| {
// Just time how long it takes for the AST to become available
do time(~"wait_ast") {
do astsrv::exec(srv.clone()) |_ctxt| { }
};
// Extract the initial doc tree from the AST. This contains
// just names and node ids.
let doc = time(~"extract", || {
let default_name = copy source_file;
extract::from_srv(srv.clone(), default_name.to_str())
});
// Refine and publish the document
pass::run_passes(srv, doc, ~[
// Generate type and signature strings
tystr_pass::mk_pass(),
// Record the full paths to various nodes
path_pass::mk_pass(),
// Extract the docs attributes and attach them to doc nodes
attr_pass::mk_pass(),
// Perform various text escaping
escape_pass::mk_pass(),
// Remove things marked doc(hidden)
prune_hidden_pass::mk_pass(),
// Remove things that are private
prune_private_pass::mk_pass(),
// Extract brief documentation from the full descriptions
desc_to_brief_pass::mk_pass(),
// Massage the text to remove extra indentation
unindent_pass::mk_pass(),
// Split text into multiple sections according to headers
sectionalize_pass::mk_pass(),
// Trim extra spaces from text
trim_pass::mk_pass(),
// Sort items by name
sort_item_name_pass::mk_pass(),
// Sort items again by kind
sort_item_type_pass::mk_pass(),
// Create indexes appropriate for markdown
markdown_index_pass::mk_pass(copy config),
// Break the document into pages if required by the
// output format
page_pass::mk_pass(config.output_style),
// Render
markdown_pass::mk_pass(
markdown_writer::make_writer_factory(copy config)
)
]);
}
}
pub fn time<T>(what: ~str, f: &fn() -> T) -> T {
let start = extra::time::precise_time_s();
let rv = f();
let end = extra::time::precise_time_s();
info!("time: %3.3f s %s", end - start, what);
rv
}
|
let args = os::args();
if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) {
|
random_line_split
|
GenEdLookup.py
|
import numpy as np
import pandas as pd
import pickle
# Return 0 or 1 based on whether Course fulfills a General Education Requirement
def lookupGenEd(cNum, college):
fileName = "data/Dietrich Gen Eds.csv"
picklepath = "data\\dietrich_gen_eds.p"
try:
with open(picklepath,'rb') as file:
gen_eds = pickle.load(file)
except:
|
with open(picklepath,'wb') as file:
pickle.dump(gen_eds,file)
return cNum in gen_eds
'''
genEdubility = lookupGenEd(73100, "dietrich")
print("73100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(70100, "tepper")
print("70100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(15322, "scs")
print("15322")
print('Is Gen Ed?:', genEdubility)
print()
'''
|
df = pd.read_csv(fileName,names=['Dept','Num','Title','1','2'])
gen_eds = set(df['Dept'].values)
|
random_line_split
|
GenEdLookup.py
|
import numpy as np
import pandas as pd
import pickle
# Return 0 or 1 based on whether Course fulfills a General Education Requirement
def lookupGenEd(cNum, college):
|
'''
genEdubility = lookupGenEd(73100, "dietrich")
print("73100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(70100, "tepper")
print("70100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(15322, "scs")
print("15322")
print('Is Gen Ed?:', genEdubility)
print()
'''
|
fileName = "data/Dietrich Gen Eds.csv"
picklepath = "data\\dietrich_gen_eds.p"
try:
with open(picklepath,'rb') as file:
gen_eds = pickle.load(file)
except:
df = pd.read_csv(fileName,names=['Dept','Num','Title','1','2'])
gen_eds = set(df['Dept'].values)
with open(picklepath,'wb') as file:
pickle.dump(gen_eds,file)
return cNum in gen_eds
|
identifier_body
|
GenEdLookup.py
|
import numpy as np
import pandas as pd
import pickle
# Return 0 or 1 based on whether Course fulfills a General Education Requirement
def
|
(cNum, college):
fileName = "data/Dietrich Gen Eds.csv"
picklepath = "data\\dietrich_gen_eds.p"
try:
with open(picklepath,'rb') as file:
gen_eds = pickle.load(file)
except:
df = pd.read_csv(fileName,names=['Dept','Num','Title','1','2'])
gen_eds = set(df['Dept'].values)
with open(picklepath,'wb') as file:
pickle.dump(gen_eds,file)
return cNum in gen_eds
'''
genEdubility = lookupGenEd(73100, "dietrich")
print("73100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(70100, "tepper")
print("70100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(15322, "scs")
print("15322")
print('Is Gen Ed?:', genEdubility)
print()
'''
|
lookupGenEd
|
identifier_name
|
rgb24.rs
|
#[derive(Clone, Copy, Debug)]
pub struct Rgb24 {
pub red: u8,
pub green: u8,
pub blue: u8,
}
impl Rgb24 {
pub fn new(red: u8, green: u8, blue: u8) -> Self {
Rgb24 {
red: red,
green: green,
blue: blue,
}
}
pub fn
|
(self) -> u8 {
self.red
}
pub fn green(self) -> u8 {
self.green
}
pub fn blue(self) -> u8 {
self.blue
}
}
pub mod colours {
use super::*;
pub const RED: Rgb24 = Rgb24 { red: 255, green: 0, blue: 0 };
pub const GREEN: Rgb24 = Rgb24 { red: 0, green: 255, blue: 0 };
pub const BLUE: Rgb24 = Rgb24 { red: 0, green: 0, blue: 255 };
}
|
red
|
identifier_name
|
rgb24.rs
|
#[derive(Clone, Copy, Debug)]
pub struct Rgb24 {
pub red: u8,
pub green: u8,
pub blue: u8,
}
impl Rgb24 {
pub fn new(red: u8, green: u8, blue: u8) -> Self {
Rgb24 {
red: red,
green: green,
blue: blue,
}
}
pub fn red(self) -> u8 {
self.red
}
pub fn green(self) -> u8
|
pub fn blue(self) -> u8 {
self.blue
}
}
pub mod colours {
use super::*;
pub const RED: Rgb24 = Rgb24 { red: 255, green: 0, blue: 0 };
pub const GREEN: Rgb24 = Rgb24 { red: 0, green: 255, blue: 0 };
pub const BLUE: Rgb24 = Rgb24 { red: 0, green: 0, blue: 255 };
}
|
{
self.green
}
|
identifier_body
|
main.py
|
import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def getCommentsForItem(itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+itemID, None)
# print(item)
# print(item['kids'])
for commentID in item['kids']:
# print("inside loop. kid:", commentID)
commentID = str(commentID)
comment = firebase.get_async('/v0/item/'+commentID, None, callback=cbNewComment)
def getItems(items, startID=None, count=None):
if items is None and startID is None and count is None:
return
currentlyDownloading(True)
global getItemsCount
global itemIDs
items = str(items)
if count is None:
getItemsCount = 30
else:
getItemsCount = count
if startID is None:
itemIDs = firebase.get('/v0/'+items, None)
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
else:
allIDs = firebase.get('/v0/'+items, None)
startIDFound = False
for i in allIDs:
if i == startID:
startIDFound = True
continue
if startIDFound is False:
continue
itemIDs.append(i)
if len(itemIDs) >= getItemsCount:
break
if len(itemIDs) == 0:
resetDownloader()
currentlyDownloading(False)
return
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
itemID = None
i = 0
for itemID in itemIDs:
itemID = str(itemID)
item = firebase.get_async('/v0/item/'+itemID, None, callback=cbNewItem)
i += 1
if i >= getItemsCount:
break
def cbNewItem(response):
global eventCount
eventCount += 1
pyotherside.send('item-downloaded')
bufferResponse(response)
def cbNewComment(response):
# print("cbNewComment", response)
pyotherside.send('comment-downloaded', response)
def bufferResponse(response):
global getItemsCount
global eventCount
global itemIDs
global responses
responses.append(response)
# print(eventCount, getItemsCount)
if eventCount == getItemsCount:
orderedResponses = []
# print(itemIDs)
for r in responses:
index = itemIDs.index(r['id'])
if index is None:
continue
orderedResponses.insert(index, r)
sendResponses(orderedResponses)
def sendResponses(responses):
for r in responses:
pyotherside.send('new-item', r)
resetDownloader()
currentlyDownloading(False)
def resetDownloader():
|
def currentlyDownloading(b):
pyotherside.send('items-currently-downloading', b)
|
global eventCount
global itemIDs
global responses
global getItemsCount
eventCount = 0
itemIDs[:] = []
responses[:] = []
getItemsCount = 0
|
identifier_body
|
main.py
|
import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def getCommentsForItem(itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+itemID, None)
# print(item)
# print(item['kids'])
for commentID in item['kids']:
# print("inside loop. kid:", commentID)
commentID = str(commentID)
comment = firebase.get_async('/v0/item/'+commentID, None, callback=cbNewComment)
def getItems(items, startID=None, count=None):
if items is None and startID is None and count is None:
return
currentlyDownloading(True)
global getItemsCount
global itemIDs
items = str(items)
if count is None:
getItemsCount = 30
else:
getItemsCount = count
if startID is None:
itemIDs = firebase.get('/v0/'+items, None)
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
else:
allIDs = firebase.get('/v0/'+items, None)
startIDFound = False
for i in allIDs:
if i == startID:
|
if startIDFound is False:
continue
itemIDs.append(i)
if len(itemIDs) >= getItemsCount:
break
if len(itemIDs) == 0:
resetDownloader()
currentlyDownloading(False)
return
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
itemID = None
i = 0
for itemID in itemIDs:
itemID = str(itemID)
item = firebase.get_async('/v0/item/'+itemID, None, callback=cbNewItem)
i += 1
if i >= getItemsCount:
break
def cbNewItem(response):
global eventCount
eventCount += 1
pyotherside.send('item-downloaded')
bufferResponse(response)
def cbNewComment(response):
# print("cbNewComment", response)
pyotherside.send('comment-downloaded', response)
def bufferResponse(response):
global getItemsCount
global eventCount
global itemIDs
global responses
responses.append(response)
# print(eventCount, getItemsCount)
if eventCount == getItemsCount:
orderedResponses = []
# print(itemIDs)
for r in responses:
index = itemIDs.index(r['id'])
if index is None:
continue
orderedResponses.insert(index, r)
sendResponses(orderedResponses)
def sendResponses(responses):
for r in responses:
pyotherside.send('new-item', r)
resetDownloader()
currentlyDownloading(False)
def resetDownloader():
global eventCount
global itemIDs
global responses
global getItemsCount
eventCount = 0
itemIDs[:] = []
responses[:] = []
getItemsCount = 0
def currentlyDownloading(b):
pyotherside.send('items-currently-downloading', b)
|
startIDFound = True
continue
|
conditional_block
|
main.py
|
import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def
|
(itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+itemID, None)
# print(item)
# print(item['kids'])
for commentID in item['kids']:
# print("inside loop. kid:", commentID)
commentID = str(commentID)
comment = firebase.get_async('/v0/item/'+commentID, None, callback=cbNewComment)
def getItems(items, startID=None, count=None):
if items is None and startID is None and count is None:
return
currentlyDownloading(True)
global getItemsCount
global itemIDs
items = str(items)
if count is None:
getItemsCount = 30
else:
getItemsCount = count
if startID is None:
itemIDs = firebase.get('/v0/'+items, None)
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
else:
allIDs = firebase.get('/v0/'+items, None)
startIDFound = False
for i in allIDs:
if i == startID:
startIDFound = True
continue
if startIDFound is False:
continue
itemIDs.append(i)
if len(itemIDs) >= getItemsCount:
break
if len(itemIDs) == 0:
resetDownloader()
currentlyDownloading(False)
return
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
itemID = None
i = 0
for itemID in itemIDs:
itemID = str(itemID)
item = firebase.get_async('/v0/item/'+itemID, None, callback=cbNewItem)
i += 1
if i >= getItemsCount:
break
def cbNewItem(response):
global eventCount
eventCount += 1
pyotherside.send('item-downloaded')
bufferResponse(response)
def cbNewComment(response):
# print("cbNewComment", response)
pyotherside.send('comment-downloaded', response)
def bufferResponse(response):
global getItemsCount
global eventCount
global itemIDs
global responses
responses.append(response)
# print(eventCount, getItemsCount)
if eventCount == getItemsCount:
orderedResponses = []
# print(itemIDs)
for r in responses:
index = itemIDs.index(r['id'])
if index is None:
continue
orderedResponses.insert(index, r)
sendResponses(orderedResponses)
def sendResponses(responses):
for r in responses:
pyotherside.send('new-item', r)
resetDownloader()
currentlyDownloading(False)
def resetDownloader():
global eventCount
global itemIDs
global responses
global getItemsCount
eventCount = 0
itemIDs[:] = []
responses[:] = []
getItemsCount = 0
def currentlyDownloading(b):
pyotherside.send('items-currently-downloading', b)
|
getCommentsForItem
|
identifier_name
|
main.py
|
import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def getCommentsForItem(itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+itemID, None)
# print(item)
# print(item['kids'])
for commentID in item['kids']:
# print("inside loop. kid:", commentID)
commentID = str(commentID)
comment = firebase.get_async('/v0/item/'+commentID, None, callback=cbNewComment)
def getItems(items, startID=None, count=None):
if items is None and startID is None and count is None:
return
currentlyDownloading(True)
global getItemsCount
|
global itemIDs
items = str(items)
if count is None:
getItemsCount = 30
else:
getItemsCount = count
if startID is None:
itemIDs = firebase.get('/v0/'+items, None)
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
else:
allIDs = firebase.get('/v0/'+items, None)
startIDFound = False
for i in allIDs:
if i == startID:
startIDFound = True
continue
if startIDFound is False:
continue
itemIDs.append(i)
if len(itemIDs) >= getItemsCount:
break
if len(itemIDs) == 0:
resetDownloader()
currentlyDownloading(False)
return
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
itemID = None
i = 0
for itemID in itemIDs:
itemID = str(itemID)
item = firebase.get_async('/v0/item/'+itemID, None, callback=cbNewItem)
i += 1
if i >= getItemsCount:
break
def cbNewItem(response):
global eventCount
eventCount += 1
pyotherside.send('item-downloaded')
bufferResponse(response)
def cbNewComment(response):
# print("cbNewComment", response)
pyotherside.send('comment-downloaded', response)
def bufferResponse(response):
global getItemsCount
global eventCount
global itemIDs
global responses
responses.append(response)
# print(eventCount, getItemsCount)
if eventCount == getItemsCount:
orderedResponses = []
# print(itemIDs)
for r in responses:
index = itemIDs.index(r['id'])
if index is None:
continue
orderedResponses.insert(index, r)
sendResponses(orderedResponses)
def sendResponses(responses):
for r in responses:
pyotherside.send('new-item', r)
resetDownloader()
currentlyDownloading(False)
def resetDownloader():
global eventCount
global itemIDs
global responses
global getItemsCount
eventCount = 0
itemIDs[:] = []
responses[:] = []
getItemsCount = 0
def currentlyDownloading(b):
pyotherside.send('items-currently-downloading', b)
|
random_line_split
|
|
xbmc.js
|
angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',
command = {id: 1, jsonrpc: "2.0" };
//url = 'http://localhost:8200/'
function
|
(){
return _.cloneDeep( command );
}
function sendRequest( data ){
$log.debug("Sending " , data , " to " , url + 'jsonrpc');
return $http.post( url + 'jsonrpc' , data );
}
XBMC.sendText = function( text ){
var data = cmd();
data.params = { method: "Player.SendText", item: { text: text, done: true } };
return sendRequest( data );
}
XBMC.input = function( what ){
var data = cmd();
switch( what ){
case 'back':
data.method = "Input.Back";
break;
case 'left':
data.method = "Input.Left";
break;
case 'right':
data.method = "Input.right";
break;
case 'up':
data.method = "Input.Up";
break;
case 'down':
data.method = "Input.Down";
break;
case 'select':
data.method = "Input.Select";
break;
case 'info':
data.method = "Input.Info";
break;
case 'context':
data.method = "Input.ContextMenu";
break;
}
return sendRequest( data );
}
XBMC.sendToPlayer = function( link ){
var data = cmd();
data.params = { method: "Player.Open", item: { file: link } };
return sendRequest( data );
}
})
|
cmd
|
identifier_name
|
xbmc.js
|
angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',
command = {id: 1, jsonrpc: "2.0" };
//url = 'http://localhost:8200/'
function cmd(){
return _.cloneDeep( command );
}
function sendRequest( data )
|
XBMC.sendText = function( text ){
var data = cmd();
data.params = { method: "Player.SendText", item: { text: text, done: true } };
return sendRequest( data );
}
XBMC.input = function( what ){
var data = cmd();
switch( what ){
case 'back':
data.method = "Input.Back";
break;
case 'left':
data.method = "Input.Left";
break;
case 'right':
data.method = "Input.right";
break;
case 'up':
data.method = "Input.Up";
break;
case 'down':
data.method = "Input.Down";
break;
case 'select':
data.method = "Input.Select";
break;
case 'info':
data.method = "Input.Info";
break;
case 'context':
data.method = "Input.ContextMenu";
break;
}
return sendRequest( data );
}
XBMC.sendToPlayer = function( link ){
var data = cmd();
data.params = { method: "Player.Open", item: { file: link } };
return sendRequest( data );
}
})
|
{
$log.debug("Sending " , data , " to " , url + 'jsonrpc');
return $http.post( url + 'jsonrpc' , data );
}
|
identifier_body
|
xbmc.js
|
angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',
command = {id: 1, jsonrpc: "2.0" };
//url = 'http://localhost:8200/'
function cmd(){
return _.cloneDeep( command );
}
function sendRequest( data ){
$log.debug("Sending " , data , " to " , url + 'jsonrpc');
return $http.post( url + 'jsonrpc' , data );
}
XBMC.sendText = function( text ){
var data = cmd();
|
return sendRequest( data );
}
XBMC.input = function( what ){
var data = cmd();
switch( what ){
case 'back':
data.method = "Input.Back";
break;
case 'left':
data.method = "Input.Left";
break;
case 'right':
data.method = "Input.right";
break;
case 'up':
data.method = "Input.Up";
break;
case 'down':
data.method = "Input.Down";
break;
case 'select':
data.method = "Input.Select";
break;
case 'info':
data.method = "Input.Info";
break;
case 'context':
data.method = "Input.ContextMenu";
break;
}
return sendRequest( data );
}
XBMC.sendToPlayer = function( link ){
var data = cmd();
data.params = { method: "Player.Open", item: { file: link } };
return sendRequest( data );
}
})
|
data.params = { method: "Player.SendText", item: { text: text, done: true } };
|
random_line_split
|
notepad_slow.py
|
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Run some automations to test things"""
from __future__ import unicode_literals
from __future__ import print_function
import os.path
import sys
import time
try:
from pywinauto import application
except ImportError:
pywinauto_path = os.path.abspath(__file__)
pywinauto_path = os.path.split(os.path.split(pywinauto_path)[0])[0]
sys.path.append(pywinauto_path)
from pywinauto import application
from pywinauto import tests
from pywinauto.findbestmatch import MatchError
from pywinauto.timings import Timings
print("Setting timings to slow settings, may be necessary for")
print("slow applications or slow machines.")
Timings.slow()
#application.set_timing(3, .5, 10, .5, .4, .2, .2, .1, .2, .5)
def run_notepad():
|
if __name__ == "__main__":
run_notepad()
|
"""Run notepad and do some small stuff with it"""
start = time.time()
app = application.Application()
## for distribution we don't want to connect to anybodies application
## because we may mess up something they are working on!
#try:
# app.connect_(path = r"c:\windows\system32\notepad.exe")
#except application.ProcessNotFoundError:
# app.start_(r"c:\windows\system32\notepad.exe")
app.start(r"notepad.exe")
app.Notepad.menu_select("File->PageSetup")
# ----- Page Setup Dialog ----
# Select the 4th combobox item
app.PageSetupDlg.SizeComboBox.select(4)
# Select the 'Letter' combobox item or the Letter
try:
app.PageSetupDlg.SizeComboBox.select("Letter")
except ValueError:
app.PageSetupDlg.SizeComboBox.select('Letter (8.5" x 11")')
app.PageSetupDlg.SizeComboBox.select(2)
# run some tests on the Dialog. List of available tests:
# "AllControls",
# "AsianHotkey",
# "ComboBoxDroppedHeight",
# "CompareToRefFont",
# "LeadTrailSpaces",
# "MiscValues",
# "Missalignment",
# "MissingExtraString",
# "Overlapping",
# "RepeatedHotkey",
# "Translation",
# "Truncation",
bugs = app.PageSetupDlg.run_tests('RepeatedHotkey Truncation')
# if there are any bugs they will be printed to the console
# and the controls will be highlighted
tests.print_bugs(bugs)
# ----- Next Page Setup Dialog ----
app.PageSetupDlg.Printer.click()
# do some radio button clicks
# Open the Connect to printer dialog so we can
# try out checking/unchecking a checkbox
app.PageSetupDlg.Network.click()
# ----- Connect To Printer Dialog ----
# Select a checkbox
app.ConnectToPrinter.ExpandByDefault.check()
app.ConnectToPrinter.ExpandByDefault.uncheck()
# try doing the same by using click
app.ConnectToPrinter.ExpandByDefault.click()
app.ConnectToPrinter.ExpandByDefault.click()
# close the dialog
app.ConnectToPrinter.Cancel.close_click()
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.Properties.click()
doc_props = app.window(title_re = ".*Properties$")
doc_props.wait('exists', timeout=40)
# ----- Document Properties Dialog ----
# some tab control selections
# Two ways of selecting tabs with indices...
doc_props.TabCtrl.select(0)
doc_props.TabCtrl.select(1)
try:
doc_props.TabCtrl.select(2)
except IndexError:
# not all users have 3 tabs in this dialog
print('Skip 3rd tab selection...')
# or with text...
doc_props.TabCtrl.select("PaperQuality")
try:
doc_props.TabCtrl.select("JobRetention")
except MatchError:
# some people do not have the "Job Retention" tab
print('Skip "Job Retention" tab...')
# doc_props.TabCtrl.select("Layout")
#
# # do some radio button clicks
# doc_props.RotatedLandscape.click()
# doc_props.BackToFront.click()
# doc_props.FlipOnShortEdge.click()
#
# doc_props.Portrait.click()
# doc_props._None.click()
# doc_props.FrontToBack.click()
#
# # open the Advanced options dialog in two steps
# advbutton = doc_props.Advanced
# advbutton.click()
#
# # close the 4 windows
#
# # ----- Advanced Options Dialog ----
# app.window(title_re = ".* Advanced Options").Ok.click()
# ----- Document Properties Dialog again ----
doc_props.Cancel.close_click()
# for some reason my current printer driver
# window does not close cleanly :(
if doc_props.Cancel.Exists():
doc_props.OK.close_click()
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.OK.close_click()
# ----- Page Setup Dialog ----
app.PageSetupDlg.Ok.close_click()
# type some text - note that extended characters ARE allowed
app.Notepad.Edit.set_edit_text("I am typing s\xe4me text to Notepad\r\n\r\n"
"And then I am going to quit")
app.Notepad.Edit.right_click()
app.Popup.menu_item("Right To Left Reading Order").click()
#app.PopupMenu.menu_select("Paste", app.Notepad.ctrl_())
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Right To Left Reading Order", app.Notepad.ctrl_())
#app.PopupMenu.menu_select("Show unicode control characters", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Right To Left Reading Order", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Insert Unicode control character -> IAFS", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.type_keys("{ESC}")
# the following shows that Sendtext does not accept
# accented characters - but does allow 'control' characters
app.Notepad.Edit.type_keys("{END}{ENTER}SendText d\xf6\xe9s "
u"s\xfcpp\xf4rt \xe0cce\xf1ted characters!!!", with_spaces = True)
# Try and save
app.Notepad.menu_select("File->SaveAs")
app.SaveAs.EncodingComboBox.select("UTF-8")
app.SaveAs.FileNameEdit.set_edit_text("Example-utf8.txt")
app.SaveAs.Save.close_click()
# my machine has a weird problem - when connected to the network
# the SaveAs Dialog appears - but doing anything with it can
# cause a LONG delay - the easiest thing is to just wait
# until the dialog is no longer active
# - Dialog might just be gone - because click worked
# - dialog might be waiting to disappear
# so can't wait for next dialog or for it to be disabled
# - dialog might be waiting to display message box so can't wait
# for it to be gone or for the main dialog to be enabled.
# while the dialog exists wait upto 30 seconds (and yes it can
# take that long on my computer sometimes :-( )
app.SaveAsDialog2.Cancel.wait_not('enabled')
# If file exists - it asks you if you want to overwrite
try:
app.SaveAs.Yes.wait('exists').close_click()
except MatchError:
print('Skip overwriting...')
# exit notepad
app.Notepad.menu_select("File->Exit")
#if not run_with_appdata:
# app.WriteAppData(os.path.join(scriptdir, "Notepad_fast.pkl"))
print("That took %.3f to run"% (time.time() - start))
|
identifier_body
|
notepad_slow.py
|
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Run some automations to test things"""
from __future__ import unicode_literals
from __future__ import print_function
import os.path
import sys
import time
try:
from pywinauto import application
except ImportError:
pywinauto_path = os.path.abspath(__file__)
pywinauto_path = os.path.split(os.path.split(pywinauto_path)[0])[0]
sys.path.append(pywinauto_path)
from pywinauto import application
from pywinauto import tests
from pywinauto.findbestmatch import MatchError
from pywinauto.timings import Timings
print("Setting timings to slow settings, may be necessary for")
print("slow applications or slow machines.")
Timings.slow()
#application.set_timing(3, .5, 10, .5, .4, .2, .2, .1, .2, .5)
def run_notepad():
"""Run notepad and do some small stuff with it"""
start = time.time()
app = application.Application()
## for distribution we don't want to connect to anybodies application
## because we may mess up something they are working on!
#try:
# app.connect_(path = r"c:\windows\system32\notepad.exe")
#except application.ProcessNotFoundError:
# app.start_(r"c:\windows\system32\notepad.exe")
app.start(r"notepad.exe")
|
app.Notepad.menu_select("File->PageSetup")
# ----- Page Setup Dialog ----
# Select the 4th combobox item
app.PageSetupDlg.SizeComboBox.select(4)
# Select the 'Letter' combobox item or the Letter
try:
app.PageSetupDlg.SizeComboBox.select("Letter")
except ValueError:
app.PageSetupDlg.SizeComboBox.select('Letter (8.5" x 11")')
app.PageSetupDlg.SizeComboBox.select(2)
# run some tests on the Dialog. List of available tests:
# "AllControls",
# "AsianHotkey",
# "ComboBoxDroppedHeight",
# "CompareToRefFont",
# "LeadTrailSpaces",
# "MiscValues",
# "Missalignment",
# "MissingExtraString",
# "Overlapping",
# "RepeatedHotkey",
# "Translation",
# "Truncation",
bugs = app.PageSetupDlg.run_tests('RepeatedHotkey Truncation')
# if there are any bugs they will be printed to the console
# and the controls will be highlighted
tests.print_bugs(bugs)
# ----- Next Page Setup Dialog ----
app.PageSetupDlg.Printer.click()
# do some radio button clicks
# Open the Connect to printer dialog so we can
# try out checking/unchecking a checkbox
app.PageSetupDlg.Network.click()
# ----- Connect To Printer Dialog ----
# Select a checkbox
app.ConnectToPrinter.ExpandByDefault.check()
app.ConnectToPrinter.ExpandByDefault.uncheck()
# try doing the same by using click
app.ConnectToPrinter.ExpandByDefault.click()
app.ConnectToPrinter.ExpandByDefault.click()
# close the dialog
app.ConnectToPrinter.Cancel.close_click()
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.Properties.click()
doc_props = app.window(title_re = ".*Properties$")
doc_props.wait('exists', timeout=40)
# ----- Document Properties Dialog ----
# some tab control selections
# Two ways of selecting tabs with indices...
doc_props.TabCtrl.select(0)
doc_props.TabCtrl.select(1)
try:
doc_props.TabCtrl.select(2)
except IndexError:
# not all users have 3 tabs in this dialog
print('Skip 3rd tab selection...')
# or with text...
doc_props.TabCtrl.select("PaperQuality")
try:
doc_props.TabCtrl.select("JobRetention")
except MatchError:
# some people do not have the "Job Retention" tab
print('Skip "Job Retention" tab...')
# doc_props.TabCtrl.select("Layout")
#
# # do some radio button clicks
# doc_props.RotatedLandscape.click()
# doc_props.BackToFront.click()
# doc_props.FlipOnShortEdge.click()
#
# doc_props.Portrait.click()
# doc_props._None.click()
# doc_props.FrontToBack.click()
#
# # open the Advanced options dialog in two steps
# advbutton = doc_props.Advanced
# advbutton.click()
#
# # close the 4 windows
#
# # ----- Advanced Options Dialog ----
# app.window(title_re = ".* Advanced Options").Ok.click()
# ----- Document Properties Dialog again ----
doc_props.Cancel.close_click()
# for some reason my current printer driver
# window does not close cleanly :(
if doc_props.Cancel.Exists():
doc_props.OK.close_click()
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.OK.close_click()
# ----- Page Setup Dialog ----
app.PageSetupDlg.Ok.close_click()
# type some text - note that extended characters ARE allowed
app.Notepad.Edit.set_edit_text("I am typing s\xe4me text to Notepad\r\n\r\n"
"And then I am going to quit")
app.Notepad.Edit.right_click()
app.Popup.menu_item("Right To Left Reading Order").click()
#app.PopupMenu.menu_select("Paste", app.Notepad.ctrl_())
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Right To Left Reading Order", app.Notepad.ctrl_())
#app.PopupMenu.menu_select("Show unicode control characters", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Right To Left Reading Order", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Insert Unicode control character -> IAFS", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.type_keys("{ESC}")
# the following shows that Sendtext does not accept
# accented characters - but does allow 'control' characters
app.Notepad.Edit.type_keys("{END}{ENTER}SendText d\xf6\xe9s "
u"s\xfcpp\xf4rt \xe0cce\xf1ted characters!!!", with_spaces = True)
# Try and save
app.Notepad.menu_select("File->SaveAs")
app.SaveAs.EncodingComboBox.select("UTF-8")
app.SaveAs.FileNameEdit.set_edit_text("Example-utf8.txt")
app.SaveAs.Save.close_click()
# my machine has a weird problem - when connected to the network
# the SaveAs Dialog appears - but doing anything with it can
# cause a LONG delay - the easiest thing is to just wait
# until the dialog is no longer active
# - Dialog might just be gone - because click worked
# - dialog might be waiting to disappear
# so can't wait for next dialog or for it to be disabled
# - dialog might be waiting to display message box so can't wait
# for it to be gone or for the main dialog to be enabled.
# while the dialog exists wait upto 30 seconds (and yes it can
# take that long on my computer sometimes :-( )
app.SaveAsDialog2.Cancel.wait_not('enabled')
# If file exists - it asks you if you want to overwrite
try:
app.SaveAs.Yes.wait('exists').close_click()
except MatchError:
print('Skip overwriting...')
# exit notepad
app.Notepad.menu_select("File->Exit")
#if not run_with_appdata:
# app.WriteAppData(os.path.join(scriptdir, "Notepad_fast.pkl"))
print("That took %.3f to run"% (time.time() - start))
if __name__ == "__main__":
run_notepad()
|
random_line_split
|
|
notepad_slow.py
|
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Run some automations to test things"""
from __future__ import unicode_literals
from __future__ import print_function
import os.path
import sys
import time
try:
from pywinauto import application
except ImportError:
pywinauto_path = os.path.abspath(__file__)
pywinauto_path = os.path.split(os.path.split(pywinauto_path)[0])[0]
sys.path.append(pywinauto_path)
from pywinauto import application
from pywinauto import tests
from pywinauto.findbestmatch import MatchError
from pywinauto.timings import Timings
print("Setting timings to slow settings, may be necessary for")
print("slow applications or slow machines.")
Timings.slow()
#application.set_timing(3, .5, 10, .5, .4, .2, .2, .1, .2, .5)
def run_notepad():
"""Run notepad and do some small stuff with it"""
start = time.time()
app = application.Application()
## for distribution we don't want to connect to anybodies application
## because we may mess up something they are working on!
#try:
# app.connect_(path = r"c:\windows\system32\notepad.exe")
#except application.ProcessNotFoundError:
# app.start_(r"c:\windows\system32\notepad.exe")
app.start(r"notepad.exe")
app.Notepad.menu_select("File->PageSetup")
# ----- Page Setup Dialog ----
# Select the 4th combobox item
app.PageSetupDlg.SizeComboBox.select(4)
# Select the 'Letter' combobox item or the Letter
try:
app.PageSetupDlg.SizeComboBox.select("Letter")
except ValueError:
app.PageSetupDlg.SizeComboBox.select('Letter (8.5" x 11")')
app.PageSetupDlg.SizeComboBox.select(2)
# run some tests on the Dialog. List of available tests:
# "AllControls",
# "AsianHotkey",
# "ComboBoxDroppedHeight",
# "CompareToRefFont",
# "LeadTrailSpaces",
# "MiscValues",
# "Missalignment",
# "MissingExtraString",
# "Overlapping",
# "RepeatedHotkey",
# "Translation",
# "Truncation",
bugs = app.PageSetupDlg.run_tests('RepeatedHotkey Truncation')
# if there are any bugs they will be printed to the console
# and the controls will be highlighted
tests.print_bugs(bugs)
# ----- Next Page Setup Dialog ----
app.PageSetupDlg.Printer.click()
# do some radio button clicks
# Open the Connect to printer dialog so we can
# try out checking/unchecking a checkbox
app.PageSetupDlg.Network.click()
# ----- Connect To Printer Dialog ----
# Select a checkbox
app.ConnectToPrinter.ExpandByDefault.check()
app.ConnectToPrinter.ExpandByDefault.uncheck()
# try doing the same by using click
app.ConnectToPrinter.ExpandByDefault.click()
app.ConnectToPrinter.ExpandByDefault.click()
# close the dialog
app.ConnectToPrinter.Cancel.close_click()
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.Properties.click()
doc_props = app.window(title_re = ".*Properties$")
doc_props.wait('exists', timeout=40)
# ----- Document Properties Dialog ----
# some tab control selections
# Two ways of selecting tabs with indices...
doc_props.TabCtrl.select(0)
doc_props.TabCtrl.select(1)
try:
doc_props.TabCtrl.select(2)
except IndexError:
# not all users have 3 tabs in this dialog
print('Skip 3rd tab selection...')
# or with text...
doc_props.TabCtrl.select("PaperQuality")
try:
doc_props.TabCtrl.select("JobRetention")
except MatchError:
# some people do not have the "Job Retention" tab
print('Skip "Job Retention" tab...')
# doc_props.TabCtrl.select("Layout")
#
# # do some radio button clicks
# doc_props.RotatedLandscape.click()
# doc_props.BackToFront.click()
# doc_props.FlipOnShortEdge.click()
#
# doc_props.Portrait.click()
# doc_props._None.click()
# doc_props.FrontToBack.click()
#
# # open the Advanced options dialog in two steps
# advbutton = doc_props.Advanced
# advbutton.click()
#
# # close the 4 windows
#
# # ----- Advanced Options Dialog ----
# app.window(title_re = ".* Advanced Options").Ok.click()
# ----- Document Properties Dialog again ----
doc_props.Cancel.close_click()
# for some reason my current printer driver
# window does not close cleanly :(
if doc_props.Cancel.Exists():
|
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.OK.close_click()
# ----- Page Setup Dialog ----
app.PageSetupDlg.Ok.close_click()
# type some text - note that extended characters ARE allowed
app.Notepad.Edit.set_edit_text("I am typing s\xe4me text to Notepad\r\n\r\n"
"And then I am going to quit")
app.Notepad.Edit.right_click()
app.Popup.menu_item("Right To Left Reading Order").click()
#app.PopupMenu.menu_select("Paste", app.Notepad.ctrl_())
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Right To Left Reading Order", app.Notepad.ctrl_())
#app.PopupMenu.menu_select("Show unicode control characters", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Right To Left Reading Order", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Insert Unicode control character -> IAFS", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.type_keys("{ESC}")
# the following shows that Sendtext does not accept
# accented characters - but does allow 'control' characters
app.Notepad.Edit.type_keys("{END}{ENTER}SendText d\xf6\xe9s "
u"s\xfcpp\xf4rt \xe0cce\xf1ted characters!!!", with_spaces = True)
# Try and save
app.Notepad.menu_select("File->SaveAs")
app.SaveAs.EncodingComboBox.select("UTF-8")
app.SaveAs.FileNameEdit.set_edit_text("Example-utf8.txt")
app.SaveAs.Save.close_click()
# my machine has a weird problem - when connected to the network
# the SaveAs Dialog appears - but doing anything with it can
# cause a LONG delay - the easiest thing is to just wait
# until the dialog is no longer active
# - Dialog might just be gone - because click worked
# - dialog might be waiting to disappear
# so can't wait for next dialog or for it to be disabled
# - dialog might be waiting to display message box so can't wait
# for it to be gone or for the main dialog to be enabled.
# while the dialog exists wait upto 30 seconds (and yes it can
# take that long on my computer sometimes :-( )
app.SaveAsDialog2.Cancel.wait_not('enabled')
# If file exists - it asks you if you want to overwrite
try:
app.SaveAs.Yes.wait('exists').close_click()
except MatchError:
print('Skip overwriting...')
# exit notepad
app.Notepad.menu_select("File->Exit")
#if not run_with_appdata:
# app.WriteAppData(os.path.join(scriptdir, "Notepad_fast.pkl"))
print("That took %.3f to run"% (time.time() - start))
if __name__ == "__main__":
run_notepad()
|
doc_props.OK.close_click()
|
conditional_block
|
notepad_slow.py
|
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Run some automations to test things"""
from __future__ import unicode_literals
from __future__ import print_function
import os.path
import sys
import time
try:
from pywinauto import application
except ImportError:
pywinauto_path = os.path.abspath(__file__)
pywinauto_path = os.path.split(os.path.split(pywinauto_path)[0])[0]
sys.path.append(pywinauto_path)
from pywinauto import application
from pywinauto import tests
from pywinauto.findbestmatch import MatchError
from pywinauto.timings import Timings
print("Setting timings to slow settings, may be necessary for")
print("slow applications or slow machines.")
Timings.slow()
#application.set_timing(3, .5, 10, .5, .4, .2, .2, .1, .2, .5)
def
|
():
"""Run notepad and do some small stuff with it"""
start = time.time()
app = application.Application()
## for distribution we don't want to connect to anybodies application
## because we may mess up something they are working on!
#try:
# app.connect_(path = r"c:\windows\system32\notepad.exe")
#except application.ProcessNotFoundError:
# app.start_(r"c:\windows\system32\notepad.exe")
app.start(r"notepad.exe")
app.Notepad.menu_select("File->PageSetup")
# ----- Page Setup Dialog ----
# Select the 4th combobox item
app.PageSetupDlg.SizeComboBox.select(4)
# Select the 'Letter' combobox item or the Letter
try:
app.PageSetupDlg.SizeComboBox.select("Letter")
except ValueError:
app.PageSetupDlg.SizeComboBox.select('Letter (8.5" x 11")')
app.PageSetupDlg.SizeComboBox.select(2)
# run some tests on the Dialog. List of available tests:
# "AllControls",
# "AsianHotkey",
# "ComboBoxDroppedHeight",
# "CompareToRefFont",
# "LeadTrailSpaces",
# "MiscValues",
# "Missalignment",
# "MissingExtraString",
# "Overlapping",
# "RepeatedHotkey",
# "Translation",
# "Truncation",
bugs = app.PageSetupDlg.run_tests('RepeatedHotkey Truncation')
# if there are any bugs they will be printed to the console
# and the controls will be highlighted
tests.print_bugs(bugs)
# ----- Next Page Setup Dialog ----
app.PageSetupDlg.Printer.click()
# do some radio button clicks
# Open the Connect to printer dialog so we can
# try out checking/unchecking a checkbox
app.PageSetupDlg.Network.click()
# ----- Connect To Printer Dialog ----
# Select a checkbox
app.ConnectToPrinter.ExpandByDefault.check()
app.ConnectToPrinter.ExpandByDefault.uncheck()
# try doing the same by using click
app.ConnectToPrinter.ExpandByDefault.click()
app.ConnectToPrinter.ExpandByDefault.click()
# close the dialog
app.ConnectToPrinter.Cancel.close_click()
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.Properties.click()
doc_props = app.window(title_re = ".*Properties$")
doc_props.wait('exists', timeout=40)
# ----- Document Properties Dialog ----
# some tab control selections
# Two ways of selecting tabs with indices...
doc_props.TabCtrl.select(0)
doc_props.TabCtrl.select(1)
try:
doc_props.TabCtrl.select(2)
except IndexError:
# not all users have 3 tabs in this dialog
print('Skip 3rd tab selection...')
# or with text...
doc_props.TabCtrl.select("PaperQuality")
try:
doc_props.TabCtrl.select("JobRetention")
except MatchError:
# some people do not have the "Job Retention" tab
print('Skip "Job Retention" tab...')
# doc_props.TabCtrl.select("Layout")
#
# # do some radio button clicks
# doc_props.RotatedLandscape.click()
# doc_props.BackToFront.click()
# doc_props.FlipOnShortEdge.click()
#
# doc_props.Portrait.click()
# doc_props._None.click()
# doc_props.FrontToBack.click()
#
# # open the Advanced options dialog in two steps
# advbutton = doc_props.Advanced
# advbutton.click()
#
# # close the 4 windows
#
# # ----- Advanced Options Dialog ----
# app.window(title_re = ".* Advanced Options").Ok.click()
# ----- Document Properties Dialog again ----
doc_props.Cancel.close_click()
# for some reason my current printer driver
# window does not close cleanly :(
if doc_props.Cancel.Exists():
doc_props.OK.close_click()
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.OK.close_click()
# ----- Page Setup Dialog ----
app.PageSetupDlg.Ok.close_click()
# type some text - note that extended characters ARE allowed
app.Notepad.Edit.set_edit_text("I am typing s\xe4me text to Notepad\r\n\r\n"
"And then I am going to quit")
app.Notepad.Edit.right_click()
app.Popup.menu_item("Right To Left Reading Order").click()
#app.PopupMenu.menu_select("Paste", app.Notepad.ctrl_())
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Right To Left Reading Order", app.Notepad.ctrl_())
#app.PopupMenu.menu_select("Show unicode control characters", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Right To Left Reading Order", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.right_click()
#app.PopupMenu.menu_select("Insert Unicode control character -> IAFS", app.Notepad.ctrl_())
#time.sleep(1)
#app.Notepad.Edit.type_keys("{ESC}")
# the following shows that Sendtext does not accept
# accented characters - but does allow 'control' characters
app.Notepad.Edit.type_keys("{END}{ENTER}SendText d\xf6\xe9s "
u"s\xfcpp\xf4rt \xe0cce\xf1ted characters!!!", with_spaces = True)
# Try and save
app.Notepad.menu_select("File->SaveAs")
app.SaveAs.EncodingComboBox.select("UTF-8")
app.SaveAs.FileNameEdit.set_edit_text("Example-utf8.txt")
app.SaveAs.Save.close_click()
# my machine has a weird problem - when connected to the network
# the SaveAs Dialog appears - but doing anything with it can
# cause a LONG delay - the easiest thing is to just wait
# until the dialog is no longer active
# - Dialog might just be gone - because click worked
# - dialog might be waiting to disappear
# so can't wait for next dialog or for it to be disabled
# - dialog might be waiting to display message box so can't wait
# for it to be gone or for the main dialog to be enabled.
# while the dialog exists wait upto 30 seconds (and yes it can
# take that long on my computer sometimes :-( )
app.SaveAsDialog2.Cancel.wait_not('enabled')
# If file exists - it asks you if you want to overwrite
try:
app.SaveAs.Yes.wait('exists').close_click()
except MatchError:
print('Skip overwriting...')
# exit notepad
app.Notepad.menu_select("File->Exit")
#if not run_with_appdata:
# app.WriteAppData(os.path.join(scriptdir, "Notepad_fast.pkl"))
print("That took %.3f to run"% (time.time() - start))
if __name__ == "__main__":
run_notepad()
|
run_notepad
|
identifier_name
|
appServerAlertsDetails.ts
|
///
/// Copyright 2015 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// <reference path="../metricsPlugin.ts"/>
/// <reference path="../services/alertsManager.ts"/>
/// <reference path="../services/errorsManager.ts"/>
module HawkularMetrics {
export class
|
{
}
_module.controller('HawkularMetrics.AppServerAlertsDetailsController', AppServerAlertsDetailsController);
}
|
AppServerAlertsDetailsController
|
identifier_name
|
appServerAlertsDetails.ts
|
///
/// Copyright 2015 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// <reference path="../metricsPlugin.ts"/>
/// <reference path="../services/alertsManager.ts"/>
/// <reference path="../services/errorsManager.ts"/>
module HawkularMetrics {
|
export class AppServerAlertsDetailsController {
}
_module.controller('HawkularMetrics.AppServerAlertsDetailsController', AppServerAlertsDetailsController);
}
|
random_line_split
|
|
cards.js
|
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 1024,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
}
function create ()
{
// Create a stack of random cards
var frames = this.textures.get('cards').getFrameNames();
var x = 100;
var y = 100;
for (var i = 0; i < 64; i++)
|
this.input.on('gameobjectdown', function (pointer, gameObject) {
// Will contain the top-most Game Object (in the display list)
this.tweens.add({
targets: gameObject,
x: { value: 1100, duration: 1500, ease: 'Power2' },
y: { value: 500, duration: 500, ease: 'Bounce.easeOut', delay: 150 }
});
}, this);
}
|
{
this.add.image(x, y, 'cards', Phaser.Math.RND.pick(frames)).setInteractive();
x += 4;
y += 4;
}
|
conditional_block
|
cards.js
|
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 1024,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
|
function create ()
{
// Create a stack of random cards
var frames = this.textures.get('cards').getFrameNames();
var x = 100;
var y = 100;
for (var i = 0; i < 64; i++)
{
this.add.image(x, y, 'cards', Phaser.Math.RND.pick(frames)).setInteractive();
x += 4;
y += 4;
}
this.input.on('gameobjectdown', function (pointer, gameObject) {
// Will contain the top-most Game Object (in the display list)
this.tweens.add({
targets: gameObject,
x: { value: 1100, duration: 1500, ease: 'Power2' },
y: { value: 500, duration: 500, ease: 'Bounce.easeOut', delay: 150 }
});
}, this);
}
|
{
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
}
|
identifier_body
|
cards.js
|
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 1024,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
}
function create ()
{
// Create a stack of random cards
var frames = this.textures.get('cards').getFrameNames();
var x = 100;
var y = 100;
for (var i = 0; i < 64; i++)
{
this.add.image(x, y, 'cards', Phaser.Math.RND.pick(frames)).setInteractive();
x += 4;
y += 4;
}
this.input.on('gameobjectdown', function (pointer, gameObject) {
// Will contain the top-most Game Object (in the display list)
this.tweens.add({
targets: gameObject,
x: { value: 1100, duration: 1500, ease: 'Power2' },
y: { value: 500, duration: 500, ease: 'Bounce.easeOut', delay: 150 }
});
}, this);
|
}
|
random_line_split
|
|
cards.js
|
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 1024,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
}
function
|
()
{
// Create a stack of random cards
var frames = this.textures.get('cards').getFrameNames();
var x = 100;
var y = 100;
for (var i = 0; i < 64; i++)
{
this.add.image(x, y, 'cards', Phaser.Math.RND.pick(frames)).setInteractive();
x += 4;
y += 4;
}
this.input.on('gameobjectdown', function (pointer, gameObject) {
// Will contain the top-most Game Object (in the display list)
this.tweens.add({
targets: gameObject,
x: { value: 1100, duration: 1500, ease: 'Power2' },
y: { value: 500, duration: 500, ease: 'Bounce.easeOut', delay: 150 }
});
}, this);
}
|
create
|
identifier_name
|
DistributedCartesianGridAI.py
|
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNotify.newCategory("DistributedCartesianGridAI")
RuleSeparator = ":"
def __init__(self, air, startingZone, gridSize, gridRadius, cellWidth,
style="Cartesian"):
DistributedNodeAI.__init__(self, air)
self.style = style
self.startingZone = startingZone
self.gridSize = gridSize
self.gridRadius = gridRadius
self.cellWidth = cellWidth
# Keep track of all AI objects added to the grid
self.gridObjects = {}
self.updateTaskStarted = 0
def delete(self):
DistributedNodeAI.delete(self)
self.stopUpdateGridTask()
def isGridParent(self):
# If this distributed object is a DistributedGrid return 1.
# 0 by default
return 1
def getCellWidth(self):
|
def getParentingRules(self):
self.notify.debug("calling getter")
rule = ("%i%s%i%s%i" % (self.startingZone, self.RuleSeparator,
self.gridSize, self.RuleSeparator,
self.gridRadius))
return [self.style, rule]
# Reparent and setLocation on av to DistributedOceanGrid
def addObjectToGrid(self, av, useZoneId=-1, startAutoUpdate=True):
self.notify.debug("setting parent to grid %s" % self)
avId = av.doId
# Create a grid parent
#gridParent = self.attachNewNode("gridParent-%s" % avId)
#self.gridParents[avId] = gridParent
self.gridObjects[avId] = av
# Put the avatar on the grid
self.handleAvatarZoneChange(av, useZoneId)
if (not self.updateTaskStarted) and startAutoUpdate:
self.startUpdateGridTask()
def removeObjectFromGrid(self, av):
# TODO: WHAT LOCATION SHOULD WE SET THIS TO?
#av.wrtReparentTo(self.parentNP)
#av.setLocation(self.air.districtId, 1000)
# Remove grid parent for this av
avId = av.doId
if avId in self.gridObjects:
del self.gridObjects[avId]
# Stop task if there are no more av's being managed
if len(self.gridObjects) == 0:
self.stopUpdateGridTask()
#####################################################################
# updateGridTask
# This task is similar to the processVisibility task for the local client.
# A couple differences:
# - we are not doing setInterest on the AI (that is a local client
# specific call).
# - we assume that the moving objects on the grid are parented to a
# gridParent, and are broadcasting their position relative to that
# gridParent. This makes the task's math easy. Just check to see
# when our position goes out of the current grid cell. When it does,
# call handleAvatarZoneChange
def startUpdateGridTask(self):
self.stopUpdateGridTask()
self.updateTaskStarted = 1
taskMgr.add(self.updateGridTask, self.taskName("updateGridTask"))
def stopUpdateGridTask(self):
taskMgr.remove(self.taskName("updateGridTask"))
self.updateTaskStarted = 0
def updateGridTask(self, task=None):
# Run through all grid objects and update their parents if needed
missingObjs = []
for avId in self.gridObjects.keys():
av = self.gridObjects[avId]
# handle a missing object after it is already gone?
if (av.isEmpty()):
task.setDelay(1.0)
del self.gridObjects[avId]
continue
pos = av.getPos()
if ((pos[0] < 0 or pos[1] < 0) or
(pos[0] > self.cellWidth or pos[1] > self.cellWidth)):
# we are out of the bounds of this current cell
self.handleAvatarZoneChange(av)
# Do this every second, not every frame
if (task):
task.setDelay(1.0)
return Task.again
def handleAvatarZoneChange(self, av, useZoneId=-1):
# Calculate zone id
# Get position of av relative to this grid
if (useZoneId == -1):
pos = av.getPos(self)
zoneId = self.getZoneFromXYZ(pos)
else:
# zone already calculated, position of object might not
# give the correct zone
pos = None
zoneId = useZoneId
if not self.isValidZone(zoneId):
self.notify.warning(
"%s handleAvatarZoneChange %s: not a valid zone (%s) for pos %s" %(self.doId, av.doId, zoneId, pos))
return
# Set the location on the server.
# setLocation will update the gridParent
av.b_setLocation(self.doId, zoneId)
def handleSetLocation(self, av, parentId, zoneId):
pass
#if (av.parentId != parentId):
# parent changed, need to look up instance tree
# to see if avatar's named area location information
# changed
#av.requestRegionUpdateTask(regionegionUid)
|
return self.cellWidth
|
identifier_body
|
DistributedCartesianGridAI.py
|
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNotify.newCategory("DistributedCartesianGridAI")
RuleSeparator = ":"
def __init__(self, air, startingZone, gridSize, gridRadius, cellWidth,
style="Cartesian"):
DistributedNodeAI.__init__(self, air)
self.style = style
self.startingZone = startingZone
self.gridSize = gridSize
self.gridRadius = gridRadius
self.cellWidth = cellWidth
# Keep track of all AI objects added to the grid
self.gridObjects = {}
self.updateTaskStarted = 0
def delete(self):
DistributedNodeAI.delete(self)
self.stopUpdateGridTask()
def isGridParent(self):
# If this distributed object is a DistributedGrid return 1.
# 0 by default
return 1
def getCellWidth(self):
return self.cellWidth
def getParentingRules(self):
self.notify.debug("calling getter")
rule = ("%i%s%i%s%i" % (self.startingZone, self.RuleSeparator,
self.gridSize, self.RuleSeparator,
self.gridRadius))
return [self.style, rule]
# Reparent and setLocation on av to DistributedOceanGrid
def addObjectToGrid(self, av, useZoneId=-1, startAutoUpdate=True):
self.notify.debug("setting parent to grid %s" % self)
avId = av.doId
# Create a grid parent
#gridParent = self.attachNewNode("gridParent-%s" % avId)
#self.gridParents[avId] = gridParent
self.gridObjects[avId] = av
# Put the avatar on the grid
self.handleAvatarZoneChange(av, useZoneId)
if (not self.updateTaskStarted) and startAutoUpdate:
self.startUpdateGridTask()
def removeObjectFromGrid(self, av):
# TODO: WHAT LOCATION SHOULD WE SET THIS TO?
#av.wrtReparentTo(self.parentNP)
#av.setLocation(self.air.districtId, 1000)
# Remove grid parent for this av
avId = av.doId
if avId in self.gridObjects:
del self.gridObjects[avId]
# Stop task if there are no more av's being managed
if len(self.gridObjects) == 0:
self.stopUpdateGridTask()
#####################################################################
# updateGridTask
# This task is similar to the processVisibility task for the local client.
# A couple differences:
# - we are not doing setInterest on the AI (that is a local client
# specific call).
# - we assume that the moving objects on the grid are parented to a
# gridParent, and are broadcasting their position relative to that
# gridParent. This makes the task's math easy. Just check to see
# when our position goes out of the current grid cell. When it does,
# call handleAvatarZoneChange
def startUpdateGridTask(self):
self.stopUpdateGridTask()
self.updateTaskStarted = 1
taskMgr.add(self.updateGridTask, self.taskName("updateGridTask"))
def stopUpdateGridTask(self):
taskMgr.remove(self.taskName("updateGridTask"))
self.updateTaskStarted = 0
def updateGridTask(self, task=None):
# Run through all grid objects and update their parents if needed
missingObjs = []
for avId in self.gridObjects.keys():
av = self.gridObjects[avId]
# handle a missing object after it is already gone?
if (av.isEmpty()):
task.setDelay(1.0)
del self.gridObjects[avId]
continue
pos = av.getPos()
if ((pos[0] < 0 or pos[1] < 0) or
(pos[0] > self.cellWidth or pos[1] > self.cellWidth)):
# we are out of the bounds of this current cell
self.handleAvatarZoneChange(av)
# Do this every second, not every frame
if (task):
task.setDelay(1.0)
return Task.again
def handleAvatarZoneChange(self, av, useZoneId=-1):
# Calculate zone id
# Get position of av relative to this grid
if (useZoneId == -1):
pos = av.getPos(self)
zoneId = self.getZoneFromXYZ(pos)
else:
# zone already calculated, position of object might not
# give the correct zone
|
if not self.isValidZone(zoneId):
self.notify.warning(
"%s handleAvatarZoneChange %s: not a valid zone (%s) for pos %s" %(self.doId, av.doId, zoneId, pos))
return
# Set the location on the server.
# setLocation will update the gridParent
av.b_setLocation(self.doId, zoneId)
def handleSetLocation(self, av, parentId, zoneId):
pass
#if (av.parentId != parentId):
# parent changed, need to look up instance tree
# to see if avatar's named area location information
# changed
#av.requestRegionUpdateTask(regionegionUid)
|
pos = None
zoneId = useZoneId
|
conditional_block
|
DistributedCartesianGridAI.py
|
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNotify.newCategory("DistributedCartesianGridAI")
RuleSeparator = ":"
def __init__(self, air, startingZone, gridSize, gridRadius, cellWidth,
style="Cartesian"):
DistributedNodeAI.__init__(self, air)
self.style = style
self.startingZone = startingZone
self.gridSize = gridSize
self.gridRadius = gridRadius
self.cellWidth = cellWidth
# Keep track of all AI objects added to the grid
self.gridObjects = {}
self.updateTaskStarted = 0
def delete(self):
DistributedNodeAI.delete(self)
self.stopUpdateGridTask()
def isGridParent(self):
# If this distributed object is a DistributedGrid return 1.
# 0 by default
return 1
def getCellWidth(self):
return self.cellWidth
def getParentingRules(self):
self.notify.debug("calling getter")
rule = ("%i%s%i%s%i" % (self.startingZone, self.RuleSeparator,
self.gridSize, self.RuleSeparator,
self.gridRadius))
return [self.style, rule]
# Reparent and setLocation on av to DistributedOceanGrid
def addObjectToGrid(self, av, useZoneId=-1, startAutoUpdate=True):
self.notify.debug("setting parent to grid %s" % self)
avId = av.doId
# Create a grid parent
#gridParent = self.attachNewNode("gridParent-%s" % avId)
#self.gridParents[avId] = gridParent
self.gridObjects[avId] = av
# Put the avatar on the grid
self.handleAvatarZoneChange(av, useZoneId)
if (not self.updateTaskStarted) and startAutoUpdate:
self.startUpdateGridTask()
def removeObjectFromGrid(self, av):
# TODO: WHAT LOCATION SHOULD WE SET THIS TO?
#av.wrtReparentTo(self.parentNP)
#av.setLocation(self.air.districtId, 1000)
# Remove grid parent for this av
avId = av.doId
if avId in self.gridObjects:
del self.gridObjects[avId]
# Stop task if there are no more av's being managed
if len(self.gridObjects) == 0:
self.stopUpdateGridTask()
#####################################################################
# updateGridTask
# This task is similar to the processVisibility task for the local client.
# A couple differences:
# - we are not doing setInterest on the AI (that is a local client
# specific call).
# - we assume that the moving objects on the grid are parented to a
# gridParent, and are broadcasting their position relative to that
# gridParent. This makes the task's math easy. Just check to see
# when our position goes out of the current grid cell. When it does,
# call handleAvatarZoneChange
def startUpdateGridTask(self):
self.stopUpdateGridTask()
self.updateTaskStarted = 1
taskMgr.add(self.updateGridTask, self.taskName("updateGridTask"))
def stopUpdateGridTask(self):
taskMgr.remove(self.taskName("updateGridTask"))
self.updateTaskStarted = 0
def updateGridTask(self, task=None):
# Run through all grid objects and update their parents if needed
missingObjs = []
for avId in self.gridObjects.keys():
|
continue
pos = av.getPos()
if ((pos[0] < 0 or pos[1] < 0) or
(pos[0] > self.cellWidth or pos[1] > self.cellWidth)):
# we are out of the bounds of this current cell
self.handleAvatarZoneChange(av)
# Do this every second, not every frame
if (task):
task.setDelay(1.0)
return Task.again
def handleAvatarZoneChange(self, av, useZoneId=-1):
# Calculate zone id
# Get position of av relative to this grid
if (useZoneId == -1):
pos = av.getPos(self)
zoneId = self.getZoneFromXYZ(pos)
else:
# zone already calculated, position of object might not
# give the correct zone
pos = None
zoneId = useZoneId
if not self.isValidZone(zoneId):
self.notify.warning(
"%s handleAvatarZoneChange %s: not a valid zone (%s) for pos %s" %(self.doId, av.doId, zoneId, pos))
return
# Set the location on the server.
# setLocation will update the gridParent
av.b_setLocation(self.doId, zoneId)
def handleSetLocation(self, av, parentId, zoneId):
pass
#if (av.parentId != parentId):
# parent changed, need to look up instance tree
# to see if avatar's named area location information
# changed
#av.requestRegionUpdateTask(regionegionUid)
|
av = self.gridObjects[avId]
# handle a missing object after it is already gone?
if (av.isEmpty()):
task.setDelay(1.0)
del self.gridObjects[avId]
|
random_line_split
|
DistributedCartesianGridAI.py
|
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNotify.newCategory("DistributedCartesianGridAI")
RuleSeparator = ":"
def __init__(self, air, startingZone, gridSize, gridRadius, cellWidth,
style="Cartesian"):
DistributedNodeAI.__init__(self, air)
self.style = style
self.startingZone = startingZone
self.gridSize = gridSize
self.gridRadius = gridRadius
self.cellWidth = cellWidth
# Keep track of all AI objects added to the grid
self.gridObjects = {}
self.updateTaskStarted = 0
def delete(self):
DistributedNodeAI.delete(self)
self.stopUpdateGridTask()
def isGridParent(self):
# If this distributed object is a DistributedGrid return 1.
# 0 by default
return 1
def getCellWidth(self):
return self.cellWidth
def
|
(self):
self.notify.debug("calling getter")
rule = ("%i%s%i%s%i" % (self.startingZone, self.RuleSeparator,
self.gridSize, self.RuleSeparator,
self.gridRadius))
return [self.style, rule]
# Reparent and setLocation on av to DistributedOceanGrid
def addObjectToGrid(self, av, useZoneId=-1, startAutoUpdate=True):
self.notify.debug("setting parent to grid %s" % self)
avId = av.doId
# Create a grid parent
#gridParent = self.attachNewNode("gridParent-%s" % avId)
#self.gridParents[avId] = gridParent
self.gridObjects[avId] = av
# Put the avatar on the grid
self.handleAvatarZoneChange(av, useZoneId)
if (not self.updateTaskStarted) and startAutoUpdate:
self.startUpdateGridTask()
def removeObjectFromGrid(self, av):
# TODO: WHAT LOCATION SHOULD WE SET THIS TO?
#av.wrtReparentTo(self.parentNP)
#av.setLocation(self.air.districtId, 1000)
# Remove grid parent for this av
avId = av.doId
if avId in self.gridObjects:
del self.gridObjects[avId]
# Stop task if there are no more av's being managed
if len(self.gridObjects) == 0:
self.stopUpdateGridTask()
#####################################################################
# updateGridTask
# This task is similar to the processVisibility task for the local client.
# A couple differences:
# - we are not doing setInterest on the AI (that is a local client
# specific call).
# - we assume that the moving objects on the grid are parented to a
# gridParent, and are broadcasting their position relative to that
# gridParent. This makes the task's math easy. Just check to see
# when our position goes out of the current grid cell. When it does,
# call handleAvatarZoneChange
def startUpdateGridTask(self):
self.stopUpdateGridTask()
self.updateTaskStarted = 1
taskMgr.add(self.updateGridTask, self.taskName("updateGridTask"))
def stopUpdateGridTask(self):
taskMgr.remove(self.taskName("updateGridTask"))
self.updateTaskStarted = 0
def updateGridTask(self, task=None):
# Run through all grid objects and update their parents if needed
missingObjs = []
for avId in self.gridObjects.keys():
av = self.gridObjects[avId]
# handle a missing object after it is already gone?
if (av.isEmpty()):
task.setDelay(1.0)
del self.gridObjects[avId]
continue
pos = av.getPos()
if ((pos[0] < 0 or pos[1] < 0) or
(pos[0] > self.cellWidth or pos[1] > self.cellWidth)):
# we are out of the bounds of this current cell
self.handleAvatarZoneChange(av)
# Do this every second, not every frame
if (task):
task.setDelay(1.0)
return Task.again
def handleAvatarZoneChange(self, av, useZoneId=-1):
# Calculate zone id
# Get position of av relative to this grid
if (useZoneId == -1):
pos = av.getPos(self)
zoneId = self.getZoneFromXYZ(pos)
else:
# zone already calculated, position of object might not
# give the correct zone
pos = None
zoneId = useZoneId
if not self.isValidZone(zoneId):
self.notify.warning(
"%s handleAvatarZoneChange %s: not a valid zone (%s) for pos %s" %(self.doId, av.doId, zoneId, pos))
return
# Set the location on the server.
# setLocation will update the gridParent
av.b_setLocation(self.doId, zoneId)
def handleSetLocation(self, av, parentId, zoneId):
pass
#if (av.parentId != parentId):
# parent changed, need to look up instance tree
# to see if avatar's named area location information
# changed
#av.requestRegionUpdateTask(regionegionUid)
|
getParentingRules
|
identifier_name
|
block.py
|
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes for analyzing and storing the state of Python code blocks."""
from __future__ import unicode_literals
import abc
import collections
import re
from grumpy.compiler import expr
from grumpy.compiler import util
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
from grumpy.pythonparser import source
_non_word_re = re.compile('[^A-Za-z0-9_]')
class Package(object):
"""A Go package import."""
def __init__(self, name, alias=None):
self.name = name
# Use Γ as a separator since it provides readability with a low
# probability of name collisions.
self.alias = alias or 'π_' + name.replace('/', 'Γ').replace('.', 'Γ')
class Loop(object):
"""Represents a for or while loop within a particular block."""
def __init__(self, breakvar):
self.breakvar = breakvar
class Block(object):
"""Represents a Python block such as a function or class definition."""
__metaclass__ = abc.ABCMeta
def __init__(self, parent, name):
self.root = parent.root if parent else self
self.parent = parent
self.name = name
self.free_temps = set()
self.used_temps = set()
self.temp_index = 0
self.label_count = 0
self.checkpoints = set()
self.loop_stack = []
self.is_generator = False
@abc.abstractmethod
def bind_var(self, writer, name, value):
"""Writes Go statements for assigning value to named var in this block.
This is overridden in the different concrete block types since in Python,
binding a variable in, e.g. a function is quite different than binding at
global block.
Args:
writer: The Writer object where statements will be written.
name: The name of the Python variable.
value: A Go expression to assign to the variable.
"""
pass
@abc.abstractmethod
def del_var(self, writer, name):
pass
@abc.abstractmethod
def resolve_name(self, writer, name):
"""Returns a GeneratedExpr object for accessing the named var in this block.
This is overridden in the different concrete block types since name
resolution in Python behaves differently depending on where in what kind of
block its happening within, e.g. local vars are different than globals.
Args:
writer: Writer object where intermediate calculations will be printed.
name: The name of the Python variable.
"""
pass
def genlabel(self, is_checkpoint=False):
self.label_count += 1
if is_checkpoint:
self.checkpoints.add(self.label_count)
return self.label_count
def alloc_temp(self, type_='*πg.Object'):
"""Create a new temporary Go variable having type type_ for this block."""
for v in sorted(self.free_temps, key=lambda k: k.name):
if v.type_ == type_:
self.free_temps.remove(v)
self.used_temps.add(v)
return v
self.temp_index += 1
name = 'πTemp{:03d}'.format(self.temp_index)
v = expr.GeneratedTempVar(self, name, type_)
self.used_temps.add(v)
return v
def free_temp(self, v):
"""Release the GeneratedTempVar v so it can be reused."""
self.used_temps.remove(v)
self.free_temps.add(v)
def push_loop(self, breakvar):
loop = Loop(breakvar)
self.loop_stack.append(loop)
return loop
def pop_loop(self):
self.loop_stack.pop()
def top_loop(self):
return self.loop_stack[-1]
def _resolve_global(self, writer, name):
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveGlobal(πF, {})', self.root.intern(name))
return result
class ModuleBlock(Block):
"""Python block for a module."""
def __init__(self, importer, full_package_name,
filename, src, future_features):
Block.__init__(self, None, '<module>')
self.importer = importer
self.full_package_name = full_package_name
self.filename = filename
self.buffer = source.Buffer(src)
self.strings = set()
self.future_features = future_features
def bind_var(self, writer, name, value):
writer.write_checked_call1(
'πF.Globals().SetItem(πF, {}.ToObject(), {})',
self.intern(name), value)
def del_var(self, writer, name):
writer.write_checked_call1('πg.DelVar(πF, πF.Globals(), {})',
self.intern(name))
def resolve_name(self, writer, name):
return self._resolve_global(writer, name)
def intern(self, s):
if len(s) > 64 or _non_word_re.search(s):
return 'πg.NewStr({})'.format(util.go_str(s))
self.strings.add(s)
return 'ß' + s
class ClassBlock(Block):
"""Python block for a class definition."""
def __init__(self, parent, name, global_vars):
Block.__init__(self, parent, name)
self.global_vars = global_vars
def bind_var(self, writer, name, value):
if name in self.global_vars:
return self.root.bind_var(writer, name, value)
writer.write_checked_call1('πClass.SetItem(πF, {}.ToObject(), {})',
self.root.intern(name), value)
def del_var(self, writer, name):
if name in self.global_vars:
return self.root.del_var(writer, name)
writer.write_checked_call1('πg.DelVar(πF, πClass, {})',
self.root.intern(name))
def resolve_name(self, writer, name):
local = 'nil'
if name not in self.global_vars:
# Only look for a local in an outer block when name hasn't been declared
# global in this block. If it has been declared global then we fallback
# straight to the global dict.
block = self.parent
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock) and name in block.vars:
var = block.vars[name]
if var.type != Var.TYPE_GLOBAL:
local = util.adjust_local_name(name)
# When it is declared global, prefer it to anything in outer blocks.
break
block = block.parent
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveClass(πF, πClass, {}, {})',
local, self.root.intern(name))
return result
class FunctionBlock(Block):
"""Python block for a function definition."""
def __init__(self, parent, name, block_vars, is_generator):
Block.__init__(self, parent, name)
self.vars = block_vars
self.parent = parent
self.is_generator = is_generator
def bind_var(self, writer, name, value):
if self.vars[name].type == Var.TYPE_GLOBAL:
return self.root.bind_var(writer, name, value)
writer.write('{} = {}'.format(util.adjust_local_name(name), value))
def del_var(self, writer, name):
var = self.vars.get(name)
if not var:
raise util.ParseError(
None, 'cannot delete nonexistent local: {}'.format(name))
if var.type == Var.TYPE_GLOBAL:
return self.root.del_var(writer, name)
adjusted_name = util.adjust_local_name(name)
# Resolve local first to ensure the variable is already bound.
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
adjusted_name, util.go_str(name))
writer.write('{} = πg.UnboundLocal'.format(adjusted_name))
def resolve_name(self, writer, name):
block = self
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock):
var = block.vars.get(name)
if var:
if var.type == Var.TYPE_GLOBAL:
return self._resolve_global(writer, name)
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
util.adjust_local_name(name),
util.go_str(name))
return expr.GeneratedLocalVar(name)
block = block.parent
return self._resolve_global(writer, name)
class Var(object):
"""A Python variable used within a particular block."""
TYPE_LOCAL = 0
TYPE_PARAM = 1
TYPE_GLOBAL = 2
def __init__(self, name, var_type, arg_index=None):
self.name = name
self.type = var_type
if var_type == Var.TYPE_LOCAL:
assert arg_index is None
self.init_expr = 'πg.UnboundLocal'
elif var_type == Var.TYPE_PARAM:
assert arg_index is not None
self.init_expr = 'πArgs[{}]'.format(arg_index)
else:
assert arg_index is None
self.init_expr = None
class BlockVisitor(algorithm.Visitor):
"""Visits nodes in a function or class to determine block variables."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self):
self.vars = collections.OrderedDict()
def visit_Assign(self, node):
for target in node.targets:
self._assign_target(target)
self.visit(node.value)
def visit_AugAssign(self, node):
self._assign_target(node.target)
self.visit(node.value)
def visit_ClassDef(self, node):
self._register_local(node.name)
def visit_ExceptHandler(self, node):
if node.name:
self._register_local(node.name.id)
self.generic_visit(node)
def visit_For(self, node):
self._assign_target(node.target)
self.generic_visit(node)
def visit_FunctionDef(self, node):
# The function being defined is local to this block, i.e. is nested within
# another function. Note that further nested symbols are not traversed
# because we don't explicitly visit the function body.
self._register_local(node.name)
def visit_Global(self, node):
for name in node.names:
self._register_global(node, name)
def visit_Import(self, node):
for alias in node.names:
self._register_local(alias.asn
|
node):
for alias in node.names:
self._register_local(alias.asname or alias.name)
def visit_With(self, node):
for item in node.items:
if item.optional_vars:
self._assign_target(item.optional_vars)
self.generic_visit(node)
def _assign_target(self, target):
if isinstance(target, ast.Name):
self._register_local(target.id)
elif isinstance(target, (ast.Tuple, ast.List)):
for elt in target.elts:
self._assign_target(elt)
def _register_global(self, node, name):
var = self.vars.get(name)
if var:
if var.type == Var.TYPE_PARAM:
msg = "name '{}' is parameter and global"
raise util.ParseError(node, msg.format(name))
if var.type == Var.TYPE_LOCAL:
msg = "name '{}' is used prior to global declaration"
raise util.ParseError(node, msg.format(name))
else:
self.vars[name] = Var(name, Var.TYPE_GLOBAL)
def _register_local(self, name):
if not self.vars.get(name):
self.vars[name] = Var(name, Var.TYPE_LOCAL)
class FunctionBlockVisitor(BlockVisitor):
"""Visits function nodes to determine variables and generator state."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self, node):
BlockVisitor.__init__(self)
self.is_generator = False
node_args = node.args
args = [a.arg for a in node_args.args]
if node_args.vararg:
args.append(node_args.vararg.arg)
if node_args.kwarg:
args.append(node_args.kwarg.arg)
for i, name in enumerate(args):
if name in self.vars:
msg = "duplicate argument '{}' in function definition".format(name)
raise util.ParseError(node, msg)
self.vars[name] = Var(name, Var.TYPE_PARAM, arg_index=i)
def visit_Yield(self, unused_node): # pylint: disable=unused-argument
self.is_generator = True
|
ame or alias.name.split('.')[0])
def visit_ImportFrom(self,
|
conditional_block
|
block.py
|
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes for analyzing and storing the state of Python code blocks."""
from __future__ import unicode_literals
import abc
import collections
import re
from grumpy.compiler import expr
from grumpy.compiler import util
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
from grumpy.pythonparser import source
_non_word_re = re.compile('[^A-Za-z0-9_]')
class Package(object):
"""A Go package import."""
def __init__(self, name, alias=None):
self.name = name
# Use Γ as a separator since it provides readability with a low
# probability of name collisions.
self.alias = alias or 'π_' + name.replace('/', 'Γ').replace('.', 'Γ')
|
def __init__(self, breakvar):
self.breakvar = breakvar
class Block(object):
"""Represents a Python block such as a function or class definition."""
__metaclass__ = abc.ABCMeta
def __init__(self, parent, name):
self.root = parent.root if parent else self
self.parent = parent
self.name = name
self.free_temps = set()
self.used_temps = set()
self.temp_index = 0
self.label_count = 0
self.checkpoints = set()
self.loop_stack = []
self.is_generator = False
@abc.abstractmethod
def bind_var(self, writer, name, value):
"""Writes Go statements for assigning value to named var in this block.
This is overridden in the different concrete block types since in Python,
binding a variable in, e.g. a function is quite different than binding at
global block.
Args:
writer: The Writer object where statements will be written.
name: The name of the Python variable.
value: A Go expression to assign to the variable.
"""
pass
@abc.abstractmethod
def del_var(self, writer, name):
pass
@abc.abstractmethod
def resolve_name(self, writer, name):
"""Returns a GeneratedExpr object for accessing the named var in this block.
This is overridden in the different concrete block types since name
resolution in Python behaves differently depending on where in what kind of
block its happening within, e.g. local vars are different than globals.
Args:
writer: Writer object where intermediate calculations will be printed.
name: The name of the Python variable.
"""
pass
def genlabel(self, is_checkpoint=False):
self.label_count += 1
if is_checkpoint:
self.checkpoints.add(self.label_count)
return self.label_count
def alloc_temp(self, type_='*πg.Object'):
"""Create a new temporary Go variable having type type_ for this block."""
for v in sorted(self.free_temps, key=lambda k: k.name):
if v.type_ == type_:
self.free_temps.remove(v)
self.used_temps.add(v)
return v
self.temp_index += 1
name = 'πTemp{:03d}'.format(self.temp_index)
v = expr.GeneratedTempVar(self, name, type_)
self.used_temps.add(v)
return v
def free_temp(self, v):
"""Release the GeneratedTempVar v so it can be reused."""
self.used_temps.remove(v)
self.free_temps.add(v)
def push_loop(self, breakvar):
loop = Loop(breakvar)
self.loop_stack.append(loop)
return loop
def pop_loop(self):
self.loop_stack.pop()
def top_loop(self):
return self.loop_stack[-1]
def _resolve_global(self, writer, name):
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveGlobal(πF, {})', self.root.intern(name))
return result
class ModuleBlock(Block):
"""Python block for a module."""
def __init__(self, importer, full_package_name,
filename, src, future_features):
Block.__init__(self, None, '<module>')
self.importer = importer
self.full_package_name = full_package_name
self.filename = filename
self.buffer = source.Buffer(src)
self.strings = set()
self.future_features = future_features
def bind_var(self, writer, name, value):
writer.write_checked_call1(
'πF.Globals().SetItem(πF, {}.ToObject(), {})',
self.intern(name), value)
def del_var(self, writer, name):
writer.write_checked_call1('πg.DelVar(πF, πF.Globals(), {})',
self.intern(name))
def resolve_name(self, writer, name):
return self._resolve_global(writer, name)
def intern(self, s):
if len(s) > 64 or _non_word_re.search(s):
return 'πg.NewStr({})'.format(util.go_str(s))
self.strings.add(s)
return 'ß' + s
class ClassBlock(Block):
"""Python block for a class definition."""
def __init__(self, parent, name, global_vars):
Block.__init__(self, parent, name)
self.global_vars = global_vars
def bind_var(self, writer, name, value):
if name in self.global_vars:
return self.root.bind_var(writer, name, value)
writer.write_checked_call1('πClass.SetItem(πF, {}.ToObject(), {})',
self.root.intern(name), value)
def del_var(self, writer, name):
if name in self.global_vars:
return self.root.del_var(writer, name)
writer.write_checked_call1('πg.DelVar(πF, πClass, {})',
self.root.intern(name))
def resolve_name(self, writer, name):
local = 'nil'
if name not in self.global_vars:
# Only look for a local in an outer block when name hasn't been declared
# global in this block. If it has been declared global then we fallback
# straight to the global dict.
block = self.parent
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock) and name in block.vars:
var = block.vars[name]
if var.type != Var.TYPE_GLOBAL:
local = util.adjust_local_name(name)
# When it is declared global, prefer it to anything in outer blocks.
break
block = block.parent
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveClass(πF, πClass, {}, {})',
local, self.root.intern(name))
return result
class FunctionBlock(Block):
"""Python block for a function definition."""
def __init__(self, parent, name, block_vars, is_generator):
Block.__init__(self, parent, name)
self.vars = block_vars
self.parent = parent
self.is_generator = is_generator
def bind_var(self, writer, name, value):
if self.vars[name].type == Var.TYPE_GLOBAL:
return self.root.bind_var(writer, name, value)
writer.write('{} = {}'.format(util.adjust_local_name(name), value))
def del_var(self, writer, name):
var = self.vars.get(name)
if not var:
raise util.ParseError(
None, 'cannot delete nonexistent local: {}'.format(name))
if var.type == Var.TYPE_GLOBAL:
return self.root.del_var(writer, name)
adjusted_name = util.adjust_local_name(name)
# Resolve local first to ensure the variable is already bound.
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
adjusted_name, util.go_str(name))
writer.write('{} = πg.UnboundLocal'.format(adjusted_name))
def resolve_name(self, writer, name):
block = self
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock):
var = block.vars.get(name)
if var:
if var.type == Var.TYPE_GLOBAL:
return self._resolve_global(writer, name)
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
util.adjust_local_name(name),
util.go_str(name))
return expr.GeneratedLocalVar(name)
block = block.parent
return self._resolve_global(writer, name)
class Var(object):
"""A Python variable used within a particular block."""
TYPE_LOCAL = 0
TYPE_PARAM = 1
TYPE_GLOBAL = 2
def __init__(self, name, var_type, arg_index=None):
self.name = name
self.type = var_type
if var_type == Var.TYPE_LOCAL:
assert arg_index is None
self.init_expr = 'πg.UnboundLocal'
elif var_type == Var.TYPE_PARAM:
assert arg_index is not None
self.init_expr = 'πArgs[{}]'.format(arg_index)
else:
assert arg_index is None
self.init_expr = None
class BlockVisitor(algorithm.Visitor):
"""Visits nodes in a function or class to determine block variables."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self):
self.vars = collections.OrderedDict()
def visit_Assign(self, node):
for target in node.targets:
self._assign_target(target)
self.visit(node.value)
def visit_AugAssign(self, node):
self._assign_target(node.target)
self.visit(node.value)
def visit_ClassDef(self, node):
self._register_local(node.name)
def visit_ExceptHandler(self, node):
if node.name:
self._register_local(node.name.id)
self.generic_visit(node)
def visit_For(self, node):
self._assign_target(node.target)
self.generic_visit(node)
def visit_FunctionDef(self, node):
# The function being defined is local to this block, i.e. is nested within
# another function. Note that further nested symbols are not traversed
# because we don't explicitly visit the function body.
self._register_local(node.name)
def visit_Global(self, node):
for name in node.names:
self._register_global(node, name)
def visit_Import(self, node):
for alias in node.names:
self._register_local(alias.asname or alias.name.split('.')[0])
def visit_ImportFrom(self, node):
for alias in node.names:
self._register_local(alias.asname or alias.name)
def visit_With(self, node):
for item in node.items:
if item.optional_vars:
self._assign_target(item.optional_vars)
self.generic_visit(node)
def _assign_target(self, target):
if isinstance(target, ast.Name):
self._register_local(target.id)
elif isinstance(target, (ast.Tuple, ast.List)):
for elt in target.elts:
self._assign_target(elt)
def _register_global(self, node, name):
var = self.vars.get(name)
if var:
if var.type == Var.TYPE_PARAM:
msg = "name '{}' is parameter and global"
raise util.ParseError(node, msg.format(name))
if var.type == Var.TYPE_LOCAL:
msg = "name '{}' is used prior to global declaration"
raise util.ParseError(node, msg.format(name))
else:
self.vars[name] = Var(name, Var.TYPE_GLOBAL)
def _register_local(self, name):
if not self.vars.get(name):
self.vars[name] = Var(name, Var.TYPE_LOCAL)
class FunctionBlockVisitor(BlockVisitor):
"""Visits function nodes to determine variables and generator state."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self, node):
BlockVisitor.__init__(self)
self.is_generator = False
node_args = node.args
args = [a.arg for a in node_args.args]
if node_args.vararg:
args.append(node_args.vararg.arg)
if node_args.kwarg:
args.append(node_args.kwarg.arg)
for i, name in enumerate(args):
if name in self.vars:
msg = "duplicate argument '{}' in function definition".format(name)
raise util.ParseError(node, msg)
self.vars[name] = Var(name, Var.TYPE_PARAM, arg_index=i)
def visit_Yield(self, unused_node): # pylint: disable=unused-argument
self.is_generator = True
|
class Loop(object):
"""Represents a for or while loop within a particular block."""
|
random_line_split
|
block.py
|
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes for analyzing and storing the state of Python code blocks."""
from __future__ import unicode_literals
import abc
import collections
import re
from grumpy.compiler import expr
from grumpy.compiler import util
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
from grumpy.pythonparser import source
_non_word_re = re.compile('[^A-Za-z0-9_]')
class Package(object):
"""A Go package import."""
def __init__(self, name, alias=None):
self.name = name
# Use Γ as a separator since it provides readability with a low
# probability of name collisions.
self.alias = alias or 'π_' + name.replace('/', 'Γ').replace('.', 'Γ')
class Loop(object):
"""Represents a for or while loop within a particular block."""
def __init__(self, breakvar):
self.breakvar = breakvar
class Block(object):
"""Represents a Python block such as a function or class definition."""
__metaclass__ = abc.ABCMeta
def __init__(self, parent, name):
self.root = parent.root if parent else self
self.parent = parent
self.name = name
self.free_temps = set()
self.used_temps = set()
self.temp_index = 0
self.label_count = 0
self.checkpoints = set()
self.loop_stack = []
self.is_generator = False
@abc.abstractmethod
def bind_var(self, writer, name, value):
"""Writes Go statements for assigning value to named var in this block.
This is overridden in the different concrete block types since in Python,
binding a variable in, e.g. a function is quite different than binding at
global block.
Args:
writer: The Writer object where statements will be written.
name: The name of the Python variable.
value: A Go expression to assign to the variable.
"""
pass
@abc.abstractmethod
def del_var(self, writer, name):
pass
@abc.abstractmethod
def resolve_name(self, writer, name):
"""Returns a GeneratedExpr object for accessing the named var in this block.
This is overridden in the different concrete block types since name
resolution in Python behaves differently depending on where in what kind of
block its happening within, e.g. local vars are different than globals.
Args:
writer: Writer object where intermediate calculations will be printed.
name: The name of the Python variable.
"""
pass
def genlabel(self, is_checkpoint=False):
self.label_count += 1
if is_checkpoint:
self.checkpoints.add(self.label_count)
return self.label_count
def alloc_temp(self, type_='*πg.Object'):
"""Create a new temporary Go variable having type type_ for this block."""
for v in sorted(self.free_temps, key=lambda k: k.name):
if v.type_ == type_:
self.free_temps.remove(v)
self.used_temps.add(v)
return v
self.temp_index += 1
name = 'πTemp{:03d}'.format(self.temp_index)
v = expr.GeneratedTempVar(self, name, type_)
self.used_temps.add(v)
return v
def free_temp(self, v):
"""Release the GeneratedTempVar v so it can be reused."""
self.used_temps.remove(v)
self.free_temps.add(v)
def push_loop(self, breakvar):
loop =
|
f pop_loop(self):
self.loop_stack.pop()
def top_loop(self):
return self.loop_stack[-1]
def _resolve_global(self, writer, name):
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveGlobal(πF, {})', self.root.intern(name))
return result
class ModuleBlock(Block):
"""Python block for a module."""
def __init__(self, importer, full_package_name,
filename, src, future_features):
Block.__init__(self, None, '<module>')
self.importer = importer
self.full_package_name = full_package_name
self.filename = filename
self.buffer = source.Buffer(src)
self.strings = set()
self.future_features = future_features
def bind_var(self, writer, name, value):
writer.write_checked_call1(
'πF.Globals().SetItem(πF, {}.ToObject(), {})',
self.intern(name), value)
def del_var(self, writer, name):
writer.write_checked_call1('πg.DelVar(πF, πF.Globals(), {})',
self.intern(name))
def resolve_name(self, writer, name):
return self._resolve_global(writer, name)
def intern(self, s):
if len(s) > 64 or _non_word_re.search(s):
return 'πg.NewStr({})'.format(util.go_str(s))
self.strings.add(s)
return 'ß' + s
class ClassBlock(Block):
"""Python block for a class definition."""
def __init__(self, parent, name, global_vars):
Block.__init__(self, parent, name)
self.global_vars = global_vars
def bind_var(self, writer, name, value):
if name in self.global_vars:
return self.root.bind_var(writer, name, value)
writer.write_checked_call1('πClass.SetItem(πF, {}.ToObject(), {})',
self.root.intern(name), value)
def del_var(self, writer, name):
if name in self.global_vars:
return self.root.del_var(writer, name)
writer.write_checked_call1('πg.DelVar(πF, πClass, {})',
self.root.intern(name))
def resolve_name(self, writer, name):
local = 'nil'
if name not in self.global_vars:
# Only look for a local in an outer block when name hasn't been declared
# global in this block. If it has been declared global then we fallback
# straight to the global dict.
block = self.parent
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock) and name in block.vars:
var = block.vars[name]
if var.type != Var.TYPE_GLOBAL:
local = util.adjust_local_name(name)
# When it is declared global, prefer it to anything in outer blocks.
break
block = block.parent
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveClass(πF, πClass, {}, {})',
local, self.root.intern(name))
return result
class FunctionBlock(Block):
"""Python block for a function definition."""
def __init__(self, parent, name, block_vars, is_generator):
Block.__init__(self, parent, name)
self.vars = block_vars
self.parent = parent
self.is_generator = is_generator
def bind_var(self, writer, name, value):
if self.vars[name].type == Var.TYPE_GLOBAL:
return self.root.bind_var(writer, name, value)
writer.write('{} = {}'.format(util.adjust_local_name(name), value))
def del_var(self, writer, name):
var = self.vars.get(name)
if not var:
raise util.ParseError(
None, 'cannot delete nonexistent local: {}'.format(name))
if var.type == Var.TYPE_GLOBAL:
return self.root.del_var(writer, name)
adjusted_name = util.adjust_local_name(name)
# Resolve local first to ensure the variable is already bound.
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
adjusted_name, util.go_str(name))
writer.write('{} = πg.UnboundLocal'.format(adjusted_name))
def resolve_name(self, writer, name):
block = self
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock):
var = block.vars.get(name)
if var:
if var.type == Var.TYPE_GLOBAL:
return self._resolve_global(writer, name)
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
util.adjust_local_name(name),
util.go_str(name))
return expr.GeneratedLocalVar(name)
block = block.parent
return self._resolve_global(writer, name)
class Var(object):
"""A Python variable used within a particular block."""
TYPE_LOCAL = 0
TYPE_PARAM = 1
TYPE_GLOBAL = 2
def __init__(self, name, var_type, arg_index=None):
self.name = name
self.type = var_type
if var_type == Var.TYPE_LOCAL:
assert arg_index is None
self.init_expr = 'πg.UnboundLocal'
elif var_type == Var.TYPE_PARAM:
assert arg_index is not None
self.init_expr = 'πArgs[{}]'.format(arg_index)
else:
assert arg_index is None
self.init_expr = None
class BlockVisitor(algorithm.Visitor):
"""Visits nodes in a function or class to determine block variables."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self):
self.vars = collections.OrderedDict()
def visit_Assign(self, node):
for target in node.targets:
self._assign_target(target)
self.visit(node.value)
def visit_AugAssign(self, node):
self._assign_target(node.target)
self.visit(node.value)
def visit_ClassDef(self, node):
self._register_local(node.name)
def visit_ExceptHandler(self, node):
if node.name:
self._register_local(node.name.id)
self.generic_visit(node)
def visit_For(self, node):
self._assign_target(node.target)
self.generic_visit(node)
def visit_FunctionDef(self, node):
# The function being defined is local to this block, i.e. is nested within
# another function. Note that further nested symbols are not traversed
# because we don't explicitly visit the function body.
self._register_local(node.name)
def visit_Global(self, node):
for name in node.names:
self._register_global(node, name)
def visit_Import(self, node):
for alias in node.names:
self._register_local(alias.asname or alias.name.split('.')[0])
def visit_ImportFrom(self, node):
for alias in node.names:
self._register_local(alias.asname or alias.name)
def visit_With(self, node):
for item in node.items:
if item.optional_vars:
self._assign_target(item.optional_vars)
self.generic_visit(node)
def _assign_target(self, target):
if isinstance(target, ast.Name):
self._register_local(target.id)
elif isinstance(target, (ast.Tuple, ast.List)):
for elt in target.elts:
self._assign_target(elt)
def _register_global(self, node, name):
var = self.vars.get(name)
if var:
if var.type == Var.TYPE_PARAM:
msg = "name '{}' is parameter and global"
raise util.ParseError(node, msg.format(name))
if var.type == Var.TYPE_LOCAL:
msg = "name '{}' is used prior to global declaration"
raise util.ParseError(node, msg.format(name))
else:
self.vars[name] = Var(name, Var.TYPE_GLOBAL)
def _register_local(self, name):
if not self.vars.get(name):
self.vars[name] = Var(name, Var.TYPE_LOCAL)
class FunctionBlockVisitor(BlockVisitor):
"""Visits function nodes to determine variables and generator state."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self, node):
BlockVisitor.__init__(self)
self.is_generator = False
node_args = node.args
args = [a.arg for a in node_args.args]
if node_args.vararg:
args.append(node_args.vararg.arg)
if node_args.kwarg:
args.append(node_args.kwarg.arg)
for i, name in enumerate(args):
if name in self.vars:
msg = "duplicate argument '{}' in function definition".format(name)
raise util.ParseError(node, msg)
self.vars[name] = Var(name, Var.TYPE_PARAM, arg_index=i)
def visit_Yield(self, unused_node): # pylint: disable=unused-argument
self.is_generator = True
|
Loop(breakvar)
self.loop_stack.append(loop)
return loop
de
|
identifier_body
|
block.py
|
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes for analyzing and storing the state of Python code blocks."""
from __future__ import unicode_literals
import abc
import collections
import re
from grumpy.compiler import expr
from grumpy.compiler import util
from grumpy.pythonparser import algorithm
from grumpy.pythonparser import ast
from grumpy.pythonparser import source
_non_word_re = re.compile('[^A-Za-z0-9_]')
class Package(object):
"""A Go package import."""
def __init__(self, name, alias=None):
self.name = name
# Use Γ as a separator since it provides readability with a low
# probability of name collisions.
self.alias = alias or 'π_' + name.replace('/', 'Γ').replace('.', 'Γ')
class Loop(object):
"""Represents a for or while loop within a particular block."""
def __init__(self, breakvar):
self.breakvar = breakvar
class Block(object):
"""Represents a Python block such as a function or class definition."""
__metaclass__ = abc.ABCMeta
def __init__(self, parent, name):
self.root = parent.root if parent else self
self.parent = parent
self.name = name
self.free_temps = set()
self.used_temps = set()
self.temp_index = 0
self.label_count = 0
self.checkpoints = set()
self.loop_stack = []
self.is_generator = False
@abc.abstractmethod
def bind_var(self, writer, name, value):
"""Writes Go statements for assigning value to named var in this block.
This is overridden in the different concrete block types since in Python,
binding a variable in, e.g. a function is quite different than binding at
global block.
Args:
writer: The Writer object where statements will be written.
name: The name of the Python variable.
value: A Go expression to assign to the variable.
"""
pass
@abc.abstractmethod
def del_var(self, writer, name):
pass
@abc.abstractmethod
def resolve_name(self, writer, name):
"""Returns a GeneratedExpr object for accessing the named var in this block.
This is overridden in the different concrete block types since name
resolution in Python behaves differently depending on where in what kind of
block its happening within, e.g. local vars are different than globals.
Args:
writer: Writer object where intermediate calculations will be printed.
name: The name of the Python variable.
"""
pass
def genlabel(self, is_checkpoint=False):
self.label_count += 1
if is_checkpoint:
self.checkpoints.add(self.label_count)
return self.label_count
def alloc_temp(self, type_='*πg.Object'):
"""Create a new temporary Go variable having type type_ for this block."""
for v in sorted(self.free_temps, key=lambda k: k.name):
if v.type_ == type_:
self.free_temps.remove(v)
self.used_temps.add(v)
return v
self.temp_index += 1
name = 'πTemp{:03d}'.format(self.temp_index)
v = expr.GeneratedTempVar(self, name, type_)
self.used_temps.add(v)
return v
def free_temp(self, v):
"""Release the GeneratedTempVar v so it can be reused."""
self.used_temps.remove(v)
self.free_temps.add(v)
def push_loop(self, breakvar):
loop = Loop(breakvar)
self.loop_stack.append(loop)
return loop
def pop_loop(self):
self.loop_stack.pop()
def top_loop(self):
return self.loop_stack[-1]
def _resolve_global(self, writer, name):
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveGlobal(πF, {})', self.root.intern(name))
return result
class ModuleBlock(Block):
"""Python block for a module."""
def __init__(self, importer, full_package_name,
filename, src, future_features):
Block.__init__(self, None, '<module>')
self.importer = importer
self.full_package_name = full_package_name
self.filename = filename
self.buffer = source.Buffer(src)
self.strings = set()
self.future_features = future_features
def bind_var(self, writer, name, value):
writer.write_checked_call1(
'πF.Globals().SetItem(πF, {}.ToObject(), {})',
self.intern(name), value)
def del_var(self, writer, name):
writer.write_checked_call1('πg.DelVar(πF, πF.Globals(), {})',
self.intern(name))
def resolve_name(self, writer, name):
return self._resolve_global(writer, name)
def intern(self, s):
if len(s) > 64 or _non_word_re.search(s):
return 'πg.NewStr({})'.format(util.go_str(s))
self.strings.add(s)
return 'ß' + s
class ClassBlock(Block):
"""Python block for a class definition."""
def __init__(self, parent, name, global_vars):
Block.__init__(self, parent, name)
self.global_vars = global_vars
def bind_var(self, writer, name, value):
if name in self.global_vars:
return self.root.bind_var(writer, name, value)
writer.write_checked_call1('πClass.SetItem(πF, {}.ToObject(), {})',
self.root.intern(name), value)
def del_var(self, writer, name):
if name in self.global_vars:
return self.root.del_var(writer, name)
writer.write_checked_call1('πg.DelVar(πF, πClass, {})',
self.root.intern(name))
def resolve_name(self, writer, name):
local = 'nil'
if name not in self.global_vars:
# Only look for a local in an outer block when name hasn't been declared
# global in this block. If it has been declared global then we fallback
# straight to the global dict.
block = self.parent
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock) and name in block.vars:
var = block.vars[name]
if var.type != Var.TYPE_GLOBAL:
local = util.adjust_local_name(name)
# When it is declared global, prefer it to anything in outer blocks.
break
block = block.parent
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveClass(πF, πClass, {}, {})',
local, self.root.intern(name))
return result
class FunctionBlock(Block):
"""Python block for a function definition."""
def __init__(self, parent, name, block_vars, is_generator):
Block.__init__(self, parent, name)
self.vars = block_vars
self.parent = parent
self.is_generator = is_generator
def bind_var(self, writer, name, value):
if self.vars[name].type == Var.TYPE_GLOBAL:
return self.root.bind_var(writer, name, value)
writer.write('{} = {}'.format(util.adjust_local_name(name), value))
def del_var(self, writer, name):
var = self.vars.get(name)
if not var:
raise util.ParseError(
None, 'cannot delete nonexistent local: {}'.format(name))
if var.type == Var.TYPE_GLOBAL:
return self.root.del_var(writer, name)
adjusted_name = util.adjust_local_name(name)
# Resolve local first to ensure the variable is already bound.
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
adjusted_name, util.go_str(name))
writer.write('{} = πg.UnboundLocal'.format(adjusted_name))
def resolve_name(self, writer, name):
block = self
while not isinstance(block, ModuleBlock):
if isinstance(block, FunctionBlock):
var = block.vars.get(name)
if var:
if var.type == Var.TYPE_GLOBAL:
return self._resolve_global(writer, name)
writer.write_checked_call1('πg.CheckLocal(πF, {}, {})',
util.adjust_local_name(name),
util.go_str(name))
return expr.GeneratedLocalVar(name)
block = block.parent
return self._resolve_global(writer, name)
class Var(object):
"""A Python variable used within a particular block."""
TYPE_LOCAL = 0
TYPE_PARAM = 1
TYPE_GLOBAL = 2
def __init__(self, name, var_type, arg_index=None):
self.name = name
self.type = var_type
if var_type == Var.TYPE_LOCAL:
assert arg_index is None
self.init_expr = 'πg.UnboundLocal'
elif var_type == Var.TYPE_PARAM:
assert arg_index is not None
self.init_expr = 'πArgs[{}]'.format(arg_index)
else:
assert arg_index is None
self.init_expr = None
class BlockVisitor(algorithm.Visitor):
"""Visits nodes in a function or class to determine block variables."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self):
self.vars = collections.OrderedDict()
def visit_Assign(self, node):
for target in node.targets:
self._assign_target(target)
self.visit(node.value)
def visit_AugAssign(self, node):
self._assign_target(node.target)
self.visit(node.value)
def visit_ClassDef(self, node):
self._register_local(node.name)
def visit_ExceptHandler(self, node):
if node.name:
self._register_local(node.name.id)
self.generic_visit(node)
def visit_For(self, node):
self._assign_target(node.target)
self.generic_visit(node)
def visit_FunctionDef(self, node):
# The function being defined is local to this block, i.e. is nested within
# another function. Note that further nested symbols are not traversed
# because we don't explicitly visit the function body.
self._register_local(node.name)
def visit_Global(self, node):
for name in node.names:
self._register_global(node, name)
def visit_Import(self, node):
for alias in node.names:
self._register_local(alias.asname or alias.name.split('.')[0])
def visit_ImportFrom(self, node):
for alias in node.names:
self._register_local(alias.asname or alias.name)
def visit_With(self, node):
for item in node.items:
if item.optional_vars:
self._assign_target(item.optional_vars)
self.generic_visit(node)
def _assign_target(self, target):
if isinstance(target, ast.Name):
self._register_local(target.id)
elif isinstance(target, (ast.Tuple, ast.List)):
for elt in target.elts:
self._assign_target(elt)
def _register_global(self, node, name):
var = self.vars.get(name)
if var:
if var.type == Var.TYPE_PARAM:
msg = "name '{}' is parameter and global"
raise util.ParseError(node, msg.format(name))
if var.type == Var.TYPE_LOCAL:
msg = "name '{}' is used prior to global declaration"
raise util.ParseError(node, msg.format(name))
else:
self.vars[name] = Var(name, Var.TYPE_GLOBAL)
def _register_local(self, name):
if not self.vars.get(name):
self.vars[name] = Var(name, Var.TYPE_LOCAL)
class FunctionBlockVisitor(BlockVisitor):
"""Visits function nodes to determine variables and generator state."""
# pylint: disable=invalid-name,missing-docstring
def __init__(self, node):
BlockVisitor.__init__(self)
self.is_generator = False
node_args = node.args
args = [a.arg for a in node_args.args]
if node_args.vararg:
args.append(node_args.vararg.arg)
if node_args.kwarg:
args.append(node_args.kwarg.arg)
for i, name in enumerate(args):
if name in self.vars:
msg = "duplicate argument '{}' in function definition".format(name)
raise util.ParseError(node, msg)
self.vars[name] = Var(name, Var.TYPE_PARAM, arg_index=i)
def visit_Yield(self, unused_node)
|
disable=unused-argument
self.is_generator = True
|
: # pylint:
|
identifier_name
|
template.ts
|
import marked from "marked";
import slug from "slug";
import {
DocumentSectionInterface,
|
PluginInterface,
TypeRef
} from "../interface";
import { Plugin } from "./plugin";
export function slugTemplate() {
return (text, render) => slug(render(text)).toLowerCase();
}
export interface ITemplateData {
title: string;
type?: TypeRef;
description: string;
headers: string;
navigations: NavigationSectionInterface[];
documents: DocumentSectionInterface[];
projectPackage: any;
graphdocPackage: any;
slug: typeof slugTemplate;
}
type Headers = string[];
type Navs = NavigationSectionInterface[];
type Docs = DocumentSectionInterface[];
export async function createData(
projectPackage: any,
graphdocPackage: any,
plugins: PluginInterface[],
type?: TypeRef
): Promise<ITemplateData> {
const name = (type && type.name) || "";
const [headers, navigations, documents]: [
Headers,
Navs,
Docs
] = await Promise.all([
Plugin.collectHeaders(plugins, name),
Plugin.collectNavigations(plugins, name),
Plugin.collectDocuments(plugins, name)
]);
const title =
name || (projectPackage && projectPackage.graphdoc && projectPackage.graphdoc.title) || "Graphql schema documentation";
const description = type
? marked(type.description || "")
: marked(projectPackage.description || "");
return {
title,
type,
description,
headers: headers.join(""),
navigations,
documents,
projectPackage,
graphdocPackage,
slug: slugTemplate
};
}
|
NavigationSectionInterface,
|
random_line_split
|
template.ts
|
import marked from "marked";
import slug from "slug";
import {
DocumentSectionInterface,
NavigationSectionInterface,
PluginInterface,
TypeRef
} from "../interface";
import { Plugin } from "./plugin";
export function
|
() {
return (text, render) => slug(render(text)).toLowerCase();
}
export interface ITemplateData {
title: string;
type?: TypeRef;
description: string;
headers: string;
navigations: NavigationSectionInterface[];
documents: DocumentSectionInterface[];
projectPackage: any;
graphdocPackage: any;
slug: typeof slugTemplate;
}
type Headers = string[];
type Navs = NavigationSectionInterface[];
type Docs = DocumentSectionInterface[];
export async function createData(
projectPackage: any,
graphdocPackage: any,
plugins: PluginInterface[],
type?: TypeRef
): Promise<ITemplateData> {
const name = (type && type.name) || "";
const [headers, navigations, documents]: [
Headers,
Navs,
Docs
] = await Promise.all([
Plugin.collectHeaders(plugins, name),
Plugin.collectNavigations(plugins, name),
Plugin.collectDocuments(plugins, name)
]);
const title =
name || (projectPackage && projectPackage.graphdoc && projectPackage.graphdoc.title) || "Graphql schema documentation";
const description = type
? marked(type.description || "")
: marked(projectPackage.description || "");
return {
title,
type,
description,
headers: headers.join(""),
navigations,
documents,
projectPackage,
graphdocPackage,
slug: slugTemplate
};
}
|
slugTemplate
|
identifier_name
|
template.ts
|
import marked from "marked";
import slug from "slug";
import {
DocumentSectionInterface,
NavigationSectionInterface,
PluginInterface,
TypeRef
} from "../interface";
import { Plugin } from "./plugin";
export function slugTemplate()
|
export interface ITemplateData {
title: string;
type?: TypeRef;
description: string;
headers: string;
navigations: NavigationSectionInterface[];
documents: DocumentSectionInterface[];
projectPackage: any;
graphdocPackage: any;
slug: typeof slugTemplate;
}
type Headers = string[];
type Navs = NavigationSectionInterface[];
type Docs = DocumentSectionInterface[];
export async function createData(
projectPackage: any,
graphdocPackage: any,
plugins: PluginInterface[],
type?: TypeRef
): Promise<ITemplateData> {
const name = (type && type.name) || "";
const [headers, navigations, documents]: [
Headers,
Navs,
Docs
] = await Promise.all([
Plugin.collectHeaders(plugins, name),
Plugin.collectNavigations(plugins, name),
Plugin.collectDocuments(plugins, name)
]);
const title =
name || (projectPackage && projectPackage.graphdoc && projectPackage.graphdoc.title) || "Graphql schema documentation";
const description = type
? marked(type.description || "")
: marked(projectPackage.description || "");
return {
title,
type,
description,
headers: headers.join(""),
navigations,
documents,
projectPackage,
graphdocPackage,
slug: slugTemplate
};
}
|
{
return (text, render) => slug(render(text)).toLowerCase();
}
|
identifier_body
|
top10artists.component.ts
|
import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import { Artist } from './../Modules/artist';
import { ArtistService } from './../Services/artist.service';
import { SongService } from '../Services/song.service';
@Component({
selector: 'top10artists',
templateUrl: './../Views/top10artists.component.html',
providers: [SongService]
})
export class Top10ArtistsComponent implements OnInit {
artists: Array<Artist>;
private width: number;
|
private height: number;
private radius: number;
private arc: any;
private labelArc: any;
private pie: any;
private color: any;
private svg: any;
constructor(private artistService: ArtistService) {
this.width = 500;
this.height = 500;
this.radius = Math.min(this.width, this.height) / 2;
this.artists = new Array<Artist>();
this.getArtist();
}
ngOnInit(): void {
this.initSvg();
}
initSvg(): any {
this.color = d3Scale.scaleOrdinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
this.arc = d3Shape.arc()
.outerRadius(this.radius - 10)
.innerRadius(0);
this.labelArc = d3Shape.arc()
.outerRadius(this.radius - 40)
.innerRadius(this.radius - 40);
this.pie = d3Shape.pie()
.sort(null)
.value((d: any) => d.views);
this.svg = d3.select("svg")
.append("g")
.attr("transform", "translate(" + this.width / 2 + "," + this.height / 2 + ")");;
}
getArtist(): void {
this.artistService.getTopArtists()
.subscribe((topArtists) => {
this.artists = topArtists;
this.drawPie();
})
}
private drawPie() {
let g = this.svg.selectAll(".arc")
.data(this.pie(this.artists))
.enter().append("g")
.attr("class", "arc");
g.append("path").attr("d", this.arc)
.style("fill", (d: { data: Artist }) => this.color(d.data._id));
g.append("text").attr("transform", (d: any) => "translate(" + this.labelArc.centroid(d) + ")")
.attr("dy", ".35em")
.text((d: { data: Artist }) => {
return d.data.firstName + ' ' + d.data.lastName;
});
}
}
|
random_line_split
|
|
top10artists.component.ts
|
import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import { Artist } from './../Modules/artist';
import { ArtistService } from './../Services/artist.service';
import { SongService } from '../Services/song.service';
@Component({
selector: 'top10artists',
templateUrl: './../Views/top10artists.component.html',
providers: [SongService]
})
export class Top10ArtistsComponent implements OnInit {
artists: Array<Artist>;
private width: number;
private height: number;
private radius: number;
private arc: any;
private labelArc: any;
private pie: any;
private color: any;
private svg: any;
constructor(private artistService: ArtistService) {
this.width = 500;
this.height = 500;
this.radius = Math.min(this.width, this.height) / 2;
this.artists = new Array<Artist>();
this.getArtist();
}
ngOnInit(): void {
this.initSvg();
}
|
(): any {
this.color = d3Scale.scaleOrdinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
this.arc = d3Shape.arc()
.outerRadius(this.radius - 10)
.innerRadius(0);
this.labelArc = d3Shape.arc()
.outerRadius(this.radius - 40)
.innerRadius(this.radius - 40);
this.pie = d3Shape.pie()
.sort(null)
.value((d: any) => d.views);
this.svg = d3.select("svg")
.append("g")
.attr("transform", "translate(" + this.width / 2 + "," + this.height / 2 + ")");;
}
getArtist(): void {
this.artistService.getTopArtists()
.subscribe((topArtists) => {
this.artists = topArtists;
this.drawPie();
})
}
private drawPie() {
let g = this.svg.selectAll(".arc")
.data(this.pie(this.artists))
.enter().append("g")
.attr("class", "arc");
g.append("path").attr("d", this.arc)
.style("fill", (d: { data: Artist }) => this.color(d.data._id));
g.append("text").attr("transform", (d: any) => "translate(" + this.labelArc.centroid(d) + ")")
.attr("dy", ".35em")
.text((d: { data: Artist }) => {
return d.data.firstName + ' ' + d.data.lastName;
});
}
}
|
initSvg
|
identifier_name
|
top10artists.component.ts
|
import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import { Artist } from './../Modules/artist';
import { ArtistService } from './../Services/artist.service';
import { SongService } from '../Services/song.service';
@Component({
selector: 'top10artists',
templateUrl: './../Views/top10artists.component.html',
providers: [SongService]
})
export class Top10ArtistsComponent implements OnInit {
artists: Array<Artist>;
private width: number;
private height: number;
private radius: number;
private arc: any;
private labelArc: any;
private pie: any;
private color: any;
private svg: any;
constructor(private artistService: ArtistService) {
this.width = 500;
this.height = 500;
this.radius = Math.min(this.width, this.height) / 2;
this.artists = new Array<Artist>();
this.getArtist();
}
ngOnInit(): void {
this.initSvg();
}
initSvg(): any {
this.color = d3Scale.scaleOrdinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
this.arc = d3Shape.arc()
.outerRadius(this.radius - 10)
.innerRadius(0);
this.labelArc = d3Shape.arc()
.outerRadius(this.radius - 40)
.innerRadius(this.radius - 40);
this.pie = d3Shape.pie()
.sort(null)
.value((d: any) => d.views);
this.svg = d3.select("svg")
.append("g")
.attr("transform", "translate(" + this.width / 2 + "," + this.height / 2 + ")");;
}
getArtist(): void {
this.artistService.getTopArtists()
.subscribe((topArtists) => {
this.artists = topArtists;
this.drawPie();
})
}
private drawPie()
|
}
|
{
let g = this.svg.selectAll(".arc")
.data(this.pie(this.artists))
.enter().append("g")
.attr("class", "arc");
g.append("path").attr("d", this.arc)
.style("fill", (d: { data: Artist }) => this.color(d.data._id));
g.append("text").attr("transform", (d: any) => "translate(" + this.labelArc.centroid(d) + ")")
.attr("dy", ".35em")
.text((d: { data: Artist }) => {
return d.data.firstName + ' ' + d.data.lastName;
});
}
|
identifier_body
|
nehan.tip.js
|
// nehan.tip.js
// Copyright(c) 2014-, Watanabe Masaki
// license: MIT
|
/**
plugin name: tip
description: create link that shows popup message when clicked.
tag_name: tip
close_tag: required
attributes:
- title: tip title
example:
<tip title="this is tip title">this text is popuped when clicked.</tip>
*/
Nehan.setStyle("tip", {
"display":"inline",
"background-color":"gold",
"color":"green",
// <tip title='cilck me'>some text</tip>
// => <a href='#' data-title='click me' data-content='some text'>click me</a>
"onload":function(selector_context){
var markup = selector_context.getMarkup();
var tip_title = markup.getAttr("title");
var tip_content = markup.getContent();
markup.setAlias("a");
markup.setAttr("href", "#" + tip_title);
markup.setData("title", tip_title);
markup.setData("content", tip_content);
markup.setContent(tip_title);
},
"oncreate":function(context){
var tip_content = context.box.style.getMarkupData("content");
context.dom.onclick = function(){
alert(tip_content);
return false;
};
}
});
|
random_line_split
|
|
UnZip.py
|
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12"
__description = """Zip extractor plugin"""
__license = "GPLv3"
__authors = [("Walter Purcaro", "[email protected]")]
EXTENSIONS = [".zip", ".zip64"]
NAME = __name__.rsplit('.', 1)[1]
VERSION = "(python %s.%s.%s)" % (sys.version_info[0], sys.version_info[1], sys.version_info[2])
@classmethod
def isUsable(cls):
|
def list(self, password=None):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
return z.namelist()
def check(self, password):
pass
def verify(self):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
raise PasswordError
def extract(self, password=None):
try:
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
z.extractall(self.out)
except (zipfile.BadZipfile, zipfile.LargeZipFile), e:
raise ArchiveError(e)
except RuntimeError, e:
if "encrypted" in e:
raise PasswordError
else:
raise ArchiveError(e)
else:
self.files = z.namelist()
|
return sys.version_info[:2] >= (2, 6)
|
identifier_body
|
UnZip.py
|
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12"
__description = """Zip extractor plugin"""
__license = "GPLv3"
__authors = [("Walter Purcaro", "[email protected]")]
EXTENSIONS = [".zip", ".zip64"]
NAME = __name__.rsplit('.', 1)[1]
|
@classmethod
def isUsable(cls):
return sys.version_info[:2] >= (2, 6)
def list(self, password=None):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
return z.namelist()
def check(self, password):
pass
def verify(self):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
raise PasswordError
def extract(self, password=None):
try:
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
z.extractall(self.out)
except (zipfile.BadZipfile, zipfile.LargeZipFile), e:
raise ArchiveError(e)
except RuntimeError, e:
if "encrypted" in e:
raise PasswordError
else:
raise ArchiveError(e)
else:
self.files = z.namelist()
|
VERSION = "(python %s.%s.%s)" % (sys.version_info[0], sys.version_info[1], sys.version_info[2])
|
random_line_split
|
UnZip.py
|
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12"
__description = """Zip extractor plugin"""
__license = "GPLv3"
__authors = [("Walter Purcaro", "[email protected]")]
EXTENSIONS = [".zip", ".zip64"]
NAME = __name__.rsplit('.', 1)[1]
VERSION = "(python %s.%s.%s)" % (sys.version_info[0], sys.version_info[1], sys.version_info[2])
@classmethod
def isUsable(cls):
return sys.version_info[:2] >= (2, 6)
def list(self, password=None):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
return z.namelist()
def
|
(self, password):
pass
def verify(self):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
raise PasswordError
def extract(self, password=None):
try:
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
z.extractall(self.out)
except (zipfile.BadZipfile, zipfile.LargeZipFile), e:
raise ArchiveError(e)
except RuntimeError, e:
if "encrypted" in e:
raise PasswordError
else:
raise ArchiveError(e)
else:
self.files = z.namelist()
|
check
|
identifier_name
|
UnZip.py
|
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12"
__description = """Zip extractor plugin"""
__license = "GPLv3"
__authors = [("Walter Purcaro", "[email protected]")]
EXTENSIONS = [".zip", ".zip64"]
NAME = __name__.rsplit('.', 1)[1]
VERSION = "(python %s.%s.%s)" % (sys.version_info[0], sys.version_info[1], sys.version_info[2])
@classmethod
def isUsable(cls):
return sys.version_info[:2] >= (2, 6)
def list(self, password=None):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
return z.namelist()
def check(self, password):
pass
def verify(self):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
raise PasswordError
def extract(self, password=None):
try:
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
z.extractall(self.out)
except (zipfile.BadZipfile, zipfile.LargeZipFile), e:
raise ArchiveError(e)
except RuntimeError, e:
if "encrypted" in e:
|
else:
raise ArchiveError(e)
else:
self.files = z.namelist()
|
raise PasswordError
|
conditional_block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.