code stringlengths 4 1.01M |
|---|
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: qb_docker_image
short_description: QB extension of Ansible's `docker_image` module.
description:
- Build, load or pull an image, making the image available for creating containers. Also supports tagging an
image into a repository and archiving an image to a .tar file.
options:
archive_path:
description:
- Use with state C(present) to archive an image to a .tar file.
required: false
version_added: "2.1"
load_path:
description:
- Use with state C(present) to load an image from a .tar file.
required: false
version_added: "2.2"
dockerfile:
description:
- Use with state C(present) to provide an alternate name for the Dockerfile to use when building an image.
default: Dockerfile
required: false
version_added: "2.0"
force:
description:
- Use with state I(absent) to un-tag and remove all images matching the specified name. Use with state
C(present) to build, load or pull an image when the image already exists.
default: false
required: false
version_added: "2.1"
type: bool
http_timeout:
description:
- Timeout for HTTP requests during the image build operation. Provide a positive integer value for the number of
seconds.
required: false
version_added: "2.1"
name:
description:
- "Image name. Name format will be one of: name, repository/name, registry_server:port/name.
When pushing or pulling an image the name can optionally include the tag by appending ':tag_name'."
required: true
path:
description:
- Use with state 'present' to build an image. Will be the path to a directory containing the context and
Dockerfile for building an image.
aliases:
- build_path
required: false
pull:
description:
- When building an image downloads any updates to the FROM image in Dockerfile.
default: true
required: false
version_added: "2.1"
type: bool
push:
description:
- Push the image to the registry. Specify the registry as part of the I(name) or I(repository) parameter.
default: false
required: false
version_added: "2.2"
type: bool
rm:
description:
- Remove intermediate containers after build.
default: true
required: false
version_added: "2.1"
type: bool
nocache:
description:
- Do not use cache when building an image.
default: false
required: false
type: bool
repository:
description:
- Full path to a repository. Use with state C(present) to tag the image into the repository. Expects
format I(repository:tag). If no tag is provided, will use the value of the C(tag) parameter or I(latest).
required: false
version_added: "2.1"
state:
description:
- Make assertions about the state of an image.
- When C(absent) an image will be removed. Use the force option to un-tag and remove all images
matching the provided name.
- When C(present) check if an image exists using the provided name and tag. If the image is not found or the
force option is used, the image will either be pulled, built or loaded. By default the image will be pulled
from Docker Hub. To build the image, provide a path value set to a directory containing a context and
Dockerfile. To load an image, specify load_path to provide a path to an archive file. To tag an image to a
repository, provide a repository path. If the name contains a repository path, it will be pushed.
- "NOTE: C(build) is DEPRECATED and will be removed in release 2.3. Specifying C(build) will behave the
same as C(present)."
required: false
default: present
choices:
- absent
- present
- build
tag:
description:
- Used to select an image when pulling. Will be added to the image when pushing, tagging or building. Defaults to
I(latest).
- If C(name) parameter format is I(name:tag), then tag value from C(name) will take precedence.
default: latest
required: false
buildargs:
description:
- Provide a dictionary of C(key:value) build arguments that map to Dockerfile ARG directive.
- Docker expects the value to be a string. For convenience any non-string values will be converted to strings.
- Requires Docker API >= 1.21 and docker-py >= 1.7.0.
required: false
version_added: "2.2"
container_limits:
description:
- A dictionary of limits applied to each container created by the build process.
required: false
version_added: "2.1"
suboptions:
memory:
description:
- Set memory limit for build.
memswap:
description:
- Total memory (memory + swap), -1 to disable swap.
cpushares:
description:
- CPU shares (relative weight).
cpusetcpus:
description:
- CPUs in which to allow execution, e.g., "0-3", "0,1".
use_tls:
description:
- "DEPRECATED. Whether to use tls to connect to the docker server. Set to C(no) when TLS will not be used. Set to
C(encrypt) to use TLS. And set to C(verify) to use TLS and verify that the server's certificate is valid for the
server. NOTE: If you specify this option, it will set the value of the tls or tls_verify parameters."
choices:
- no
- encrypt
- verify
default: no
required: false
version_added: "2.0"
try_to_pull:
description:
- Try to pull the image before building. Added by QB.
choices:
- yes
- no
default: yes
required: false
extends_documentation_fragment:
- docker
requirements:
- "python >= 2.6"
- "docker-py >= 1.7.0"
- "Docker API >= 1.20"
author:
- Pavel Antonov (@softzilla)
- Chris Houseknecht (@chouseknecht)
- James Tanner (@jctanner)
'''
EXAMPLES = '''
- name: pull an image
docker_image:
name: pacur/centos-7
- name: Tag and push to docker hub
docker_image:
name: pacur/centos-7
repository: dcoppenhagan/myimage
tag: 7.0
push: yes
- name: Tag and push to local registry
docker_image:
name: centos
repository: localhost:5000/centos
tag: 7
push: yes
- name: Remove image
docker_image:
state: absent
name: registry.ansible.com/chouseknecht/sinatra
tag: v1
- name: Build an image and push it to a private repo
docker_image:
path: ./sinatra
name: registry.ansible.com/chouseknecht/sinatra
tag: v1
push: yes
- name: Archive image
docker_image:
name: registry.ansible.com/chouseknecht/sinatra
tag: v1
archive_path: my_sinatra.tar
- name: Load image from archive and push to a private registry
docker_image:
name: localhost:5000/myimages/sinatra
tag: v1
push: yes
load_path: my_sinatra.tar
- name: Build image and with buildargs
docker_image:
path: /path/to/build/dir
name: myimage
buildargs:
log_volume: /var/log/myapp
listen_port: 8080
'''
RETURN = '''
image:
description: Image inspection results for the affected image.
returned: success
type: dict
sample: {}
'''
import os
import re
import json
import socket
import threading
import logging
from ansible.module_utils.docker_common import HAS_DOCKER_PY_2, AnsibleDockerClient, DockerBaseClass
from ansible.module_utils._text import to_native
try:
if HAS_DOCKER_PY_2:
from docker.auth import resolve_repository_name
else:
from docker.auth.auth import resolve_repository_name
from docker.utils.utils import parse_repository_tag
except ImportError:
# missing docker-py handled in docker_common
pass
import qb.ipc.stdio
import qb.ipc.stdio.logging_
# from qb.ipc.stdio import client as io_client, logging_ as stdio_logging
# import qb.ipc.stdio.logging_
# from qb.ipc.stdio import
logger = qb.ipc.stdio.logging_.getLogger('qb_docker_image')
class QBAnsibleDockerClient( AnsibleDockerClient ):
def try_pull_image(self, name, tag="latest"):
'''
Pull an image
'''
self.log("(Try) Pulling image %s:%s" % (name, tag))
try:
for line in self.pull(name, tag=tag, stream=True, decode=True):
self.log(line, pretty_print=True)
if line.get('error'):
return None
except Exception as exc:
self.log("Error pulling image %s:%s - %s" % (name, tag, str(exc)))
return None
return self.find_image(name=name, tag=tag)
def log(self, msg, pretty_print=False):
qb_log(msg)
class ImageManager(DockerBaseClass):
def __init__(self, client, results):
super(ImageManager, self).__init__()
self.client = client
self.results = results
parameters = self.client.module.params
self.check_mode = self.client.check_mode
self.archive_path = parameters.get('archive_path')
self.container_limits = parameters.get('container_limits')
self.dockerfile = parameters.get('dockerfile')
self.force = parameters.get('force')
self.load_path = parameters.get('load_path')
self.name = parameters.get('name')
self.nocache = parameters.get('nocache')
self.path = parameters.get('path')
self.pull = parameters.get('pull')
self.repository = parameters.get('repository')
self.rm = parameters.get('rm')
self.state = parameters.get('state')
self.tag = parameters.get('tag')
self.http_timeout = parameters.get('http_timeout')
self.push = parameters.get('push')
self.buildargs = parameters.get('buildargs')
# QB additions
self.try_to_pull = parameters.get('try_to_pull')
self.logger = qb.ipc.stdio.logging_.getLogger(
'qb_docker_image:ImageManager',
level = logging.DEBUG
)
# If name contains a tag, it takes precedence over tag parameter.
repo, repo_tag = parse_repository_tag(self.name)
if repo_tag:
self.name = repo
self.tag = repo_tag
if self.state in ['present', 'build']:
self.present()
elif self.state == 'absent':
self.absent()
def fail(self, msg):
self.client.fail(msg)
def present(self):
'''
Handles state = 'present', which includes building, loading or pulling
an image, depending on user provided parameters.
:returns None
'''
self.logger.info("Starting state=present...")
image = self.client.find_image(name=self.name, tag=self.tag)
pulled_image = None
if not image or self.force:
if self.try_to_pull:
self.log("Try to pull the image")
self.results['actions'].append(
'Tried to pull image %s:%s' % (self.name, self.tag)
)
self.results['changed'] = True
if not self.check_mode:
pulled_image = self.client.try_pull_image(self.name, tag=self.tag)
if pulled_image:
self.results['actions'].append(
'Pulled image %s:%s' % (self.name, self.tag)
)
self.results['image'] = pulled_image
if pulled_image is None:
if self.path:
# Build the image
if not os.path.isdir(self.path):
self.fail("Requested build path %s could not be found or you do not have access." % self.path)
image_name = self.name
if self.tag:
image_name = "%s:%s" % (self.name, self.tag)
self.log("Building image %s" % image_name)
self.results['actions'].append("Built image %s from %s" % (image_name, self.path))
self.results['changed'] = True
if not self.check_mode:
self.results['image'] = self.build_image()
elif self.load_path:
# Load the image from an archive
if not os.path.isfile(self.load_path):
self.fail("Error loading image %s. Specified path %s does not exist." % (self.name,
self.load_path))
image_name = self.name
if self.tag:
image_name = "%s:%s" % (self.name, self.tag)
self.results['actions'].append("Loaded image %s from %s" % (image_name, self.load_path))
self.results['changed'] = True
if not self.check_mode:
self.results['image'] = self.load_image()
else:
# pull the image
self.results['actions'].append('Pulled image %s:%s' % (self.name, self.tag))
self.results['changed'] = True
if not self.check_mode:
self.results['image'] = self.client.pull_image(self.name, tag=self.tag)
if image and image == self.results['image']:
self.results['changed'] = False
if self.archive_path:
self.archive_image(self.name, self.tag)
# Only push if:
#
# 1. We didn't pull the image (if we did pull it we have no need to
# then push it).
# 2. We have a local image or image result (or what are we pushing)
# have_image = image or len(self.result['image']) > 0
# 3. Either:
# A. We didn't find any image before doing anything
# B. The resulting image is different
#
# image_is_different = (
# (not image) or (
# len(self.results image[u'Id'] != self.results['image'][u'Id']
self.logger.debug("Deciding to push...")
if (
pulled_image is None and (
image or self.result['image']
) and (
((not image) and self.results['image']) or
(image and self.results['image'] and image['Id'] != self.results['Id'])
)
):
self.logger.debug("Into push section!")
# self.log("have_image: {}".format(have_image))
# self.log("image_is_different: {}".format(image_is_different))
self.logger.debug("Image", image)
# if self.push and not self.repository:
# self.push_image(self.name, self.tag)
# elif self.repository:
# self.tag_image(
# self.name,
# self.tag,
# self.repository,
# force=self.force,
# push=self.push
# )
def absent(self):
'''
Handles state = 'absent', which removes an image.
:return None
'''
image = self.client.find_image(self.name, self.tag)
if image:
name = self.name
if self.tag:
name = "%s:%s" % (self.name, self.tag)
if not self.check_mode:
try:
self.client.remove_image(name, force=self.force)
except Exception as exc:
self.fail("Error removing image %s - %s" % (name, str(exc)))
self.results['changed'] = True
self.results['actions'].append("Removed image %s" % (name))
self.results['image']['state'] = 'Deleted'
def archive_image(self, name, tag):
'''
Archive an image to a .tar file. Called when archive_path is passed.
:param name - name of the image. Type: str
:return None
'''
if not tag:
tag = "latest"
image = self.client.find_image(name=name, tag=tag)
if not image:
self.log("archive image: image %s:%s not found" % (name, tag))
return
image_name = "%s:%s" % (name, tag)
self.results['actions'].append('Archived image %s to %s' % (image_name, self.archive_path))
self.results['changed'] = True
if not self.check_mode:
self.log("Getting archive of image %s" % image_name)
try:
image = self.client.get_image(image_name)
except Exception as exc:
self.fail("Error getting image %s - %s" % (image_name, str(exc)))
try:
with open(self.archive_path, 'w') as fd:
for chunk in image.stream(2048, decode_content=False):
fd.write(chunk)
except Exception as exc:
self.fail("Error writing image archive %s - %s" % (self.archive_path, str(exc)))
image = self.client.find_image(name=name, tag=tag)
if image:
self.results['image'] = image
def push_image(self, name, tag=None):
'''
If the name of the image contains a repository path, then push the image.
:param name Name of the image to push.
:param tag Use a specific tag.
:return: None
'''
repository = name
if not tag:
repository, tag = parse_repository_tag(name)
registry, repo_name = resolve_repository_name(repository)
self.log("push %s to %s/%s:%s" % (self.name, registry, repo_name, tag))
if registry:
self.results['actions'].append("Pushed image %s to %s/%s:%s" % (self.name, registry, repo_name, tag))
self.results['changed'] = True
if not self.check_mode:
status = None
try:
for line in self.client.push(repository, tag=tag, stream=True, decode=True):
self.log(line, pretty_print=True)
if line.get('errorDetail'):
raise Exception(line['errorDetail']['message'])
status = line.get('status')
except Exception as exc:
if re.search('unauthorized', str(exc)):
if re.search('authentication required', str(exc)):
self.fail("Error pushing image %s/%s:%s - %s. Try logging into %s first." %
(registry, repo_name, tag, str(exc), registry))
else:
self.fail("Error pushing image %s/%s:%s - %s. Does the repository exist?" %
(registry, repo_name, tag, str(exc)))
self.fail("Error pushing image %s: %s" % (repository, str(exc)))
self.results['image'] = self.client.find_image(name=repository, tag=tag)
if not self.results['image']:
self.results['image'] = dict()
self.results['image']['push_status'] = status
def tag_image(self, name, tag, repository, force=False, push=False):
'''
Tag an image into a repository.
:param name: name of the image. required.
:param tag: image tag.
:param repository: path to the repository. required.
:param force: bool. force tagging, even it image already exists with the repository path.
:param push: bool. push the image once it's tagged.
:return: None
'''
repo, repo_tag = parse_repository_tag(repository)
if not repo_tag:
repo_tag = "latest"
if tag:
repo_tag = tag
image = self.client.find_image(name=repo, tag=repo_tag)
found = 'found' if image else 'not found'
self.log("image %s was %s" % (repo, found))
if not image or force:
self.log("tagging %s:%s to %s:%s" % (name, tag, repo, repo_tag))
self.results['changed'] = True
self.results['actions'].append("Tagged image %s:%s to %s:%s" % (name, tag, repo, repo_tag))
if not self.check_mode:
try:
# Finding the image does not always work, especially running a localhost registry. In those
# cases, if we don't set force=True, it errors.
image_name = name
if tag and not re.search(tag, name):
image_name = "%s:%s" % (name, tag)
tag_status = self.client.tag(image_name, repo, tag=repo_tag, force=True)
if not tag_status:
raise Exception("Tag operation failed.")
except Exception as exc:
self.fail("Error: failed to tag image - %s" % str(exc))
self.results['image'] = self.client.find_image(name=repo, tag=repo_tag)
if push:
self.push_image(repo, repo_tag)
def build_image(self):
'''
Build an image
:return: image dict
'''
params = dict(
path=self.path,
tag=self.name,
rm=self.rm,
nocache=self.nocache,
stream=True,
timeout=self.http_timeout,
pull=self.pull,
forcerm=self.rm,
dockerfile=self.dockerfile,
decode=True
)
build_output = []
if self.tag:
params['tag'] = "%s:%s" % (self.name, self.tag)
if self.container_limits:
params['container_limits'] = self.container_limits
if self.buildargs:
for key, value in self.buildargs.items():
self.buildargs[key] = to_native(value)
params['buildargs'] = self.buildargs
for line in self.client.build(**params):
# line = json.loads(line)
self.log(line, pretty_print=True)
if "stream" in line:
build_output.append(line["stream"])
if line.get('error'):
if line.get('errorDetail'):
errorDetail = line.get('errorDetail')
self.fail(
"Error building %s - code: %s, message: %s, logs: %s" % (
self.name,
errorDetail.get('code'),
errorDetail.get('message'),
build_output))
else:
self.fail("Error building %s - message: %s, logs: %s" % (
self.name, line.get('error'), build_output))
return self.client.find_image(name=self.name, tag=self.tag)
def load_image(self):
'''
Load an image from a .tar archive
:return: image dict
'''
try:
self.log("Opening image %s" % self.load_path)
image_tar = open(self.load_path, 'r')
except Exception as exc:
self.fail("Error opening image %s - %s" % (self.load_path, str(exc)))
try:
self.log("Loading image from %s" % self.load_path)
self.client.load_image(image_tar)
except Exception as exc:
self.fail("Error loading image %s - %s" % (self.name, str(exc)))
try:
image_tar.close()
except Exception as exc:
self.fail("Error closing image %s - %s" % (self.name, str(exc)))
return self.client.find_image(self.name, self.tag)
def log(self, msg, pretty_print=False):
return qb_log(msg)
def warn( self, warning ):
self.results['warnings'].append( str(warning) )
def qb_log( msg ):
if not qb.ipc.stdio.client.stdout.connected:
return False
string = None
if isinstance( msg, str ):
string = msg
elif isinstance( msg, dict ):
if 'stream' in msg:
string = msg['stream']
else:
string = json.dumps(
msg,
sort_keys=True,
indent=4,
separators=(',', ': ')
)
if string is not None:
if not string.endswith( u"\n" ):
string = string + u"\n"
qb.ipc.stdio.client.stdout.socket.sendall(string)
return True
def qb_debug(name, message, **payload):
if not qb.ipc.stdio.client.log.connected:
return False
struct = dict(
level='debug',
name=name,
pid=os.getpid(),
thread=threading.current_thread().name,
message=message,
payload=payload,
)
string = json.dumps(struct)
if not string.endswith( u"\n" ):
string = string + u"\n"
qb.ipc.stdio.client.log.socket.sendall(string)
return True
def main():
argument_spec = dict(
archive_path=dict(type='path'),
container_limits=dict(type='dict'),
dockerfile=dict(type='str'),
force=dict(type='bool', default=False),
http_timeout=dict(type='int'),
load_path=dict(type='path'),
name=dict(type='str', required=True),
nocache=dict(type='bool', default=False),
path=dict(type='path', aliases=['build_path']),
pull=dict(type='bool', default=True),
push=dict(type='bool', default=False),
repository=dict(type='str'),
rm=dict(type='bool', default=True),
state=dict(type='str', choices=['absent', 'present', 'build'], default='present'),
tag=dict(type='str', default='latest'),
use_tls=dict(type='str', default='no', choices=['no', 'encrypt', 'verify']),
buildargs=dict(type='dict', default=None),
# QB additions
try_to_pull=dict( type='bool', default=True ),
)
client = QBAnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True,
)
results = dict(
changed=False,
actions=[],
image={},
warnings=[],
)
qb.ipc.stdio.client.connect(results['warnings'])
logger.info("HERERERERE", extra=dict(payload=dict(x='ex', y='why?')))
ImageManager(client, results)
client.module.exit_json(**results)
if __name__ == '__main__':
main()
|
<?php
/**
* Show error messages
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if ( ! $errors ) return;
?>
<div class="alert-box alert" data-alert>
<ul class="errors">
<?php foreach ( $errors as $error ) : ?>
<li><?php echo wp_kses_post( $error ); ?></li>
<?php endforeach; ?>
</ul>
<a href="#" class="close">×</a>
</div> |
using System;
namespace StateMechanic
{
/// <summary>
/// Exception thrown when a transition could not be created from a state on an event, because the state and event do not belong to the same state machine
/// </summary>
public class InvalidEventTransitionException : Exception
{
/// <summary>
/// Gets the state from which the transition could not be created
/// </summary>
public IState From { get; }
/// <summary>
/// Gets the event on which the transition could not be created
/// </summary>
public IEvent Event { get; }
internal InvalidEventTransitionException(IState from, IEvent @event)
: base(String.Format("Unable to create transition from state {0} on event {1}, as state {0} does not belong to the same state machine as event {1}, or to a child state machine of event {1}", from.Name, @event.Name))
{
this.From = from;
this.Event = @event;
}
}
}
|
<?php
$opc = $_GET['opc'];
$local_opc = ini_get('opcache.enable');
$ua = $_GET['ua'];
if ($local_opc != $opc)
{
throw new Exception("$local_opc != $opc");
}
$time = microtime(true);
require_once 'uaparser-new.php';
$uap = new UAParserNew('regexes.php');
$uap->parse($ua);
echo microtime(true) - $time;
|
<canvas id="drawing" width="200" height="200">A drawing of something.</canvas>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from decimal import Decimal
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('farms', '0024_rain_and_irrigation_allow_null'),
]
operations = [
migrations.AlterField(
model_name='probereading',
name='irrigation',
field=models.DecimalField(decimal_places=2, validators=[django.core.validators.MinValueValidator(Decimal('0'))], max_digits=4, blank=True, null=True, verbose_name=b'Irrigation in inches'),
preserve_default=True,
),
migrations.AlterField(
model_name='probereading',
name='rain',
field=models.DecimalField(decimal_places=2, validators=[django.core.validators.MinValueValidator(Decimal('0'))], max_digits=4, blank=True, null=True, verbose_name=b'Rainfall in inches'),
preserve_default=True,
),
migrations.AlterField(
model_name='waterhistory',
name='irrigation',
field=models.DecimalField(decimal_places=2, validators=[django.core.validators.MinValueValidator(Decimal('0'))], max_digits=4, blank=True, null=True, verbose_name=b'Irrigation in inches'),
preserve_default=True,
),
migrations.AlterField(
model_name='waterhistory',
name='rain',
field=models.DecimalField(decimal_places=2, validators=[django.core.validators.MinValueValidator(Decimal('0'))], max_digits=4, blank=True, null=True, verbose_name=b'Rainfall in inches'),
preserve_default=True,
),
migrations.AlterField(
model_name='waterregister',
name='irrigation',
field=models.DecimalField(decimal_places=2, validators=[django.core.validators.MinValueValidator(Decimal('0'))], max_digits=4, blank=True, null=True, verbose_name=b'Irrigation in inches'),
preserve_default=True,
),
migrations.AlterField(
model_name='waterregister',
name='rain',
field=models.DecimalField(decimal_places=2, validators=[django.core.validators.MinValueValidator(Decimal('0'))], max_digits=4, blank=True, null=True, verbose_name=b'Rainfall in inches'),
preserve_default=True,
),
]
|
import { ProviderEvent } from "./ProviderEvent";
/**
*
* Interface for data provider cell events.
*/
export interface ProviderCellEvent extends ProviderEvent {
/**
* Cell ids for cells where data have been created.
*/
cellIds: string[];
/**
* Provider event type.
*/
type: "datacreate";
}
|
<?php
declare(strict_types=1);
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\Tests\OrmFunctionalTestCase;
use function array_filter;
use function current;
use function method_exists;
use function sprintf;
use function strpos;
/** @group GH7875 */
final class GH7875Test extends OrmFunctionalTestCase
{
/** @after */
public function cleanUpSchema(): void
{
$connection = $this->_em->getConnection();
$connection->exec('DROP TABLE IF EXISTS gh7875_my_entity');
$connection->exec('DROP TABLE IF EXISTS gh7875_my_other_entity');
if ($connection->getDatabasePlatform() instanceof PostgreSqlPlatform) {
$connection->exec('DROP SEQUENCE IF EXISTS gh7875_my_entity_id_seq');
$connection->exec('DROP SEQUENCE IF EXISTS gh7875_my_other_entity_id_seq');
}
}
/**
* @param string[] $sqls
*
* @return string[]
*/
private function filterCreateTable(array $sqls, string $tableName): array
{
return array_filter($sqls, static function (string $sql) use ($tableName): bool {
return strpos($sql, sprintf('CREATE TABLE %s (', $tableName)) === 0;
});
}
public function testUpdateSchemaSql(): void
{
$classes = [$this->_em->getClassMetadata(GH7875MyEntity::class)];
$tool = new SchemaTool($this->_em);
$sqls = $this->filterCreateTable($tool->getUpdateSchemaSql($classes), 'gh7875_my_entity');
self::assertCount(1, $sqls);
$this->_em->getConnection()->exec(current($sqls));
$sqls = array_filter($tool->getUpdateSchemaSql($classes), static function (string $sql): bool {
return strpos($sql, ' gh7875_my_entity ') !== false;
});
self::assertSame([], $sqls);
$classes[] = $this->_em->getClassMetadata(GH7875MyOtherEntity::class);
$sqls = $tool->getUpdateSchemaSql($classes);
self::assertCount(0, $this->filterCreateTable($sqls, 'gh7875_my_entity'));
self::assertCount(1, $this->filterCreateTable($sqls, 'gh7875_my_other_entity'));
}
/**
* @return array<array<string|callable|null>>
*/
public function provideUpdateSchemaSqlWithSchemaAssetFilter(): array
{
return [
['/^(?!my_enti)/', null],
[
null,
static function ($assetName): bool {
return $assetName !== 'gh7875_my_entity';
},
],
];
}
/** @dataProvider provideUpdateSchemaSqlWithSchemaAssetFilter */
public function testUpdateSchemaSqlWithSchemaAssetFilter(?string $filterRegex, ?callable $filterCallback): void
{
if ($filterRegex && ! method_exists(Configuration::class, 'setFilterSchemaAssetsExpression')) {
self::markTestSkipped(sprintf('Test require %s::setFilterSchemaAssetsExpression method', Configuration::class));
}
$classes = [$this->_em->getClassMetadata(GH7875MyEntity::class)];
$tool = new SchemaTool($this->_em);
$tool->createSchema($classes);
$config = $this->_em->getConnection()->getConfiguration();
if ($filterRegex) {
$config->setFilterSchemaAssetsExpression($filterRegex);
} else {
$config->setSchemaAssetsFilter($filterCallback);
}
$previousFilter = $config->getSchemaAssetsFilter();
$sqls = $tool->getUpdateSchemaSql($classes);
$sqls = array_filter($sqls, static function (string $sql): bool {
return strpos($sql, ' gh7875_my_entity ') !== false;
});
self::assertCount(0, $sqls);
self::assertSame($previousFilter, $config->getSchemaAssetsFilter());
}
}
/**
* @Entity
* @Table(name="gh7875_my_entity")
*/
class GH7875MyEntity
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
}
/**
* @Entity
* @Table(name="gh7875_my_other_entity")
*/
class GH7875MyOtherEntity
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
}
|
using System;
using System.Reflection;
using System.Text.RegularExpressions;
using NUnit.Framework;
using SharpTestsEx;
namespace BehaveN.Tests
{
[TestFixture]
public class PatternMaker_Tests
{
[Test]
public void it_generates_patterns_for_int_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_an_int_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given an int 123");
groups["n"].Value.Should().Be("123");
}
[Test]
public void it_generates_patterns_that_support_negatives_for_int_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_an_int_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given an int -123");
groups["n"].Value.Should().Be("-123");
}
public void given_an_int_arg1(int n)
{
}
[Test]
public void it_generates_patterns_for_nullable_int_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_nullable_int_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a nullable int 123");
groups["n"].Value.Should().Be("123");
}
[Test]
public void it_generates_patterns_that_support_null_for_nullable_int_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_nullable_int_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a nullable int null");
groups["n"].Value.Should().Be("null");
}
public void given_a_nullable_int_arg1(int? n)
{
}
[Test]
public void it_generates_patterns_for_decimal_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_decimal_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a decimal 123.456");
groups["d"].Value.Should().Be("123.456");
}
[Test]
public void it_generates_patterns_that_support_negatives_for_decimal_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_decimal_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a decimal -123.456");
groups["d"].Value.Should().Be("-123.456");
}
[Test]
public void it_generates_patterns_that_support_dollar_signs_for_decimal_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_decimal_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a decimal $123.456");
groups["d"].Value.Should().Be("123.456");
}
[Test]
public void it_generates_patterns_that_do_not_require_dots_for_decimal_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_decimal_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a decimal 123");
groups["d"].Value.Should().Be("123");
}
public void given_a_decimal_arg1(decimal d)
{
}
[Test]
public void it_generates_patterns_for_string_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_string_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a string foo bar baz");
groups["s"].Value.Should().Be("foo bar baz");
}
[Test]
public void it_generates_patterns_that_support_quotes_for_string_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_string_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a string \"foo bar baz\"");
groups["s"].Value.Should().Be("foo bar baz");
}
public void given_a_string_arg1(string s)
{
}
[Test]
public void it_generates_patterns_for_date_time_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_a_date_time_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a date time 2009-10-16");
groups["dt"].Value.Should().Be("2009-10-16");
}
public void given_a_date_time_arg1(DateTime dt)
{
}
[Test]
public void it_generates_patterns_for_enum_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_an_enum_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given an enum Foo");
groups["e"].Value.Should().Be("Foo");
}
[Test]
public void it_generates_patterns_that_support_spaces_for_enum_arguments()
{
MethodInfo method = this.GetType().GetMethod("given_an_enum_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given an enum Baz Quux");
groups["e"].Value.Should().Be("Baz Quux");
}
[Test]
public void it_generates_patterns_that_do_not_match_when_an_enum_argument_is_wrong()
{
MethodInfo method = this.GetType().GetMethod("given_an_enum_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given an enum abc");
groups["e"].Value.Should().Be("");
}
public enum MyEnum { Foo, Bar, BazQuux }
public void given_an_enum_arg1(MyEnum e)
{
}
[Test]
public void it_generates_patterns_for_methods_with_two_arguments_in_the_same_order_as_the_method_name()
{
MethodInfo method = this.GetType().GetMethod("given_foo_arg1_and_bar_arg2");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given foo my foo and bar my bar");
groups["fooName"].Value.Should().Be("my foo");
groups["barName"].Value.Should().Be("my bar");
}
public void given_foo_arg1_and_bar_arg2(string fooName, string barName)
{
}
[Test]
public void it_generates_patterns_for_methods_with_two_arguments_not_in_the_same_order_as_the_method_name()
{
MethodInfo method = this.GetType().GetMethod("given_bar_arg2_and_foo_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given bar my bar and foo my foo");
groups["fooName"].Value.Should().Be("my foo");
groups["barName"].Value.Should().Be("my bar");
}
public void given_bar_arg2_and_foo_arg1(string fooName, string barName)
{
}
[Test]
public void it_allows_extra_spaces_in_the_step_an_the_beginning()
{
MethodInfo method = this.GetType().GetMethod("given_a_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, " given a whatever");
groups[0].Success.Should().Be.True();
}
[Test]
public void it_allows_extra_spaces_in_the_step_in_the_middle()
{
MethodInfo method = this.GetType().GetMethod("given_a_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a whatever");
groups[0].Success.Should().Be.True();
}
[Test]
public void it_allows_extra_spaces_in_the_step_an_the_end()
{
MethodInfo method = this.GetType().GetMethod("given_a_arg1");
string pattern = PatternMaker.GetPattern(method);
var groups = ApplyPattern(pattern, "given a whatever ");
groups[0].Success.Should().Be.True();
}
public void given_a_arg1(string whatever)
{
}
private static GroupCollection ApplyPattern(string pattern, string text)
{
var regex = new Regex("^" + pattern + "$");
var match = regex.Match(text);
return match.Groups;
}
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
{!! Html::style('css/app.css') !!}
{!! Html::style('css/theme.default.min.css') !!}
{!! Html::script('js/jquery.min.js') !!}
{!! Html::script('js/bootstrap.min.js') !!}
{!! Html::script('js/jquery.tablesorter.min.js') !!}
<style>
body { padding-top: 60px; }
@media (max-width: 979px) {
body { padding-top: 0px; }
}
</style>
@yield('head')
</head>
@include('partials.navbar')
<body>
<div class="container">
@yield('content')
</div><!-- /.container -->
</body>
</html> |
// instanciando módulos
var gulp = require('gulp');
var watch = require('gulp-watch');
var del = require('del');
var shell = require('gulp-shell');
var connect = require('gulp-connect');
gulp.task('run:pelican', shell.task([
'pelican content -s pelicanconf.py'
]));
gulp.task('clean:pelican', function () {
return del([
'output/*'
]);
});
gulp.task('connect', function(){
connect.server({
root: ['output'],
port: 1337,
livereload: true
});
});
gulp.task('reload:output', function () {
connect.reload();
});
gulp.task('watch', function(){
// watch('content/*', gulp.series('run:pelican', 'reload:output'));
// watch('*', gulp.series('run:pelican', 'reload:output'));
// watch('theme/*', gulp.series('run:pelican', 'reload:output'));
// watch('theme/templates/*', gulp.series('run:pelican', 'reload:output'));
// watch('theme/static/css/*', gulp.series('run:pelican', 'reload:output'));
// watch('theme/static/js/*', gulp.series('run:pelican', 'reload:output'));
})
gulp.task('serve', gulp.parallel('connect','run:pelican', 'watch'));
|
While creating an Azure-based lab is very easy and only requires to set the default virtualization engine to Azure instead of HyperV. Not all features are readily available from the start. To fully make use of Azure, you should also synch your lab sources with Azure. Doing so only requires a single line of code: `Sync-LabAzureLabSources`.
This by default will synchronize your entire local lab sources folder with a pre-created Azure file share called labsources in the resource group AutomatedLabSources and the lab's randomly-named storage account. This file share will automatically be mapped on each virtual machine.
Operating system images are automatically skipped in the synchronization process as they are readily available on Azure and are not being used.
During the lab initialization the builtin variable $labSources will be automatically updated to point to your Azure lab sources location if you are deploying an Azure-based lab. There is no need to declare the variable in any script, as it is dynamically calculated to match the default virtualization engine.
To skip large files or entire ISOs for certain products like e.g. Exchange or Skype for Business the following parameters are available:
* SkipIsos: This switch parameter indicates that all ISO files should be skipped.
* MaxFileSizeInMb: This parameter takes an integer value indicating the maximum size of the files to synch.
Now you can simply use the other cmdlets provided by AutomatedLab to access files from the file share:
* `$postInstallActivity = Get-LabPostInstallationActivity -ScriptFileName PrepareRootDomain.ps1 -DependencyFolder $labSources\PostInstallationActivities\PrepareRootDomain`
* `Install-LabSoftwarePackage -ComputerName $machines -Path $labSources\SoftwarePackages\Notepad++.exe -CommandLine /S -AsJob` |
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file JSConsole.h
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
* Ethereum client.
*/
#pragma once
#include <libdevcore/Log.h>
#if ETH_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif
namespace dev
{
namespace eth
{
template<typename Engine, typename Printer>
class JSConsole
{
public:
JSConsole(): m_engine(Engine()), m_printer(Printer(m_engine)) {}
~JSConsole() {}
void readAndEval() const
{
std::string cmd = "";
g_logPost = [](std::string const& a, char const*)
{
std::cout << "\r \r" << a << std::endl << std::flush;
#if ETH_READLINE
rl_forced_update_display();
#endif
};
bool isEmpty = true;
int openBrackets = 0;
do {
std::string rl;
#if ETH_READLINE
char* buff = readline(promptForIndentionLevel(openBrackets).c_str());
if (buff)
{
rl = std::string(buff);
free(buff);
}
#else
std::cout << promptForIndentionLevel(openBrackets) << std::flush;
std::getline(std::cin, rl);
#endif
isEmpty = rl.empty();
//@todo this should eventually check the structure of the input, since unmatched
// brackets in strings will fail to execute the input now.
if (!isEmpty)
{
cmd += rl;
int open = 0;
for (char c: {'{', '[', '('})
open += std::count(cmd.begin(), cmd.end(), c);
int closed = 0;
for (char c: {'}', ']', ')'})
closed += std::count(cmd.begin(), cmd.end(), c);
openBrackets = open - closed;
}
} while (openBrackets > 0 && std::cin);
if (!isEmpty)
{
#if ETH_READLINE
add_history(cmd.c_str());
#endif
auto value = m_engine.eval(cmd.c_str());
std::string result = m_printer.prettyPrint(value).cstr();
std::cout << result << std::endl;
}
}
void eval(std::string const& _expression) { m_engine.eval(_expression.c_str()); }
protected:
Engine m_engine;
Printer m_printer;
virtual std::string promptForIndentionLevel(int _i) const
{
if (_i == 0)
return "> ";
return std::string((_i + 1) * 2, ' ');
}
};
}
}
|
// To check if a library is compiled with CocoaPods you
// can use the `COCOAPODS` macro definition which is
// defined in the xcconfigs so it is available in
// headers also when they are imported in the client
// project.
// LTHPasscodeViewController
#define COCOAPODS_POD_AVAILABLE_LTHPasscodeViewController
#define COCOAPODS_VERSION_MAJOR_LTHPasscodeViewController 3
#define COCOAPODS_VERSION_MINOR_LTHPasscodeViewController 1
#define COCOAPODS_VERSION_PATCH_LTHPasscodeViewController 4
|
/* shanti image gallery */
.og-grid {
list-style: none;
padding: 0;
margin: 0 auto;
text-align: center;
width: 100%;
}
.og-grid .item {
float: left;
margin: 0 5px 10px 0;
display: block;
}
.og-grid .item img {
max-width: 100%;
max-height: 100%;
vertical-align: bottom;
}
.og-grid .item > a,
.og-grid .item > a img {
border: none;
outline: none;
display: block;
position: relative;
}
.og-grid .item.last-row,
.og-grid .item.first-item {
clear: both;
}
/* remove margin bottom on last row */
.last-row,
.last-row ~ .item {
margin-bottom: 0;
}
.og-expander {
position: absolute !important;
border-bottom: 0.75rem double #eee;
background: #222;
top: auto;
left: 0;
z-index: 1;
width: 102%;
margin-left: -0.5rem;
margin-top: 1rem;
text-align: left;
overflow: hidden;
}
.og-expander-inner {
background: #303030;
background: transparent;
margin: 2rem 5.5rem;
height: 450px;
}
.og-close {
position: absolute;
width: 3rem;
height: 3rem;
top: 1.5rem;
right: 2rem;
color: #aaa;
cursor: pointer;
}
.og-close::before,
.og-close::after {
content: '';
position: absolute;
width: 100%;
top: 50%;
height: 1px;
background: #aaa;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
}
.og-close::after {
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
transform: rotate(-45deg);
}
.og-close:hover::before,
.og-close:hover::after {
background: #eee;
}
.og-fullimg,
.og-details {
float: left;
height: 100%;
/*position: relative;*/
}
.og-fullimg {
padding: 0 1rem;
margin: 0 1rem;
width: 50.0%;
text-align: center;
position: relative;
}
/* coordinate og-fullimg img, and img wrapper */
.og-img-wrapper {
/*position:relative;*/
padding-bottom: 81%;
overflow: hidden;
display: block;
}
.og-fullimg img {
display: inline-block;
max-height: 100%;
max-width: 100%;
position: absolute;
top: -50%;
bottom: -50%;
left: -50%;
right: -50%;
margin: auto;
width: auto;
height: auto;
vertical-align: middle;
}
.og-details {
padding: 0;
width: 44%;
float: left;
margin: 0;
margin: 0 0 0 1rem;
-webkit-transition: margin .3s ease-out;
transition: margin .3s ease-out;
}
.og-details .tab-content {
background: #1b1b1b;
border-bottom: 1px solid #555;
padding: 1rem 0 1rem 1rem;
}
.og-details .tab-pane {
padding: 1rem 0 0;
max-height: 450px;
min-height: 240px;
position: relative;
}
.row-offcanvas > section.content-section .og-details .tab-content:nth-of-type(1) {
padding-left: 2.5rem !important;
padding-right: 1rem !important;
padding-bottom: 0 !important;
}
.og-details a {
font-size: 1em;
color: #d6d6d6;
border: none;
outline: none;
margin: 0;
padding: 0;
}
.og-details #download a {
color: #ddd;
}
.og-details a:hover {
color: #f0f0f0;
border: none;
}
.og-details a::before {
margin: 0;
}
.og-expanded > a::after {
top: auto;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-width: 10px;
left: 50%;
margin: -8px 0 0 -10px;
border-bottom-color: #222;
}
/* gallery dropdown right metadata tabs */
.og-details .nav-tabs {
border-bottom: 1px solid #555;
margin-bottom: 0;
}
.og-details .nav-tabs > li {
margin-right: 0.2rem
}
.og-details .nav-tabs > li > a {
border: 1px solid #555;
border-color: #555 #555 #555 #555;
border-width: 2px 1px 1px;
border-radius: 0;
color: #999;
background: #222;
text-transform: uppercase;
font-size: 0.75em;
letter-spacing: 0.05rem;
font-weight: bold;
font-family: 'Helvetica Neue', helvetica, arial, sans-serif;
padding: 12px 10px;
}
.og-details .nav-tabs > li > a:hover,
.og-details .nav-tabs > li > a:active {
color: #eee;
border-color: #909090 #555 #555 #555;
border-width: 2px 1px 1px;
background: #222;
}
/*
.og-details .nav-tabs>li>a::before {
content: '';
display: none;
}
*/
.og-details .nav-tabs > li.active > a,
.og-details .nav-tabs > li.active > a:hover,
.og-details .nav-tabs > li.active > a:active {
color: #c0c0c0;
background: #1b1b1b;
border-width: 2px 1px 1px;
border-color: #909090 #555 transparent #555;
}
.og-details .nav-tabs > li:first-of-type {
margin-left: 0.75rem;
}
/*-------------------------*/
/*--- tab #info content ---*/
/*-------------------------*/
.og-details #info > ul,
.og-details #download > ul {
font-size: 0.93em;
margin-top: 1rem;
}
.og-details #info ul,
.og-details #download ul {
margin: 0 0 0 0.75rem;
padding: 0;
}
.og-details #info li,
.og-details #download li {
list-style-type: none;
color: #eee;
margin: 1rem 0 0;
padding: 0;
letter-spacing: 0.04rem;
}
.og-details #info li label,
.og-details #download li label {
color: #888;
font-size: 0.88em;
margin-left: -1rem;
margin-right: .5rem;
display: inline;
}
.og-details #desc p {
font-size: 0.93em;
line-height: 1.44em;
font-family: 'Helvetica Neue', helvetica, arial, sans-serif;
letter-spacing: 0.025rem;
color: #ddd;
max-height: 260px;
min-height: 150px;
overflow-y: auto;
padding-right: 2rem
}
.og-details h3 {
color: #fff;
font-size: 1.12em;
/*font-weight: bold !important;*/
line-height: 1.44em;
padding: 0;
margin: 0.5em 0;
}
/*----------------------------------------------*/
/**** gallery dropdown paging arrow buttons ****/
.og-nav-arrow {
position: absolute;
top: 50%;
width: 6rem;
height: 10rem;
border-radius: .3rem;
border: 1px solid #303030;
margin-top: -5rem;
background: #242424;
box-shadow: inset 0 0 10px #111;
display: inline-block;
}
.og-nav-arrow:hover {
background: #2e2e2e;
border-color: #444;
}
.og-nav-arrow:active {
border-color: #555;
background: #202020;
}
.og-nav-arrow.next {
position: absolute;
right: -1rem;
text-shadow: 0.2rem 0 0.5rem #111;
}
.og-nav-arrow.prev {
position: absolute;
left: -1rem;
text-shadow: 0 0.2rem 0.5rem #111;
}
.og-nav-arrow .icon {
font-size: 3.5rem;
width: 6rem;
height: 10rem;
position: relative;
top: 3rem;
background: transparent;
}
.og-nav-arrow .icon::before {
position: relative;
color: #444;
background: transparent;
}
.next.og-nav-arrow .icon::before {
content: '\e607';
right: -0.4rem;
}
.prev.og-nav-arrow .icon::before {
content: '\e606';
left: 1.4rem;
}
.og-nav-arrow:hover .icon::before {
color: #707070;
background: transparent !important;
}
.og-nav-arrow:active .icon::before {
color: #aaa;
background: transparent !important;
}
/*-----------------------------*/
/*--- BEGIN Lightbox button ---*/
.og-details .og-view-more {
height: 3.2rem;
width: 3.2rem;
/*line-height: 4.5rem;*/
color: #aaa;
background: #000;
border-radius: 50%;
border: 1px solid #777 !important;
background-clip: padding-box;
display: inline-block;
white-space: nowrap;
margin: 1rem 0 1rem 1.5rem;
text-indent: 2.45rem;
text-transform: uppercase;
}
.og-details .og-view-more:hover {
text-decoration: none;
border-color: #aaa !important;
color: #ddd;
}
.og-details .og-view-more:active {
background-color: #444;
border: 1px solid #777 !important;
border-bottom-color: #777 !important;
}
.og-details .og-view-more > span {
font-size: 1.44rem;
letter-spacing: 0.05rem;
color: #999;
position: relative;
bottom: 0.6rem;
right: 0;
line-height: 4.2rem;
text-transform: uppercase;
display: inline-block;
}
.og-details .og-view-more:hover > span,
.og-details .og-view-more:active > span {
color: #ddd;
}
.og-details .btn-lightbox > span {
text-indent: 0 !important;
font-family: 'FontAwesome';
}
.og-details .og-view-more.og-details-more {
position: absolute;
bottom: 0.2rem;
margin-left: 0.5rem;
}
.og-details .og-view-more.og-details-more > span {
text-indent: 0 !important;
font-family: 'shanticon';
}
.og-details .og-view-more span::before {
display: inline-block;
color: #aaa;
}
.og-details .og-view-more:hover span::before {
color: #ddd;
}
.og-details .og-view-more.btn-lightbox > span::before {
content: '\f065'; /* icon for full-screen */
font-family: 'FontAwesome';
font-size: 1.12em;
position: relative;
top: 0.03rem;
left: -1.65rem;
}
.og-details .og-view-more.og-details-more > span::before {
content: '\e61f'; /* unique icon for Read more... */
font-family: 'shanticon';
position: relative;
top: 0;
right: 1.6rem;
font-size: 1.4rem
}
.og-details .popover-kmaps,
.og-details .kmaps-images-popover {
background: #ddd;
border: none;
height: 1rem;
width: 1.2rem;
margin-left: 0.9rem;
}
.og-details .popover-kmaps-tip {
border-right-color: #ddd;
}
.og-details .kmaps-images-popover .icon {
color: #444;
}
.og-details #download a:hover {
color: #fff;
}
.og-details .shanticon-menu3:before {
color: #000;
}
/**
* Quick fixes for the image gallery implementation in kmaps
*/
.og-details .nav-tabs > li:first-of-type {
margin-left: inherit;
}
.og-details .nav-tabs > li {
margin-right: inherit;
}
/* details button */
.og-details button.copyurl {
float: right;
box-shadow: none;
background: #333;
color: #999;
}
.og-details button.copyurl:hover {
color: #ddd;
background: #555;
}
.og-details .fa-clipboard:before {
font-size: 1.5em;
margin-right: .5rem;
}
.og-loading {
width: 20px;
height: 20px;
border-radius: 50%;
background: #ddd;
box-shadow: 0 0 1px #ccc, 15px 30px 1px #ccc, -15px 30px 1px #ccc;
position: absolute;
top: 50%;
left: 50%;
margin: -25px 0 0 -25px;
-webkit-animation: loader 0.5s infinite ease-in-out both;
-moz-animation: loader 0.5s infinite ease-in-out both;
animation: loader 0.5s infinite ease-in-out both;
}
@-webkit-keyframes loader {
0% {
background: #ddd;
}
33% {
background: #ccc;
box-shadow: 0 0 1px #ccc, 15px 30px 1px #ccc, -15px 30px 1px #ddd;
}
66% {
background: #ccc;
box-shadow: 0 0 1px #ccc, 15px 30px 1px #ddd, -15px 30px 1px #ccc;
}
}
@-moz-keyframes loader {
0% {
background: #ddd;
}
33% {
background: #ccc;
box-shadow: 0 0 1px #ccc, 15px 30px 1px #ccc, -15px 30px 1px #ddd;
}
66% {
background: #ccc;
box-shadow: 0 0 1px #ccc, 15px 30px 1px #ddd, -15px 30px 1px #ccc;
}
}
@keyframes loader {
0% {
background: #ddd;
}
33% {
background: #ccc;
box-shadow: 0 0 1px #ccc, 15px 30px 1px #ccc, -15px 30px 1px #ddd;
}
66% {
background: #ccc;
box-shadow: 0 0 1px #ccc, 15px 30px 1px #ddd, -15px 30px 1px #ccc;
}
}
@media screen and (max-width: 830px) {
.og-expander h3 {
font-size: 18px;
}
.og-expander p {
font-size: 13px;
}
.og-expander a {
font-size: 12px;
}
}
@media screen and (max-width: 650px) {
.og-fullimg {
display: none;
}
.og-details {
float: none;
width: 100%;
}
}
/* lightbox */
.pswp {
z-index: 1000;
}
.pswp__button {
margin-right: 1.5rem;
}
.pswp__caption__center {
text-align: center;
font-family: 'museo-sans-500', helvetica, arial, sans-serif;
}
.pswp__bg {
filter: alpha(opacity=100);
opacity: 1;
background: #222 !important;
}
.pswp__ui--fit .pswp__top-bar,
.pswp__ui--fit .pswp__caption {
background: transparent;
}
.pswp__share-tooltip a {
border: none;
}
.pswp__share-tooltip a:hover,
.pswp__share-tooltip a:active {
color: #fff !important;
}
.pswp__share-tooltip a:hover:nth-child(n+3),
.pswp__share-tooltip a:active:nth-child(n+3) {
color: #333 !important;
}
/**** lightbox
.pswp__counter{
display:none;
}
.pswp__top-bar{
position: absolute;
right: 0;
top: 0;
height: 100%;
width: 44px;
}
****/
/*
.container:before,
.container:after {
content: "";
display: table;
}
.container:after {
clear: both;
}
.clearfix {
zoom: 1;
}
.clearfix:before, .clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
*/
.og-grid .img-footer-overlay {
background-color: #222;
font-size: 0.88em;
font-family: 'Helvetica Neue',helvetica,arial,sans-serif;
position: absolute;
bottom: 0;
padding: .25rem .5rem;
color: white;
opacity: 1;
width: 100%;
}
/*-------------------------*/
/*=== max-width (first) ===*/
/*-------------------------*/
@media screen and (max-width: 991px) {
.og-fullimg {
width: 51%;
}
.og-nav-arrow.next {
position: absolute;
right: 0;
}
.og-nav-arrow.prev {
position: absolute;
left: 0;
}
}
@media screen and (max-width: 767px) {
.og-fullimg,
.og-details {
display: block;
width: 97%;
border: none;
}
.og-details {
padding-right: 0.6rem;
padding-top: 2.5rem;
/*padding-left: 1rem;*/
margin-top: 0;
/*width:100%;*/
height: auto;
}
.og-expander-inner {
overflow-x: auto;
padding-bottom: 5rem;
padding-top: 4.5rem;
}
.og-img-wrapper {
position: relative;
right: 0.5rem;
padding-bottom: 0;
overflow: hidden;
display: block;
}
.og-fullimg {
height: auto;
margin-bottom: 2rem
/*width:100%;*/
/*padding-left:0;*/
}
.og-fullimg img {
position: static;
top: auto;
right: auto;
left: auto;
bottom: auto;
margin: 0 auto 1.5rem;
}
.og-details h3 {
font-size: 1.5em;
margin: 1rem 0.5rem 1.25rem;
}
}
@media screen and (max-width: 750px) {
.og-fullimg {
padding: 0;
}
}
@media screen and (max-width: 600px) {
.og-fullimg,
.og-details {
width: 96%;
}
.og-details h3 {
font-size: 1.12em;
}
}
/*--------------------------*/
/*======== min-width =======*/
/*--------------------------*/
@media screen and (min-width: 600px) {
.og-details .nav-tabs > li > a {
letter-spacing: 0.12rem;
padding: 12px 15px;
}
}
@media screen and (min-width: 992px) {
.og-details {
padding: 0.3em 0 0 1rem;
}
}
|
/**
* Copyright (c) 2019 Kylart <kylart.dev@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
#ifndef BINDINGS_NAME_PARSER_SRC_PARSE_H_
#define BINDINGS_NAME_PARSER_SRC_PARSE_H_
#include <napi.h>
#include <anitomy/anitomy.h>
#include <locale>
#include <codecvt>
#include <string>
#include "wrapper.h"
namespace Parser {
Napi::Value parse(const Napi::CallbackInfo& info);
} // namespace Parser
#endif // BINDINGS_NAME_PARSER_SRC_PARSE_H_
|
// Copyright (c) 2012-2018 The DigiByte Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DIGIBYTE_BLOOM_H
#define DIGIBYTE_BLOOM_H
#include <serialize.h>
#include <vector>
class COutPoint;
class CTransaction;
class uint256;
//! 20,000 items with fp rate < 0.1% or 10,000 items and <0.0001%
static const unsigned int MAX_BLOOM_FILTER_SIZE = 36000; // bytes
static const unsigned int MAX_HASH_FUNCS = 50;
/**
* First two bits of nFlags control how much IsRelevantAndUpdate actually updates
* The remaining bits are reserved
*/
enum bloomflags
{
BLOOM_UPDATE_NONE = 0,
BLOOM_UPDATE_ALL = 1,
// Only adds outpoints to the filter if the output is a pay-to-pubkey/pay-to-multisig script
BLOOM_UPDATE_P2PUBKEY_ONLY = 2,
BLOOM_UPDATE_MASK = 3,
};
/**
* BloomFilter is a probabilistic filter which SPV clients provide
* so that we can filter the transactions we send them.
*
* This allows for significantly more efficient transaction and block downloads.
*
* Because bloom filters are probabilistic, a SPV node can increase the false-
* positive rate, making us send it transactions which aren't actually its,
* allowing clients to trade more bandwidth for more privacy by obfuscating which
* keys are controlled by them.
*/
class CBloomFilter
{
private:
std::vector<unsigned char> vData;
bool isFull;
bool isEmpty;
unsigned int nHashFuncs;
unsigned int nTweak;
unsigned char nFlags;
unsigned int Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const;
// Private constructor for CRollingBloomFilter, no restrictions on size
CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweak);
friend class CRollingBloomFilter;
public:
/**
* Creates a new bloom filter which will provide the given fp rate when filled with the given number of elements
* Note that if the given parameters will result in a filter outside the bounds of the protocol limits,
* the filter created will be as close to the given parameters as possible within the protocol limits.
* This will apply if nFPRate is very low or nElements is unreasonably high.
* nTweak is a constant which is added to the seed value passed to the hash function
* It should generally always be a random value (and is largely only exposed for unit testing)
* nFlags should be one of the BLOOM_UPDATE_* enums (not _MASK)
*/
CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweak, unsigned char nFlagsIn);
CBloomFilter() : isFull(true), isEmpty(false), nHashFuncs(0), nTweak(0), nFlags(0) {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(vData);
READWRITE(nHashFuncs);
READWRITE(nTweak);
READWRITE(nFlags);
}
void insert(const std::vector<unsigned char>& vKey);
void insert(const COutPoint& outpoint);
void insert(const uint256& hash);
bool contains(const std::vector<unsigned char>& vKey) const;
bool contains(const COutPoint& outpoint) const;
bool contains(const uint256& hash) const;
void clear();
void reset(const unsigned int nNewTweak);
//! True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS
//! (catch a filter which was just deserialized which was too big)
bool IsWithinSizeConstraints() const;
//! Also adds any outputs which match the filter to the filter (to match their spending txes)
bool IsRelevantAndUpdate(const CTransaction& tx);
//! Checks for empty and full filters to avoid wasting cpu
void UpdateEmptyFull();
};
/**
* RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
* Construct it with the number of items to keep track of, and a false-positive
* rate. Unlike CBloomFilter, by default nTweak is set to a cryptographically
* secure random value for you. Similarly rather than clear() the method
* reset() is provided, which also changes nTweak to decrease the impact of
* false-positives.
*
* contains(item) will always return true if item was one of the last N to 1.5*N
* insert()'ed ... but may also return true for items that were not inserted.
*
* It needs around 1.8 bytes per element per factor 0.1 of false positive rate.
* (More accurately: 3/(log(256)*log(2)) * log(1/fpRate) * nElements bytes)
*/
class CRollingBloomFilter
{
public:
// A random bloom filter calls GetRand() at creation time.
// Don't create global CRollingBloomFilter objects, as they may be
// constructed before the randomizer is properly initialized.
CRollingBloomFilter(const unsigned int nElements, const double nFPRate);
void insert(const std::vector<unsigned char>& vKey);
void insert(const uint256& hash);
bool contains(const std::vector<unsigned char>& vKey) const;
bool contains(const uint256& hash) const;
void reset();
private:
int nEntriesPerGeneration;
int nEntriesThisGeneration;
int nGeneration;
std::vector<uint64_t> data;
unsigned int nTweak;
int nHashFuncs;
};
#endif // DIGIBYTE_BLOOM_H
|
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "UIView.h"
@class MPImageCache, MPImageCacheRequest, MPTimeMarker, UIImage;
@interface MPVideoChapterCellContentView : UIView
{
unsigned int _current:1;
unsigned long long _index;
unsigned int _selected:1;
unsigned int _showThumbnailColumn:1;
double _timeColumnWidth;
MPTimeMarker *_timeMarker;
UIImage *_artwork;
MPImageCache *_artworkImageCache;
MPImageCacheRequest *_artworkImageRequest;
}
@property(retain, nonatomic) MPImageCache *artworkImageCache; // @synthesize artworkImageCache=_artworkImageCache;
@property(retain, nonatomic) UIImage *artwork; // @synthesize artwork=_artwork;
@property(retain, nonatomic) MPTimeMarker *timeMarker; // @synthesize timeMarker=_timeMarker;
@property(nonatomic) double timeColumnWidth; // @synthesize timeColumnWidth=_timeColumnWidth;
@property(nonatomic) unsigned long long index; // @synthesize index=_index;
- (void).cxx_destruct;
- (void)setArtworkImageRequest:(id)arg1 artworkLoadCompletionHandler:(id)arg2;
@property(nonatomic) _Bool showThumbnailColumn;
@property(nonatomic, getter=isSelected) _Bool selected;
@property(nonatomic, getter=isCurrent) _Bool current;
- (void)drawRect:(struct CGRect)arg1;
- (void)dealloc;
@end
|
---
layout: speaker
order: 13
title: How can Javascript improve your CSS mixins
image: /assets/speakers/sandrina.jpg
name: Sandrina Pereira
twitter: a_sandrina_p
github: sandrina-p
from: Porto, Portugal
decor: 1
social_card:
twitter_card_type: summary_large_image
description: Session by Sandrina Pereira
image: /assets/social-cards/speaker-sandrina.jpg
---
<div class="speaker-youtube">
<iframe src="https://www.youtube.com/embed/UUl0BZgjm3o?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
Open a new window of possibilities to CSS: Faster compilation time, advanced logic, better styles scalability with Unit Testing and more.
How can we use Javascript in order expand the potential of CSS? Why not bring Unit Testing to the table? PostCSS exposes a new world of possibilities for CSS with Javascript. Let's have a faster compilation time, a prettier and more advanced logic than `@if | @for`, access to values outside of the CSS files, and much more! Let's put your CSS to the test! |
// (C) Copyright John Maddock 2000.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "test.hpp"
#include "check_integral_constant.hpp"
#ifdef TEST_STD
# include <type_traits>
#else
# include <boost/type_traits/has_nothrow_copy.hpp>
#endif
struct non_copy
{
non_copy();
private:
non_copy(const non_copy&);
};
#ifndef BOOST_NO_CXX11_DELETED_FUNCTIONS
struct delete_copy
{
delete_copy();
delete_copy(const delete_copy&) = delete;
};
#endif
#ifndef BOOST_NO_CXX11_NOEXCEPT
struct noexcept_copy
{
noexcept_copy();
noexcept_copy& operator=(const noexcept_copy&)noexcept;
};
#endif
TT_TEST_BEGIN(has_nothrow_copy)
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<bool>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<bool const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<bool volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<bool const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<signed char>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<signed char const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<signed char volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<signed char const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned char>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<char>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned char const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<char const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned char volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<char volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned char const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<char const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned short>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<short>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned short const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<short const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned short volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<short volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned short const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<short const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned int>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned int const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned int volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned int const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned long>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<long>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned long const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<long const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned long volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<long volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned long const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<long const volatile>::value, false);
#endif
#ifdef BOOST_HAS_LONG_LONG
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy< ::boost::ulong_long_type>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy< ::boost::long_long_type>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy< ::boost::ulong_long_type const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy< ::boost::long_long_type const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy< ::boost::ulong_long_type volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy< ::boost::long_long_type volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy< ::boost::ulong_long_type const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy< ::boost::long_long_type const volatile>::value, false);
#endif
#endif
#ifdef BOOST_HAS_MS_INT64
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int8>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int8>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int8 const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int8 const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int8 volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int8 volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int8 const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int8 const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int16>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int16>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int16 const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int16 const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int16 volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int16 volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int16 const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int16 const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int32>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int32>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int32 const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int32 const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int32 volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int32 volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int32 const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int32 const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int64>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int64>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int64 const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int64 const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int64 volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int64 volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<unsigned __int64 const volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<__int64 const volatile>::value, false);
#endif
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<float>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<float const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<float volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<float const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<double>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<double const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<double volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<double const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<long double>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<long double const>::value, true);
#ifndef TEST_STD
// unspecified behaviour:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<long double volatile>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<long double const volatile>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<void*>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int*const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<f1>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<f2>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<f3>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<mf1>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<mf2>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<mf3>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<mp>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<cmf>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<enum_UDT>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int&>::value, false);
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int&&>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<const int&>::value, false);
// These used to be true, but are now false to match std conforming behavior:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int[2]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int[3][2]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<int[2][4][5][6][3]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<UDT>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<void>::value, false);
// cases we would like to succeed but can't implement in the language:
BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<empty_POD_UDT>::value, true, false);
BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<POD_UDT>::value, true, false);
BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<POD_union_UDT>::value, true, false);
BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<empty_POD_union_UDT>::value, true, false);
BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<nothrow_copy_UDT>::value, true, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<nothrow_assign_UDT>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<nothrow_construct_UDT>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<test_abc1>::value, false);
#ifndef BOOST_NO_CXX11_DELETED_FUNCTIONS
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<delete_copy>::value, false);
#endif
#ifndef BOOST_NO_CXX11_NOEXCEPT
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<noexcept_copy>::value, true);
#endif
#if !defined(BOOST_NO_CXX11_DECLTYPE) && !BOOST_WORKAROUND(BOOST_MSVC, < 1800)
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_nothrow_copy<non_copy>::value, false);
#endif
TT_TEST_END
|
<div class="modal-content">
<div class="modal-header">
<b>Results</b>
</div>
<div class="modal-body">
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Category</th>
<th>Tags</th>
<th>Likes</th>
<th>Dislikes</th>
<th>Date created</th>
<th>Author</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="idea in response track by $index">
<td class="col-md-1">{{idea.title}}</td>
<td class="col-md-2">{{idea.description}}</td>
<td class="col-md-1">{{idea.category}}</td>
<td class="col-md-2"><div class="tag category blue pull-left" ng-repeat="tag in idea.tags track by $index">{{tag}}</div></td>
<td class="col-md-1">{{idea.rating.likes}}</td>
<td class="col-md-1">{{idea.rating.dislikes}}</td>
<td class="col-md-1">{{idea.parsedDate}}</td>
<td class="col-md-1">{{idea.author.name}}</td>
</tr>
</tbody>
</table>
</div>
</div> |
<hr />
<label>
Id: <span class="idLabel"></span>
<a class="theadLink">Open</a>
</label>
<label>
Name: <span class="nameLabel"></span>
</label>
<label>
Date: <span class="dateLabel"></span>
</label> |
<html ng-app="myDemo4">
<head>
<script src="../../bower_components/angular/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MyCtrl">
Technologies :
<ul><li ng-repeat="techno in technos">{{techno}}</li></ul>
Technologies Java* :
<ul><li ng-repeat="techno in technos | filter:'Java'">{{techno}}</li></ul>
</body>
</html> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main()
{
int cakesWanted = int.Parse(Console.ReadLine());
double flourNeededFor1Cake = double.Parse(Console.ReadLine());
double flourAvailable = double.Parse(Console.ReadLine());
double truffelAvailable = double.Parse(Console.ReadLine());
double priceForTruffel = double.Parse(Console.ReadLine());
double cakes = Math.Floor(flourAvailable / flourNeededFor1Cake);
double totalTruffelPrice = truffelAvailable * priceForTruffel;
double cakePrice = (totalTruffelPrice / cakesWanted) * 1.25;
if (cakes < cakesWanted)
{
Console.WriteLine("Can make only {0} cakes, need {1:f2} kg more flour", cakes, cakesWanted * flourNeededFor1Cake - flourAvailable);
}
else if (cakes > cakesWanted)
{
Console.WriteLine("All products available, price of a cake: {0:f2}", cakePrice);
}
}
}
|
package com.microsoft.bingads.v12.api.test.entities.criterions.adgroup.profile;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import com.microsoft.bingads.v12.api.test.entities.criterions.adgroup.profile.write.*;
@RunWith(Suite.class)
@Suite.SuiteClasses({
BulkAdGroupCompanyNameCriterionWriteProfileIdTest.class,
BulkAdGroupCompanyNameCriterionWriteProfileTest.class,
BulkAdGroupIndustryCriterionWriteProfileIdTest.class,
BulkAdGroupIndustryCriterionWriteProfileTest.class,
BulkAdGroupJobFunctionCriterionWriteProfileIdTest.class,
BulkAdGroupJobFunctionCriterionWriteProfileTest.class,
})
public class BulkAdGroupProfileCriterionWriteTests {
}
|
---
title: "Plugins"
description: "Reference documentation for Sensu Plugins."
product: "Sensu Core"
version: "1.3"
weight: 9
menu:
sensu-core-1.3:
parent: reference
---
## What is a Sensu plugin?
Sensu plugins provide executable scripts or other programs that can be used as
[Sensu checks][1] (i.e. to monitor server resources, services, and application
health, or collect & analyze metrics), [Sensu handlers][2] (i.e. to send
notifications or perform other actions based on [Sensu events][3]), or [Sensu
mutators][3] (i.e. to modify [event data][4] prior to handling).
For more about Sensu plugins, please refer to the [Plugins reference documentation][5].
[1]: ../checks
[2]: ../handlers
[3]: ../events#event-data
[4]: ../mutators
[5]: ../../../../plugins/latest/reference
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" name="viewport" />
<script>
var Module = {};
var __cargo_web = {};
Object.defineProperty( Module, 'canvas', {
get: function() {
if( __cargo_web.canvas ) {
return __cargo_web.canvas;
}
var canvas = document.createElement( 'canvas' );
document.querySelector( 'body' ).appendChild( canvas );
__cargo_web.canvas = canvas;
return canvas;
}
});
</script>
</head>
<body>
<script src="rummikub-solver.js"></script>
</body>
</html> |
#include "hash.h"
#include "list.h"
extern void *hash_init(hash_table *h, size_t elem_size,
hash_fn_t hash_fn, comp_fn_t comp,
unsigned long table_size) {
array *a;
if ((a = malloc(sizeof(array))) == NULL)
return NULL;
h->a = a;
h->table_size = table_size;
h->tsize = elem_size;
h->hash_fn = hash_fn;
h->comp = comp;
array_init(a, sizeof(list*), NULL);
/* Initialize the hash table with NULL pointers */
list *init_val = NULL;
array_expand_fill(a, table_size, &init_val);
return NULL;
}
void *hash_search(hash_table *h, void *elem_addr) {
array *a = h->a;
size_t size = a->size;
hash_fn_t hash_fn = h->hash_fn;
unsigned long hash_res = hash_fn(elem_addr);
unsigned long index = hash_res % h->table_size;
list *l;
if (index >= size)
return NULL; /* Not found. */
/* The array_value returns a pointer to my stored data, and what I'm
storing is a pointer (to a list). This is the reason for casting. */
l = *(list**)array_value(a, index);
return list_search(l, elem_addr);
}
void *hash_insert(hash_table *h, void *elem_addr) {
array *a = h->a;
hash_fn_t hash_fn = h->hash_fn;
unsigned long hash_res = hash_fn(elem_addr);
unsigned long index = hash_res % h->table_size;
list *l;
/* Resolve collision if needed, create new list otherwise. */
l = *(list**)array_value(a, index);
if (l == NULL) { /* No collision - create new slot. */
if ((l = malloc(sizeof(list))) == NULL)
return NULL;
list_init(l, h->tsize, h->comp);
/* The array stores a pointer to my data, and what I'm storing
is a pointer (to a list). This is the reason for passing the
list pointer address and not the list pointer itself. */
array_add_at_index(a, &l, index);
}
list_add(l, elem_addr);
return elem_addr;
}
void hash_destroy(hash_table *h) {
array *a = h->a;
unsigned long table_size = h->table_size;
list *l;
for (int i = 0; i < table_size; i++) {
l = *(list**)array_value(a, i);
if (l != NULL) {
list_destroy(l);
free (l);
}
}
free(a);
}
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Compute::Mgmt::V2019_12_01
module Models
#
# Api request input for LogAnalytics getRequestRateByInterval Api.
#
class RequestRateByIntervalInput < LogAnalyticsInputBase
include MsRestAzure
# @return [IntervalInMins] Interval value in minutes used to create
# LogAnalytics call rate logs. Possible values include: 'ThreeMins',
# 'FiveMins', 'ThirtyMins', 'SixtyMins'
attr_accessor :interval_length
#
# Mapper for RequestRateByIntervalInput class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RequestRateByIntervalInput',
type: {
name: 'Composite',
class_name: 'RequestRateByIntervalInput',
model_properties: {
blob_container_sas_uri: {
client_side_validation: true,
required: true,
serialized_name: 'blobContainerSasUri',
type: {
name: 'String'
}
},
from_time: {
client_side_validation: true,
required: true,
serialized_name: 'fromTime',
type: {
name: 'DateTime'
}
},
to_time: {
client_side_validation: true,
required: true,
serialized_name: 'toTime',
type: {
name: 'DateTime'
}
},
group_by_throttle_policy: {
client_side_validation: true,
required: false,
serialized_name: 'groupByThrottlePolicy',
type: {
name: 'Boolean'
}
},
group_by_operation_name: {
client_side_validation: true,
required: false,
serialized_name: 'groupByOperationName',
type: {
name: 'Boolean'
}
},
group_by_resource_name: {
client_side_validation: true,
required: false,
serialized_name: 'groupByResourceName',
type: {
name: 'Boolean'
}
},
interval_length: {
client_side_validation: true,
required: true,
serialized_name: 'intervalLength',
type: {
name: 'Enum',
module: 'IntervalInMins'
}
}
}
}
}
end
end
end
end
|
var smidig = smidig || {};
smidig.voter = (function($) {
var talk_id, $form, $notice, $loader;
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function save_vote($form, talk_id) {
var votes = JSON.parse(localStorage.getItem("votes")) || {};
votes[talk_id] = true;
localStorage.setItem("votes", JSON.stringify(votes));
finished($form);
}
function bind($form, talk_id) {
$form.find("input[name='commit']").click(function() {
var data = $form.serializeObject();
if(!data["feedback_vote[vote]"]) {
alert("Du må gi minst 1 stjerne!");
return;
}
$form.find(".inputs").hide();
$form.find(".ajaxloader").show();
$form.find(".ajaxloader").css("visibility", "visible")
$.ajax({
type: "POST",
url: $form.attr("action"),
dataType: 'json',
data: data,
complete: function(xhr) {
if (xhr.readyState == 4) {
if (xhr.status == 201) {
smidig.voter.save_vote($form, talk_id);
}
} else {
alert("Det skjedde noe galt ved lagring. Prøv igjen");
$form.find(".ajaxloader").hide();
$form.find(".inputs").show();
}
}
});
//cancel submit event..
return false;
});
}
function init($form, talk_id) {
if(!supports_html5_storage()) {
$notice.text("Din enhet støttes ikke");
finished($form);
}
var votes = JSON.parse(localStorage.getItem("votes")) || {};
if(votes[talk_id]) {
finished($form);
} else {
bind($form, talk_id);
}
}
function finished($form) {
$form.empty();
$form.append("<em>(Du har stemt)</em>");
$form.show();
}
return {
init: init,
save_vote: save_vote
};
})(jQuery);
//Document on load!
$(function() {
$(".talk").each(function() {
var talk_id = $(this).data("talkid");
if(talk_id) {
var voteTmpl = $("#tmplVote").tmpl({talk_id: talk_id});
voteTmpl.find("input.star").rating();
$(this).find(".description").append(voteTmpl);
smidig.voter.init(voteTmpl, talk_id);
}
});
});
//Extensions to serialize a form to a js-object.
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
}; |
import express from 'express';
import LessonController from '../controllers/LessonController';
const router = express.Router();
/* eslint-disable no-unused-vars */
const LessonsPath = '/api/lessonplans';
const teacherName = 'yonderWay';
const subjectName = 'theatre1';
const lessonNumber = '/:id';
// the data access should look something like this:
// '/api/teachers/{name}/{class}/{lesson#}'
router.post(LessonsPath, LessonController.create);
router.get(LessonsPath, LessonController.list);
router.get(LessonsPath + '/:id', LessonController.listOne);
router.put(LessonsPath + '/:id', LessonController.update);
router.delete(LessonsPath + '/:id', LessonController.delete);
export default router;
|
export { default, email } from '@abcum/ember-helpers/helpers/email';
|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ansible.compat.six.Module_six_moves_urllib_response</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="ansible-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>ansible</th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="ansible-module.html">Package ansible</a> ::
<a href="ansible.compat-module.html">Package compat</a> ::
<a href="ansible.compat.six-module.html">Package six</a> ::
Class Module_six_moves_urllib_response
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="ansible.compat.six.Module_six_moves_urllib_response-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class Module_six_moves_urllib_response</h1><p class="nomargin-top"><span class="codelink"><a href="ansible.compat.six-pysrc.html#Module_six_moves_urllib_response">source code</a></span></p>
<pre class="base-tree">
object --+
|
??.module-1 --+
|
<a href="ansible.compat.six._LazyModule-class.html" onclick="show_private();">_LazyModule</a> --+
|
<strong class="uidshort">Module_six_moves_urllib_response</strong>
</pre>
<hr />
<p>Lazy loading of moved objects in six.moves.urllib_response</p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="ansible.compat.six._LazyModule-class.html" onclick="show_private();">_LazyModule</a></code></b>:
<code><a href="ansible.compat.six._LazyModule-class.html#__dir__">__dir__</a></code>,
<code><a href="ansible.compat.six._LazyModule-class.html#__init__">__init__</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code><i>unreachable</i>.module</code></b>:
<code>__delattr__</code>,
<code>__getattribute__</code>,
<code>__new__</code>,
<code>__repr__</code>,
<code>__setattr__</code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__format__</code>,
<code>__hash__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__sizeof__</code>,
<code>__str__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== CLASS VARIABLES ==================== -->
<a name="section-ClassVariables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Class Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-ClassVariables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr class="private">
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="ansible.compat.six.Module_six_moves_urllib_response-class.html#_moved_attributes" class="summary-name" onclick="show_private();">_moved_attributes</a> = <code title="[<ansible.compat.six.MovedAttribute object at 0x7f2ca68319d0>,
<ansible.compat.six.MovedAttribute object at 0x7f2ca6831a10>,
<ansible.compat.six.MovedAttribute object at 0x7f2ca6831a50>,
<ansible.compat.six.MovedAttribute object at 0x7f2ca6831a90>]"><code class="variable-group">[</code><ansible.compat.six.MovedAttribute object<code class="variable-ellipsis">...</code></code>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== CLASS VARIABLE DETAILS ==================== -->
<a name="section-ClassVariableDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Class Variable Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-ClassVariableDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="_moved_attributes"></a>
<div class="private">
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">_moved_attributes</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
<code class="variable-group">[</code><ansible.compat.six.MovedAttribute object at 0x7f2ca68319d0><code class="variable-op">,</code>
<ansible.compat.six.MovedAttribute object at 0x7f2ca6831a10><code class="variable-op">,</code>
<ansible.compat.six.MovedAttribute object at 0x7f2ca6831a50><code class="variable-op">,</code>
<ansible.compat.six.MovedAttribute object at 0x7f2ca6831a90><code class="variable-group">]</code>
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="ansible-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>ansible</th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Fri Jul 29 13:11:38 2016
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Diagnostics;
using ContentType = OfficeDevPnP.Core.Framework.Provisioning.Model.ContentType;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Extensions;
using OfficeDevPnP.Core.Framework.Provisioning.Connectors;
using System.IO;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions;
namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers
{
internal class ObjectContentType : ObjectHandlerBase
{
public override string Name
{
get { return "Content Types"; }
}
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
// if this is a sub site then we're not provisioning content types. Technically this can be done but it's not a recommended practice
if (web.IsSubSite())
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Context_web_is_subweb__Skipping_content_types_);
return parser;
}
web.Context.Load(web.ContentTypes, ct => ct.IncludeWithDefaultProperties(c => c.StringId, c => c.FieldLinks,
c => c.FieldLinks.Include(fl => fl.Id, fl => fl.Required, fl => fl.Hidden)));
web.Context.Load(web.Fields, fld => fld.IncludeWithDefaultProperties(f => f.Id));
web.Context.ExecuteQueryRetry();
var existingCTs = web.ContentTypes.ToList();
var existingFields = web.Fields.ToList();
foreach (var ct in template.ContentTypes.OrderBy(ct => ct.Id)) // ordering to handle references to parent content types that can be in the same template
{
var existingCT = existingCTs.FirstOrDefault(c => c.StringId.Equals(ct.Id, StringComparison.OrdinalIgnoreCase));
if (existingCT == null)
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Creating_new_Content_Type___0_____1_, ct.Id, ct.Name);
var newCT = CreateContentType(web, ct, parser, template.Connector ?? null, existingCTs, existingFields);
if (newCT != null)
{
existingCTs.Add(newCT);
}
}
else
{
if (ct.Overwrite)
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Recreating_existing_Content_Type___0_____1_, ct.Id, ct.Name);
existingCT.DeleteObject();
web.Context.ExecuteQueryRetry();
var newCT = CreateContentType(web, ct, parser, template.Connector ?? null, existingCTs, existingFields);
if (newCT != null)
{
existingCTs.Add(newCT);
}
}
else
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Updating_existing_Content_Type___0_____1_, ct.Id, ct.Name);
UpdateContentType(web, existingCT, ct, parser, scope);
}
}
}
}
return parser;
}
private static void UpdateContentType(Web web, Microsoft.SharePoint.Client.ContentType existingContentType, ContentType templateContentType, TokenParser parser, PnPMonitoredScope scope)
{
var isDirty = false;
if (existingContentType.Hidden != templateContentType.Hidden)
{
scope.LogPropertyUpdate("Hidden");
existingContentType.Hidden = templateContentType.Hidden;
isDirty = true;
}
if (existingContentType.ReadOnly != templateContentType.ReadOnly)
{
scope.LogPropertyUpdate("ReadOnly");
existingContentType.ReadOnly = templateContentType.ReadOnly;
isDirty = true;
}
if (existingContentType.Sealed != templateContentType.Sealed)
{
scope.LogPropertyUpdate("Sealed");
existingContentType.Sealed = templateContentType.Sealed;
isDirty = true;
}
if (templateContentType.Description != null && existingContentType.Description != parser.ParseString(templateContentType.Description))
{
scope.LogPropertyUpdate("Description");
existingContentType.Description = parser.ParseString(templateContentType.Description);
isDirty = true;
}
if (templateContentType.DocumentTemplate != null && existingContentType.DocumentTemplate != parser.ParseString(templateContentType.DocumentTemplate))
{
scope.LogPropertyUpdate("DocumentTemplate");
existingContentType.DocumentTemplate = parser.ParseString(templateContentType.DocumentTemplate);
isDirty = true;
}
if (existingContentType.Name != parser.ParseString(templateContentType.Name))
{
scope.LogPropertyUpdate("Name");
existingContentType.Name = parser.ParseString(templateContentType.Name);
isDirty = true;
// CT is being renamed, add an extra token to the tokenparser
parser.AddToken(new ContentTypeIdToken(web, existingContentType.Name, existingContentType.StringId));
}
if (templateContentType.Group != null && existingContentType.Group != parser.ParseString(templateContentType.Group))
{
scope.LogPropertyUpdate("Group");
existingContentType.Group = parser.ParseString(templateContentType.Group);
isDirty = true;
}
if (templateContentType.DisplayFormUrl != null && existingContentType.DisplayFormUrl != parser.ParseString(templateContentType.DisplayFormUrl))
{
scope.LogPropertyUpdate("DisplayFormUrl");
existingContentType.DisplayFormUrl = parser.ParseString(templateContentType.DisplayFormUrl);
isDirty = true;
}
if (templateContentType.EditFormUrl != null && existingContentType.EditFormUrl != parser.ParseString(templateContentType.EditFormUrl))
{
scope.LogPropertyUpdate("EditFormUrl");
existingContentType.EditFormUrl = parser.ParseString(templateContentType.EditFormUrl);
isDirty = true;
}
if (templateContentType.NewFormUrl != null && existingContentType.NewFormUrl != parser.ParseString(templateContentType.NewFormUrl))
{
scope.LogPropertyUpdate("NewFormUrl");
existingContentType.NewFormUrl = parser.ParseString(templateContentType.NewFormUrl);
isDirty = true;
}
#if !ONPREMISES
if (templateContentType.Name.ContainsResourceToken())
{
existingContentType.NameResource.SetUserResourceValue(templateContentType.Name, parser);
isDirty = true;
}
if (templateContentType.Description.ContainsResourceToken())
{
existingContentType.DescriptionResource.SetUserResourceValue(templateContentType.Description, parser);
isDirty = true;
}
#endif
if (isDirty)
{
existingContentType.Update(true);
web.Context.ExecuteQueryRetry();
}
// Delta handling
existingContentType.EnsureProperty(c => c.FieldLinks);
List<Guid> targetIds = existingContentType.FieldLinks.AsEnumerable().Select(c1 => c1.Id).ToList();
List<Guid> sourceIds = templateContentType.FieldRefs.Select(c1 => c1.Id).ToList();
var fieldsNotPresentInTarget = sourceIds.Except(targetIds).ToArray();
if (fieldsNotPresentInTarget.Any())
{
foreach (var fieldId in fieldsNotPresentInTarget)
{
var fieldRef = templateContentType.FieldRefs.Find(fr => fr.Id == fieldId);
var field = web.Fields.GetById(fieldId);
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Adding_field__0__to_content_type, fieldId);
web.AddFieldToContentType(existingContentType, field, fieldRef.Required, fieldRef.Hidden);
}
}
isDirty = false;
foreach (var fieldId in targetIds.Intersect(sourceIds))
{
var fieldLink = existingContentType.FieldLinks.FirstOrDefault(fl => fl.Id == fieldId);
var fieldRef = templateContentType.FieldRefs.Find(fr => fr.Id == fieldId);
if (fieldRef != null)
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Field__0__exists_in_content_type, fieldId);
if (fieldLink.Required != fieldRef.Required)
{
scope.LogPropertyUpdate("Required");
fieldLink.Required = fieldRef.Required;
isDirty = true;
}
if (fieldLink.Hidden != fieldRef.Hidden)
{
scope.LogPropertyUpdate("Hidden");
fieldLink.Hidden = fieldRef.Hidden;
isDirty = true;
}
}
}
// The new CT is a DocumentSet, and the target should be, as well
if (templateContentType.DocumentSetTemplate != null)
{
if (!Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.IsChildOfDocumentSetContentType(web.Context, existingContentType).Value)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_ContentTypes_InvalidDocumentSet_Update_Request, existingContentType.Id, existingContentType.Name);
}
else
{
Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate templateToUpdate =
Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, existingContentType);
// TODO: Implement Delta Handling
scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ContentTypes_DocumentSet_DeltaHandling_OnHold, existingContentType.Id, existingContentType.Name);
}
}
if (isDirty)
{
existingContentType.Update(true);
web.Context.ExecuteQueryRetry();
}
}
private static Microsoft.SharePoint.Client.ContentType CreateContentType(Web web, ContentType templateContentType, TokenParser parser, FileConnectorBase connector,
List<Microsoft.SharePoint.Client.ContentType> existingCTs = null, List<Microsoft.SharePoint.Client.Field> existingFields = null)
{
var name = parser.ParseString(templateContentType.Name);
var description = parser.ParseString(templateContentType.Description);
var id = parser.ParseString(templateContentType.Id);
var group = parser.ParseString(templateContentType.Group);
var createdCT = web.CreateContentType(name, description, id, group);
foreach (var fieldRef in templateContentType.FieldRefs)
{
var field = web.Fields.GetById(fieldRef.Id);
web.AddFieldToContentType(createdCT, field, fieldRef.Required, fieldRef.Hidden);
}
// Add new CTs
parser.AddToken(new ContentTypeIdToken(web, name, id));
#if !ONPREMISES
// Set resources
if (templateContentType.Name.ContainsResourceToken())
{
createdCT.NameResource.SetUserResourceValue(templateContentType.Name, parser);
}
if(templateContentType.Description.ContainsResourceToken())
{
createdCT.DescriptionResource.SetUserResourceValue(templateContentType.Description, parser);
}
#endif
//Reorder the elements so that the new created Content Type has the same order as defined in the
//template. The order can be different if the new Content Type inherits from another Content Type.
//In this case the new Content Type has all field of the original Content Type and missing fields
//will be added at the end. To fix this issue we ordering the fields once more.
createdCT.FieldLinks.Reorder(templateContentType.FieldRefs.Select(fld => fld.Name).ToArray());
createdCT.ReadOnly = templateContentType.ReadOnly;
createdCT.Hidden = templateContentType.Hidden;
createdCT.Sealed = templateContentType.Sealed;
if (!string.IsNullOrEmpty(parser.ParseString(templateContentType.DocumentTemplate)))
{
createdCT.DocumentTemplate = parser.ParseString(templateContentType.DocumentTemplate);
}
if (!String.IsNullOrEmpty(templateContentType.NewFormUrl))
{
createdCT.NewFormUrl = templateContentType.NewFormUrl;
}
if (!String.IsNullOrEmpty(templateContentType.EditFormUrl))
{
createdCT.EditFormUrl = templateContentType.EditFormUrl;
}
if (!String.IsNullOrEmpty(templateContentType.DisplayFormUrl))
{
createdCT.DisplayFormUrl = templateContentType.DisplayFormUrl;
}
createdCT.Update(true);
web.Context.ExecuteQueryRetry();
// If the CT is a DocumentSet
if (templateContentType.DocumentSetTemplate != null)
{
// Retrieve a reference to the DocumentSet Content Type
Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate documentSetTemplate =
Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, createdCT);
if (!String.IsNullOrEmpty(templateContentType.DocumentSetTemplate.WelcomePage))
{
// TODO: Customize the WelcomePage of the DocumentSet
}
foreach (String ctId in templateContentType.DocumentSetTemplate.AllowedContentTypes)
{
Microsoft.SharePoint.Client.ContentType ct = existingCTs.FirstOrDefault(c => c.StringId == ctId);
if (ct != null)
{
documentSetTemplate.AllowedContentTypes.Add(ct.Id);
}
}
foreach (var doc in templateContentType.DocumentSetTemplate.DefaultDocuments)
{
Microsoft.SharePoint.Client.ContentType ct = existingCTs.FirstOrDefault(c => c.StringId == doc.ContentTypeId);
if (ct != null)
{
using (Stream fileStream = connector.GetFileStream(doc.FileSourcePath))
{
documentSetTemplate.DefaultDocuments.Add(doc.Name, ct.Id, ReadFullStream(fileStream));
}
}
}
foreach (var sharedField in templateContentType.DocumentSetTemplate.SharedFields)
{
Microsoft.SharePoint.Client.Field field = existingFields.FirstOrDefault(f => f.Id == sharedField);
if (field != null)
{
documentSetTemplate.SharedFields.Add(field);
}
}
foreach (var welcomePageField in templateContentType.DocumentSetTemplate.WelcomePageFields)
{
Microsoft.SharePoint.Client.Field field = existingFields.FirstOrDefault(f => f.Id == welcomePageField);
if (field != null)
{
documentSetTemplate.WelcomePageFields.Add(field);
}
}
documentSetTemplate.Update(true);
web.Context.ExecuteQueryRetry();
}
web.Context.Load(createdCT);
web.Context.ExecuteQueryRetry();
return createdCT;
}
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
// if this is a sub site then we're not creating content type entities.
if (web.IsSubSite())
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Context_web_is_subweb__Skipping_content_types_);
return template;
}
template.ContentTypes.AddRange(GetEntities(web, scope));
// If a base template is specified then use that one to "cleanup" the generated template model
if (creationInfo.BaseTemplate != null)
{
template = CleanupEntities(template, creationInfo.BaseTemplate, scope);
}
}
return template;
}
private IEnumerable<ContentType> GetEntities(Web web, PnPMonitoredScope scope)
{
var cts = web.ContentTypes;
web.Context.Load(cts, ctCollection => ctCollection.IncludeWithDefaultProperties(ct => ct.FieldLinks));
web.Context.ExecuteQueryRetry();
List<ContentType> ctsToReturn = new List<ContentType>();
foreach (var ct in cts)
{
if (!BuiltInContentTypeId.Contains(ct.StringId))
{
ContentType newCT = new ContentType
(ct.StringId,
ct.Name,
ct.Description,
ct.Group,
ct.Sealed,
ct.Hidden,
ct.ReadOnly,
ct.DocumentTemplate,
false,
(from fieldLink in ct.FieldLinks.AsEnumerable<FieldLink>()
select new FieldRef(fieldLink.Name)
{
Id = fieldLink.Id,
Hidden = fieldLink.Hidden,
Required = fieldLink.Required,
})
)
{
DisplayFormUrl = ct.DisplayFormUrl,
EditFormUrl = ct.EditFormUrl,
NewFormUrl = ct.NewFormUrl,
};
// If the Content Type is a DocumentSet
if (Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.IsChildOfDocumentSetContentType(web.Context, ct).Value ||
ct.StringId.StartsWith(BuiltInContentTypeId.DocumentSet)) // TODO: This is kind of an hack... we should find a better solution ...
{
Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate documentSetTemplate =
Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, ct);
// Retrieve the Document Set
web.Context.Load(documentSetTemplate,
t => t.AllowedContentTypes,
t => t.DefaultDocuments,
t => t.SharedFields,
t => t.WelcomePageFields);
web.Context.ExecuteQueryRetry();
newCT.DocumentSetTemplate = new DocumentSetTemplate(
null, // TODO: WelcomePage not yet supported
(from allowedCT in documentSetTemplate.AllowedContentTypes.AsEnumerable()
select allowedCT.StringValue).ToArray(),
(from defaultDocument in documentSetTemplate.DefaultDocuments.AsEnumerable()
select new DefaultDocument
{
ContentTypeId = defaultDocument.ContentTypeId.StringValue,
Name = defaultDocument.Name,
FileSourcePath = String.Empty, // TODO: How can we extract the proper file?!
}).ToArray(),
(from sharedField in documentSetTemplate.SharedFields.AsEnumerable()
select sharedField.Id).ToArray(),
(from welcomePageField in documentSetTemplate.WelcomePageFields.AsEnumerable()
select welcomePageField.Id).ToArray()
);
}
ctsToReturn.Add(newCT);
}
}
return ctsToReturn;
}
private ProvisioningTemplate CleanupEntities(ProvisioningTemplate template, ProvisioningTemplate baseTemplate, PnPMonitoredScope scope)
{
foreach (var ct in baseTemplate.ContentTypes)
{
var index = template.ContentTypes.FindIndex(f => f.Id.Equals(ct.Id, StringComparison.OrdinalIgnoreCase));
if (index > -1)
{
template.ContentTypes.RemoveAt(index);
}
else
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ContentTypes_Adding_content_type_to_template___0_____1_, ct.Id, ct.Name);
}
}
return template;
}
public override bool WillProvision(Web web, ProvisioningTemplate template)
{
if (!_willProvision.HasValue)
{
_willProvision = template.ContentTypes.Any();
}
return _willProvision.Value;
}
public override bool WillExtract(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
{
if (!_willExtract.HasValue)
{
_willExtract = true;
}
return _willExtract.Value;
}
private static Byte[] ReadFullStream(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream mem = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
mem.Write(buffer, 0, read);
}
return mem.ToArray();
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using MixedRealityToolkit.Common;
using UnityEngine;
namespace MixedRealityToolkit.Utilities
{
/// <summary>
/// A Tagalong that stays at a fixed distance from the camera and always
/// seeks to stay on the edge or inside a sphere that is straight in front of the camera.
/// </summary>
public class SphereBasedTagalong : MonoBehaviour
{
[Tooltip("Sphere radius.")]
public float SphereRadius = 1.0f;
[Tooltip("How fast the object will move to the target position.")]
public float MoveSpeed = 2.0f;
/// <summary>
/// When moving, use unscaled time. This is useful for games that have a pause mechanism or otherwise adjust the game timescale.
/// </summary>
[SerializeField]
[Tooltip("When moving, use unscaled time. This is useful for games that have a pause mechanism or otherwise adjust the game timescale.")]
private bool useUnscaledTime = true;
/// <summary>
/// Used to initialize the initial position of the SphereBasedTagalong before being hidden on LateUpdate.
/// </summary>
[SerializeField]
[Tooltip("Used to initialize the initial position of the SphereBasedTagalong before being hidden on LateUpdate.")]
private bool hideOnStart;
[SerializeField]
[Tooltip("Display the sphere in red wireframe for debugging purposes.")]
private bool debugDisplaySphere = false;
[SerializeField]
[Tooltip("Display a small green cube where the target position is.")]
private bool debugDisplayTargetPosition = false;
private Vector3 targetPosition;
private Vector3 optimalPosition;
private float initialDistanceToCamera;
private void Start()
{
initialDistanceToCamera = Vector3.Distance(transform.position, CameraCache.Main.transform.position);
}
private void Update()
{
optimalPosition = CameraCache.Main.transform.position + CameraCache.Main.transform.forward * initialDistanceToCamera;
Vector3 offsetDir = transform.position - optimalPosition;
if (offsetDir.magnitude > SphereRadius)
{
targetPosition = optimalPosition + offsetDir.normalized * SphereRadius;
float deltaTime = useUnscaledTime
? Time.unscaledDeltaTime
: Time.deltaTime;
transform.position = Vector3.Lerp(transform.position, targetPosition, MoveSpeed * deltaTime);
}
}
private void LateUpdate()
{
if (hideOnStart)
{
hideOnStart = !hideOnStart;
gameObject.SetActive(false);
}
}
public void OnDrawGizmos()
{
if (Application.isPlaying == false) { return; }
Color oldColor = Gizmos.color;
if (debugDisplaySphere)
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(optimalPosition, SphereRadius);
}
if (debugDisplayTargetPosition)
{
Gizmos.color = Color.green;
Gizmos.DrawCube(targetPosition, new Vector3(0.1f, 0.1f, 0.1f));
}
Gizmos.color = oldColor;
}
}
}
|
<?php
namespace MCPI;
/**
* Transaction Recurrance Type Month
* - Repeat every X months on the Y day of the month
*/
class Transaction_Recurrance_Type_Month extends Transaction_Recurrance_Type_Abstract
{
protected static $type = 'month';
protected static $fields = array(
'month_count',
'month_day',
);
/**
* Check Data and throw error if there's an issue
*/
public function checkData($data)
{
if (
empty($data['month_count'])
or
empty($data['month_day'])
) {
self::error('Missing required data. Go back and try again.', true);
}
}
/**
* Catch up repetitions
*/
public function catchup()
{
$data = $this->getRecurringData();
$config = $data['recurrance_data'];
$start = $this->getStart();
$d = $start->format('d');
$m = $start->format('m');
$Y = $start->format('Y');
// Get on to the correct day of the month
$start->setDate($Y , $m , $config['month_day']);
$end = $this->getEnd();
// Will use this to iterate below
$mod_string = '+' . $config['month_count'] . ' months';
$this->catchupByModString($start, $end, $mod_string);
}
}
|
module.exports = (function () {
'use strict';
var strings = require('../../strings').dead,
style = require('../../style');
return {
create: function(){
this.game.world.width = this.game.canvas.width;
this.game.world.height = this.game.canvas.height;
this.game.camera.reset();
this.game.stage.backgroundColor = style.color.three;
var deadText = this.game.add.text(
this.game.world.centerX,
200,
strings.gregory,
{
font: 'bold 60px ' + style.font.regular,
fill: style.color.white,
align: 'center'
}
);
deadText.anchor.setTo(0.5);
this.game.stage.backgroundColor = style.color.three;
var face = this.game.add.text(
this.game.world.centerX,
320,
strings.face,
{
font: 'bold 85px ' + style.font.regular,
fill: style.color.white,
align: 'center'
}
);
face.anchor.setTo(0.5);
this.game.stage.backgroundColor = style.color.three;
var instructions = this.game.add.text(
this.game.world.centerX,
430,
strings.instructions,
{
font: 'bold 20px ' + style.font.regular,
fill: style.color.white,
align: 'center'
}
);
instructions.anchor.setTo(0.5);
},
capabilities: {
'revive': function(){this.game.state.start('map');}
}
};
})(); |
// We only need to import the modules necessary for initial render
import CoreLayout from '../layouts/CoreLayout';
import Home from './Home';
import CounterRoute from './Counter';
/* Note: Instead of using JSX, we recommend using react-router
PlainRoute objects to build route definitions. */
export const createRoutes = () => ({
path : '/',
component : CoreLayout,
indexRoute : Home,
childRoutes : [
CounterRoute
]
});
/* Note: childRoutes can be chunked or otherwise loaded programmatically
using getChildRoutes with the following signature:
getChildRoutes (location, cb) {
require.ensure([], (require) => {
cb(null, [
// Remove imports!
require('./Counter').default(store)
])
})
}
However, this is not necessary for code-splitting! It simply provides
an API for async route definitions. Your code splitting should occur
inside the route `getComponent` function, since it is only invoked
when the route exists and matches.
*/
export default createRoutes;
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_datagram_socket::native_handle</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_datagram_socket.html" title="basic_datagram_socket">
<link rel="prev" href="native.html" title="basic_datagram_socket::native">
<link rel="next" href="native_handle_type.html" title="basic_datagram_socket::native_handle_type">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="native.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_datagram_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="native_handle_type.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_datagram_socket.native_handle"></a><a class="link" href="native_handle.html" title="basic_datagram_socket::native_handle">basic_datagram_socket::native_handle</a>
</h4></div></div></div>
<p>
<span class="emphasis"><em>Inherited from basic_socket.</em></span>
</p>
<p>
<a class="indexterm" name="idp58299240"></a>
Get the native socket representation.
</p>
<pre class="programlisting"><span class="identifier">native_handle_type</span> <span class="identifier">native_handle</span><span class="special">();</span>
</pre>
<p>
This function may be used to obtain the underlying representation of the
socket. This is intended to allow access to native socket functionality
that is not otherwise provided.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2013 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="native.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_datagram_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="native_handle_type.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
/*
* Header: semaphore.h
*
* Provides wrapper functions around POSIX system calls semget,
* semctl and semop allowing the creation, initialization, opening
* and removal of a single semaphore at a time and implementing
* operations down (also known as P or wait) and up (also known as V
* or signal) on it.
*
*
* Copyright 2014 Razmig Kéchichian, INSA de Lyon, TC department
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
#ifndef __SEMAPHORE_H_SEMAPHORE__
#define __SEMAPHORE_H_SEMAPHORE__
#include <stdio.h>
#include <stdlib.h>
#include <sys/sem.h>
int create_semaphore(int key)
{
return semget(key, 1, 0660 | IPC_CREAT) ;
}
int open_semaphore(int key)
{
return semget(key, 1, 0660) ;
}
int remove_semaphore(int id)
{
return semctl(id, 0, IPC_RMID) ;
}
int init_semaphore(int id, int val)
{
return semctl(id, 0, SETVAL, val) ;
}
int up(int id)
{
struct sembuf op ;
op.sem_num = 0 ;
op.sem_op = 1 ;
op.sem_flg = 0 ;
return semop(id, &op, 1) ;
}
int down(int id)
{
struct sembuf op ;
op.sem_num = 0 ;
op.sem_op = -1 ;
op.sem_flg = 0 ;
return semop(id, &op, 1) ;
}
#endif
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.10.46: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.10.46
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li class="current"><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li class="current"><a href="functions.html"><span>All</span></a></li>
<li><a href="functions_func.html"><span>Functions</span></a></li>
<li><a href="functions_vars.html"><span>Variables</span></a></li>
<li><a href="functions_type.html"><span>Typedefs</span></a></li>
<li><a href="functions_enum.html"><span>Enumerations</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="functions.html#index_a"><span>a</span></a></li>
<li><a href="functions_b.html#index_b"><span>b</span></a></li>
<li><a href="functions_c.html#index_c"><span>c</span></a></li>
<li><a href="functions_d.html#index_d"><span>d</span></a></li>
<li><a href="functions_e.html#index_e"><span>e</span></a></li>
<li><a href="functions_f.html#index_f"><span>f</span></a></li>
<li><a href="functions_g.html#index_g"><span>g</span></a></li>
<li><a href="functions_h.html#index_h"><span>h</span></a></li>
<li><a href="functions_i.html#index_i"><span>i</span></a></li>
<li><a href="functions_k.html#index_k"><span>k</span></a></li>
<li><a href="functions_l.html#index_l"><span>l</span></a></li>
<li><a href="functions_m.html#index_m"><span>m</span></a></li>
<li><a href="functions_n.html#index_n"><span>n</span></a></li>
<li><a href="functions_o.html#index_o"><span>o</span></a></li>
<li><a href="functions_p.html#index_p"><span>p</span></a></li>
<li><a href="functions_r.html#index_r"><span>r</span></a></li>
<li><a href="functions_s.html#index_s"><span>s</span></a></li>
<li class="current"><a href="functions_t.html#index_t"><span>t</span></a></li>
<li><a href="functions_u.html#index_u"><span>u</span></a></li>
<li><a href="functions_v.html#index_v"><span>v</span></a></li>
<li><a href="functions_w.html#index_w"><span>w</span></a></li>
<li><a href="functions_~.html#index_~"><span>~</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
<div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div>
<h3><a class="anchor" id="index_t"></a>- t -</h3><ul>
<li>TakeSnapshot()
: <a class="el" href="classv8_1_1HeapProfiler.html#a39e6df3b54335e183ca57edae1dc78e7">v8::HeapProfiler</a>
</li>
<li>TerminateExecution()
: <a class="el" href="classv8_1_1V8.html#af7d845e6f55eb76085d5ff3601780986">v8::V8</a>
</li>
<li>ToArrayIndex()
: <a class="el" href="classv8_1_1Value.html#ab6b19a1e5aa5df50dfbb5d2ffa60bcdc">v8::Value</a>
</li>
<li>TryCatch()
: <a class="el" href="classv8_1_1TryCatch.html#adc9b1b11e73b0325df727914c348053d">v8::TryCatch</a>
</li>
<li>TurnOnAccessCheck()
: <a class="el" href="classv8_1_1Object.html#aa2299eda3240be1e76b7d5c2af7a6bbc">v8::Object</a>
</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRResult" id="SR_categories">
<div class="SREntry">
<a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../interface_book.html#a5d02b41a17f0bf3da50e4613762d3865" target="_parent">categories</a>
<span class="SRScope">Book</span>
</div>
</div>
<div class="SRResult" id="SR_collection">
<div class="SREntry">
<a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../interface_criteria.html#a52906da275ae0744abeba6007790553f" target="_parent">collection</a>
<span class="SRScope">Criteria</span>
</div>
</div>
<div class="SRResult" id="SR_cover">
<div class="SREntry">
<a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../interface_book.html#ab9a2eba00a1c12702737db9f315cb1e8" target="_parent">cover</a>
<span class="SRScope">Book</span>
</div>
</div>
<div class="SRResult" id="SR_criteria">
<div class="SREntry">
<a id="Item3" onkeydown="return searchResults.Nav(event,3)" onkeypress="return searchResults.Nav(event,3)" onkeyup="return searchResults.Nav(event,3)" class="SRSymbol" href="../interface_open_libra_client.html#afe8b3b6e59856c494c05b2967a0dffd2" target="_parent">criteria</a>
<span class="SRScope">OpenLibraClient</span>
</div>
</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
|
div.contents.local.topic ul {
float:right;
width: 228px;
margin: 30px 0 0;
padding: 0;
background-color: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 1px 4px rgba(0,0,0,.065);
-moz-box-shadow: 0 1px 4px rgba(0,0,0,.065);
box-shadow: 0 1px 4px rgba(0,0,0,.065);
list-style:none;
}
div.contents.local.topic ul > li > a {
display: block;
width: 190px \9;
margin: 0 0 -1px;
padding: 8px 14px;
border: 1px solid #e5e5e5;
}
div.contents.local.topic ul > li:first-child > a {
-webkit-border-radius: 6px 6px 0 0;
-moz-border-radius: 6px 6px 0 0;
border-radius: 6px 6px 0 0;
}
div.contents.local.topic ul > li:last-child > a {
-webkit-border-radius: 0 0 6px 6px;
-moz-border-radius: 0 0 6px 6px;
border-radius: 0 0 6px 6px;
}
div.contents.local.topic ul > li.active > a {
background: #B24926; /* Old browsers */
background: -moz-linear-gradient(45deg, #B24926 0%, #FAA523 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#B24926), color-stop(100%,#FAA523)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(45deg, #B24926 0%,#FAA523 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(45deg, #B24926 0%,#FAA523 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(45deg, #B24926 0%,#FAA523 100%); /* IE10+ */
background: linear-gradient(45deg, #B24926 0%,#FAA523 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#B24926', endColorstr='#FAA523',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
position: relative;
z-index: 2;
padding: 9px 15px;
border: 0;
text-shadow: 0 1px 0 rgba(0,0,0,.15);
-webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
-moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
}
|
<?php
namespace Niysu\Filters;
class StatusCodeOverwriteResponseFilterTest extends \PHPUnit_Framework_TestCase {
/**
*
*/
public function testStatusCodeSet() {
$response = $this->getMock('\Niysu\HTTPResponseInterface');
$response->expects($this->atLeastOnce())
->method('setStatusCode')
->with($this->equalTo(418));
$filter = new StatusCodeOverwriteResponseFilter($response, 418);
$filter->flush();
}
/**
* @depends testStatusCodeSet
*/
public function testStatusCodeCannotBeOverwritten() {
$response = $this->getMock('\Niysu\HTTPResponseInterface');
$response->expects($this->atLeastOnce())
->method('setStatusCode')
->with($this->equalTo(418));
$filter = new StatusCodeOverwriteResponseFilter($response, 418);
$filter->setStatusCode(200);
$filter->setStatusCode(300);
$filter->setStatusCode(400);
$filter->setStatusCode(500);
$filter->flush();
}
/**
*
*/
public function testHeadersAndDataGoThrough() {
$response = $this->getMock('\Niysu\HTTPResponseInterface');
$response->expects($this->atLeastOnce())
->method('setStatusCode')
->with($this->equalTo(418));
$response->expects($this->once())
->method('setHeader')
->with($this->equalTo('test'), $this->equalTo('value'));
$response->expects($this->once())
->method('appendData')
->with($this->equalTo('test'));
$filter = new StatusCodeOverwriteResponseFilter($response, 418);
$filter->setHeader('test', 'value');
$filter->appendData('test');
$filter->flush();
}
};
?> |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Files
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Files</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="rdoc-style.css" type="text/css" />
<base target="docwin" />
</head>
<body>
<div id="index">
<h1 class="section-bar">Files</h1>
<div id="index-entries">
<a href="files/app/controllers/application_rb.html">app/controllers/application.rb</a><br />
<a href="files/app/controllers/cart_controller_rb.html">app/controllers/cart_controller.rb</a><br />
<a href="files/app/controllers/items_controller_rb.html">app/controllers/items_controller.rb</a><br />
<a href="files/app/controllers/site_controller_rb.html">app/controllers/site_controller.rb</a><br />
<a href="files/app/controllers/user_controller_rb.html">app/controllers/user_controller.rb</a><br />
<a href="files/app/helpers/application_helper_rb.html">app/helpers/application_helper.rb</a><br />
<a href="files/app/helpers/cart_helper_rb.html">app/helpers/cart_helper.rb</a><br />
<a href="files/app/helpers/items_helper_rb.html">app/helpers/items_helper.rb</a><br />
<a href="files/app/helpers/site_helper_rb.html">app/helpers/site_helper.rb</a><br />
<a href="files/app/helpers/user_helper_rb.html">app/helpers/user_helper.rb</a><br />
<a href="files/app/models/item_rb.html">app/models/item.rb</a><br />
<a href="files/app/models/user_rb.html">app/models/user.rb</a><br />
<a href="files/doc/README_FOR_APP.html">doc/README_FOR_APP</a><br />
</div>
</div>
</body>
</html> |
import Colors from './Colors';
import Fonts from './Fonts';
import Metrics from './Metrics';
import Images from './Images';
import ApplicationStyles from './ApplicationStyles';
export { Colors, Fonts, Images, Metrics, ApplicationStyles };
|
#include <iostream>
#include <vector>
#include "PointerVectorExample.h"
#include "Score.h"
using namespace std;
namespace samples
{
void PointerVectorExample()
{
vector<Score*> scores;
scores.reserve(5);
Score* cppScore = new Score(30, "C++");
Score* algoScore = new Score(59, "Algorithm");
Score* javaScore = new Score(87, "Java");
Score* dataCommScore = new Score(74, "Data Comm");
Score* androidScore = new Score(41, "Android");
scores.push_back(cppScore);
scores.push_back(algoScore);
scores.push_back(javaScore);
scores.push_back(dataCommScore);
scores.push_back(androidScore);
PrintVector(scores);
vector<Score*>::iterator iter = scores.begin();
while (iter != scores.end())
{
Score* score = *iter;
if (score->GetClassName() == "Java")
{
iter = scores.erase(iter);
}
else
{
iter++;
}
}
PrintVector(scores);
for (vector<Score*>::iterator iter = scores.begin(); iter != scores.end(); ++iter)
{
Score* score = *iter;
if (score->GetScore() == 30)
{
score->SetScore(100);
}
}
cout << "After chaning the score of class 1" << endl;
PrintVector(scores);
delete cppScore;
delete algoScore;
delete javaScore;
delete dataCommScore;
delete androidScore;
}
void PrintVector(const vector<Score*>& scores)
{
for (vector<Score*>::const_iterator iter = scores.begin(); iter != scores.end(); iter++)
{
Score* score = *iter;
score->PrintVariables();
}
cout << endl;
}
} |
#!/usr/bin/python
import math
def trapezint(f, a, b, n) :
"""
Just for testing - uses trapazoidal approximation from on f from a to b with
n trapazoids
"""
output = 0.0
for i in range(int(n)):
f_output_lower = f( a + i * (b - a) / n )
f_output_upper = f( a + (i + 1) * (b - a) / n )
output += (f_output_lower + f_output_upper) * ((b-a)/n) / 2
return output
def second_derivative_approximation(f, x, h = .001):
"""
Approximates the second derivative with h (dx) = .001
"""
return (f(x + h) - 2 * f(x) + f(x - h))/h**2
def adaptive_trapezint(f, a, b, eps=1E-5):
"""
Uses trapazoidal approximation on f from a to b with an error value
of less than epsilon, to calculate the number of trapazoids
"""
max_second_derivative = 0
for i in range(10000):
i_second_d = abs(second_derivative_approximation(f, a + i * (b - a)/10000))
if( i_second_d > max_second_derivative):
max_second_derivative = i_second_d
h = math.sqrt(12 * eps / ((b - a) * max_second_derivative))
#There is a clear problem here, as if the second derivative is zero,
#h will become too large and there will be no approximation
n = (b - a)/h
return trapezint(f, a, b, n)
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Telerik Software Academy 2015 CSS Course</title>
<link href="ForumStyle.css" rel="stylesheet" />
<meta charset="UTF-8">
</head>
<body>
<header>
<h1 id="main-header">The Header</h1>
<nav>
<ul>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#" class="current">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
</ul>
</nav>
</header>
<section>
<article>
<header>
<h1>Sed nisl quam, rutrum eget commodo et, ullamcorper sed quam</h1>
</header>
<p>In posuere bibendum enim vel venenatis. Integer gravida, tortor quis gravida fermentum, libero orci hendrerit sapien, sed facilisis turpis mauris vitae turpis. Suspendisse nunc justo, dapibus in condimentum eget, rutrum id risus. Ut varius vulputate tortor. Suspendisse fermentum laoreet ante, ut placerat enim condimentum tristique. Sed gravida scelerisque enim at euismod. Integer aliquam vehicula purus quis accumsan. Nulla eu orci nec metus condimentum vestibulum sit amet quis lacus. Mauris tempor venenatis ultrices. Phasellus et leo a massa dapibus pharetra. Donec ut tellus vel mauris imperdiet ornare. Aliquam lacus purus, dictum et tristique id, ornare vitae arcu. Sed rutrum, neque sit amet euismod viverra, libero erat fermentum neque, a cursus libero urna eu erat. Pellentesque at tempor risus.</p>
<footer>
<p>posted on 12-dec-2012 by <a href="#">Minko Ivanov</a></p>
</footer>
</article>
<article>
<header>
<h1>Duis lacus erat, tristique non pharetra ac, bibendum sit amet ante</h1>
</header>
<p>Quisque tortor mi, consequat eu volutpat in, convallis a turpis. Aenean neque mi, vehicula id sollicitudin hendrerit, posuere quis elit. Aliquam ultricies ante fringilla tortor scelerisque a pharetra orci ornare. Vivamus nec mi id lorem ullamcorper convallis. Maecenas ornare volutpat dui. Aliquam erat volutpat. Aliquam erat volutpat. Nulla gravida erat nec erat pulvinar sed rhoncus risus congue. Nulla vel dui elit.</p>
<footer>
<p>posted on 12-dec-2012 by <a href="#">Minko Ivanov</a></p>
</footer>
</article>
<article>
<header>
<h1>Aliquam eleifend, nisi ut facilisis pharetra, mauris ipsum sagittis lacus</h1>
</header>
<p>Aliquam eleifend, nisi ut facilisis pharetra, mauris ipsum sagittis lacus, vel aliquam urna felis ac leo. Nullam massa odio, consequat ut posuere at, lacinia at nunc. Curabitur quam dolor, malesuada ac sodales eget, malesuada eu ipsum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed in nibh vitae ante elementum pharetra hendrerit in ligula. Proin non leo lorem, in ultricies tortor. Donec in nibh non diam ultricies feugiat vitae quis arcu. Sed sit amet odio quis eros pharetra ullamcorper. Nam id erat et leo varius molestie vitae a est. Curabitur ornare orci at dolor cursus sagittis. Phasellus vitae bibendum enim. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.</p>
<footer>
<p>posted on 12-dec-2012 by <a href="#">Minko Ivanov</a></p>
</footer>
</article>
</section>
<footer>Telerik Software Academy 2015 - CSS Course</footer>
</body>
</html>
|
import React from 'react';
import PropTypes from 'prop-types';
import Tooltip from '../Tooltip';
import SvgExclamation from '../svg/Exclamation.js';
import styles from './Input.scss';
class InputErrorSuffix extends React.Component {
render() {
return (
<Tooltip
dataHook="input-tooltip"
disabled={this.props.errorMessage.length === 0}
placement="top"
alignment="center"
textAlign="left"
content={this.props.errorMessage}
overlay=""
theme="dark"
maxWidth="230px"
hideDelay={150}
>
<div className={styles.exclamation}><SvgExclamation width={2} height={11}/></div>
</Tooltip>
);
}
}
InputErrorSuffix.propTypes = {
theme: PropTypes.oneOf(['normal', 'paneltitle', 'material', 'amaterial']),
errorMessage: PropTypes.string.isRequired,
focused: PropTypes.bool
};
export default InputErrorSuffix;
|
namespace CNodeUwp.Models
{
public class MainPageModel
{
public string Title { get; } = "Welcome to main page";
}
}
|
# wire v0.0.1
A minimalistic signal-slot pattern implementation in C++14. This implemenation has been used with success in a small emulation software but it has not been tested extensively yet so use with care.
### Prerequisites
The example has been tested on Linux with clang 3.5.0.
### How to build the example
First make sure you have a recent version of clang installed. Then just type `make`.
### How to use
Copy the file `wire.h` to your current working directory and include it like this:
```c++
#define WIRE_USE_EXCEPTIONS // optional
#include "wire.h"
using namespace wire;
```
### Credits
See http://stackoverflow.com/questions/21192659/variadic-templates-and-stdbind and http://stackoverflow.com/questions/26129933/bind-to-function-with-an-unknown-number-of-arguments-in-c.
### License
The MIT License (MIT), see [LICENSE](LICENSE).
|
//***************************************************
//* This file was generated by JSharp
//***************************************************
namespace java.nio.channels.spi
{
public abstract partial class AbstractSelectableChannel : SelectableChannel
{
public global::System.Object blockingLock(){return default(global::System.Object);}
public SelectableChannel configureBlocking(bool prm1){return default(SelectableChannel);}
protected void implCloseChannel(){}
protected virtual void implCloseSelectableChannel(){}
protected virtual void implConfigureBlocking(bool prm1){}
public AbstractSelectableChannel(SelectorProvider prm1){}
public SelectionKey keyFor(Selector prm1){return default(SelectionKey);}
public SelectorProvider provider(){return default(SelectorProvider);}
public SelectionKey register(Selector prm1, int prm2, global::System.Object prm3){return default(SelectionKey);}
public bool IsBlocking { get; private set;}
public bool IsRegistered { get; private set;}
}
}
|
package graph_test
import (
"testing"
"github.com/filwisher/algo/graph"
"github.com/filwisher/algo/set"
)
func TestGraph(t *testing.T) {
conn := 1
g := graph.NewGraph()
for i := 2; i < 6; i++ {
g.AddEdge(conn, i)
}
s := set.NewSet()
for e := range g.Adjacent(conn) {
s.Add(e)
}
for i := 2; i < 6; i++ {
if !s.Contains(i) {
t.Errorf("graph does not contain edge between %d and %d", conn, i)
}
for e := range g.Adjacent(i) {
if e != conn {
t.Errorf("edges are not bidirectional")
}
}
}
}
|
# 数据类型
## 日期
日期类型 | 存储空间 | 日期格式 | 日期范围
----------|----------|---------------|----------------------------------
datetime | 8 bytes | YYYY-MM-DD HH:MM:SS | 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59
timestamp | 4 bytes | YYYY-MM-DD HH:MM:SS | 1970-01-01 00:00:01 ~ 2038
date | 3 bytes | YYYY-MM-DD | 1000-01-01 ~ 9999-12-31
year | 1 bytes | YYYY | 1901 ~ 2155
## 重点类型介绍
* TIMESTAMP
1. 4个字节储存
2. 值以UTC格式保存
3. 时区转化 ,存储时对当前的时区进行转换,检索时再转换回当前的时区。
* datetime
1.8个字节储存
2.实际格式储存
3.与时区无关
## 实例对比
|
///////////////////////////////////////////////////////////////////////////////
//
// (C) Autodesk, Inc. 2007-2011. All rights reserved.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef ATILDEFS_H
#include "AtilDefs.h"
#endif
#ifndef POINT2D_H
namespace Atil { class Point2d; }
#endif
#ifndef MATRIX2D_H
namespace Atil { class Matrix2d; }
#endif
#ifndef VECTOR2D_H
#define VECTOR2D_H
namespace Atil
{
/// <summary>
/// This class holds a two dimensional vector in Cartesian coordinates.
/// It interacts with the <c>Matrix2d</c> and <c>Point2d</c> classes.
/// </summary>
///
class Vector2d
{
public:
/// <summary>The x offset.
/// </summary>
double x;
/// <summary>The y offset.
/// </summary>
double y;
/// <summary>
/// The default (empty) constructor.
/// </summary>
///
Vector2d ();
/// <summary>
/// The initializing constructor.
/// </summary>
///
/// <param name="dx">This value will be set as the <c>x</c> member.
/// </param>
///
/// <param name="dy">This value will be set as the <c>y</c> member.
/// </param>
///
Vector2d ( double dx, double dy );
/// <summary>
/// The copy constructor.
/// </summary>
///
/// <param name='x'> The instance to be copied. </param>
///
Vector2d ( const Vector2d& x );
/// <summary>
/// The destructor.
/// </summary>
///
virtual ~Vector2d ();
/// <summary>
/// This method will over write the current members with values from the argument.
/// </summary>
///
/// <param name="v2d">A constant reference to a <c>Vector2d</c> instance that will be
/// referenced for the <c>x</c> and <c>y</c> member values to be set.
/// </param>
///
virtual const Vector2d& set ( const Vector2d& v2d );
/// <summary>
/// This method will over write the current members with values from the arguments.
/// </summary>
///
/// <param name="dx">This value will be set as the <c>x</c> member.
/// </param>
///
/// <param name="dy">This value will be set as the <c>y</c> member.
/// </param>
///
virtual const Vector2d& set ( double x, double y );
/// <summary>
/// This method will multiply the <c>Vector2d</c> by the <c>Matrix2d</c> affecting
/// a 2 dimensional transform of the vector.
/// </summary>
///
/// <param name="leftSide">The matrix that will be vector will be multiplied by.
/// </param>
///
virtual Vector2d& transformBy (const Matrix2d& leftSide);
/// <summary>
/// This method will rotate the vector counter clockwise through the specified angle.
/// </summary>
///
/// <param name="dRads">The angle that the vector should be rotated in Radians.
/// </param>
///
virtual const Vector2d& rotate ( double dRads );
/// <summary>
/// This method returns the length of the vector.
/// </summary>
///
virtual double length () const;
/// <summary>
/// This method returns the vector's counter clockwise angle from the positive X-Axis.
/// </summary>
///
virtual double angle () const;
/// <summary>
/// This method returns the angle between the vector and the argument vector. The return
/// will always be less than or equal to PI.
/// </summary>
///
/// <param name="bvTo">A const reference to the vector to measure the angle from.
/// </param>
///
virtual double angleTo ( const Vector2d& bvTo ) const; // between 0 and Pi
/// <summary>
/// This method returns the counter clockwise angle between the vector and
/// the argument vector. The return will always be less than or equal to 2 * PI.
/// </summary>
///
/// <param name="bvTo">A const reference to the vector to measure the angle from.
/// </param>
///
virtual double ccwAngleTo ( const Vector2d& bvTo ) const;
/// <summary>
/// This method will normalize (make the length of the vector equal to one) the vector.
/// </summary>
///
virtual const Vector2d& normalize();
/// <summary>
/// This method will calculate the normal of the vector and return a new
/// <c>Vector2d</c> instance set to the normal.
/// </summary>
///
/// <returns>
/// A <c>Vector2d</c> instance set to the normal of the vector.
/// </returns>
///
virtual Vector2d normal() const;
/// <summary>
/// This method negates the vector.
/// </summary>
///
virtual const Vector2d& negate();
/// <summary>
/// This method returns a new vector that is perpendicular to vector.
/// </summary>
///
/// <returns>
/// This method returns a <c>Vector2d</c> set to a perpendicular normal vector.
/// </returns>
///
virtual Vector2d perpVector( ) const;
/// <summary>
/// This method calculates the dot product of the vector and the argument.
/// </summary>
///
/// <param name='v'> The argument to calculate the dot product with. </param>
///
virtual double dotProduct(const Vector2d& v) const;
/// <summary>
/// This method tests if the vector and the argument have the same angle.
/// </summary>
///
/// <param name='iv'> The argument to test the direction of. </param>
///
virtual bool isCodirectionalTo( const Vector2d& iv ) const;
/// <summary>
/// This method tests if the vector and the argument specify the same line.
/// </summary>
///
/// <param name='v'> The argument to be tested. </param>
///
virtual bool isParallelTo ( const Vector2d& v ) const;
/// <summary>
/// This method returns true if the <c>x</c> and <c>y</c> members of the
/// vector and the argument are equal.
/// </summary>
///
/// <param name="v">A const reference to the vector to test for equality.
/// </param>
///
virtual bool isEqualTo (const Vector2d& v) const;
/// <summary>
/// This method calculates the nearest x or y axis and returns a <c>Vector2d</c> set to
/// that axis.
/// </summary>
///
/// <returns>
/// This methods returns a <c>Vector2d</c> instance set to one of the four axis of
/// the Cartesian coordinate system (x, y, -x, -y).
/// </returns>
///
virtual Vector2d getOrthoVector ( ) const;
/// <summary>
/// The negation operator negates returns the negation of the <c>Vector2d</c>
/// </summary>
///
/// <returns>
/// This methods returns a <c>Vector2d</c> instance set to negation of the vector.
/// </returns>
///
virtual Vector2d operator-() const;
/// <summary>
/// The subtraction operator.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// This methods returns a <c>Vector2d</c> instance result of the subtraction.
/// </returns>
///
virtual Vector2d operator-(const Vector2d& rhs) const;
/// <summary>
/// The subtract and assign operator. The result of the subtraction over writes
/// the current value of the vector.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// Returns a reference to <c>*this</c>.
/// </returns>
///
virtual Vector2d& operator-=(const Vector2d& rhs);
/// <summary>
/// An operator that subtracts the vector from a <c>Point2d</c> instance.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// This methods returns a <c>Point2d</c> instance result of the subtraction.
/// </returns>
///
virtual Point2d operator-(const Point2d& rhs) const;
/// <summary>
/// An operator that adds the vector to a <c>Point2d</c> instance.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// This methods returns a <c>Point2d</c> instance result of the addition.
/// </returns>
///
virtual Point2d operator+(const Point2d& rhs) const;
/// <summary>
/// The addition operator.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// This methods returns a <c>Vector2d</c> instance result of the addition.
/// </returns>
///
virtual Vector2d operator+(const Vector2d& rhs) const;
/// <summary>
/// The addition and assign operator. The result of the addition over writes
/// the current value of the vector.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// Returns a reference to <c>*this</c>.
/// </returns>
///
virtual Vector2d& operator+=(const Vector2d& rhs);
/// <summary>
/// The multiplication operator. This will multiply the vector by argument.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// This methods returns a <c>Vector2d</c> instance result of the multiplication.
/// </returns>
///
virtual Vector2d operator*(const double& rhs) const;
/// <summary>
/// The multiplication and assign operator. The result of the multiplication over writes
/// the current value of the vector.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// Returns a reference to <c>*this</c>.
/// </returns>
///
virtual Vector2d& operator*=( const double& rhs);
/// <summary>
/// The division operator. This will divide the vector by argument.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// This methods returns a <c>Vector2d</c> instance result of the division.
/// </returns>
///
virtual Vector2d operator/(const double&rhs) const;
/// <summary>
/// The divide and assign operator. The result of the division over writes
/// the current value of the vector.
/// </summary>
///
/// <param name='rhs'> The argument to be operated with. </param>
///
/// <returns>
/// Returns a reference to <c>*this</c>.
/// </returns>
///
virtual Vector2d& operator/=( const double& rhs);
/// <summary>
/// The equals operator.
/// </summary>
///
/// <param name='rhs'> The argument to be tested. </param>
///
/// <returns> Returns true the arguments are equal.
/// </returns>
virtual bool operator==(const Vector2d& rhs) const;
/// <summary>
/// The not equal operator.
/// </summary>
///
/// <param name='rhs'> The argument to be tested. </param>
///
/// <returns> Returns true the arguments are not equal.
/// </returns>
virtual bool operator!=(const Vector2d& rhs) const;
};
//////
// When using vectors in the image coordinate system, you should use this
// class. It takes the upper-left coordinate system of images into account
// when calculating angles.
//
class VectorUL : public Vector2d
{
public:
/// <summary>
/// The default (empty) constructor.
/// </summary>
///
VectorUL ();
/// <summary>
/// The initializing constructor.
/// </summary>
///
/// <param name="dx">This value will be set as the <c>x</c> member.
/// </param>
///
/// <param name="dy">This value will be set as the <c>y</c> member.
/// </param>
///
VectorUL ( double dx, double dy );
/// <summary>
/// The copy constructor.
/// </summary>
///
VectorUL ( const Vector2d& x );
/// <summary>
/// The destructor.
/// </summary>
///
virtual ~VectorUL ();
/// <summary>
/// This method will rotate the vector counter clockwise through the specified angle.
/// </summary>
///
/// <param name="dRads">The angle that the vector should be rotated in Radians.
/// </param>
///
/// <remarks>
/// This operation uses an upper-left image based coordinates system where the positive
/// y axis points down the image.
/// </remarks>
///
virtual const Vector2d& rotate ( double dRads );
/// <summary>
/// This method returns a new vector that is perpendicular to vector.
/// </summary>
///
/// <returns>
/// This method returns a <c>Vector2d</c> set to a perpendicular normal vector.
/// </returns>
///
/// <remarks>
/// This operation uses an upper-left image based coordinates system where the positive
/// y axis points down the image.
/// </remarks>
///
virtual Vector2d perpVector( ) const;
/// <summary>
/// This method returns the vector's counter clockwise angle from the positive X-Axis.
/// </summary>
///
/// <remarks>
/// This operation uses an upper-left image based coordinates system where the positive
/// y axis points down the image.
/// </remarks>
///
virtual double angle () const;
/// <summary>
/// This method returns the counter clockwise angle between the vector and
/// the argument vector. The return will always be less than or equal to 2 * PI.
/// </summary>
///
/// <param name="bvTo">A const reference to the vector to measure the angle from.
/// </param>
///
/// <remarks>
/// This operation uses an upper-left image based coordinates system where the positive
/// y axis points down the image.
/// </remarks>
///
virtual double ccwAngleTo ( const Vector2d& bvTo ) const;
};
} //end of namespace
#endif
|
const fs = require("fs");
const path = require("path");
const {template} = require("lodash");
const minimist = require("minimist");
const yaml = require("js-yaml");
const argv = minimist(process.argv.slice(2));
const conf = {};
try {
const src = fs.readFileSync(path.resolve(__dirname, "../deploy-config.yml"));
const yml = yaml.safeLoad(src);
Object.assign(conf, yml);
if (argv.env && yml[argv.env]) Object.assign(conf, yml[argv.env]);
else if (yml.env && yml[yml.env]) Object.assign(conf, yml[yml.env]);
} catch(e) {
if (e.code !== "ENOENT") console.error(e);
}
Object.assign(conf, argv);
function walkfs(file, exts, fn) {
const stat = fs.statSync(file);
if (stat.isDirectory()) {
fs.readdirSync(file).forEach(name => {
walkfs(path.join(file, name), exts, fn);
});
} else if (exts.includes(path.extname(file))) {
const src = fs.readFileSync(file, "utf-8");
fn(src, file);
}
}
function build(dir, out, exts, join="", mode) {
const result = [];
walkfs(dir, exts, (src, file) => {
const data = Object.assign({}, conf, {
__filename: file,
__dirname: path.dirname(file)
});
const opts = {
variable: "$",
imports: {}
};
result.push(template(src, opts)(data).trim() + "\n");
});
if (result) {
fs.writeFileSync(out, result.join(join + "\n"), { mode });
}
}
build(
path.join(__dirname, "kube-conf"),
path.resolve(__dirname, "../kubernetes.yml"),
[ ".yml" ],
"---"
);
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="BloggerCMS" />
<meta name="description" content="BloggerCMS Official Blog">
<meta name="author" content="BloggerCMS">
<title>BloggerCMS Blog</title>
<!-- rss feed url -->
<link rel="alternate" type="application/rss+xml" title="BloggerCMS Blog" href="https://bloggercms.github.io/rss.xml"/>
<!-- favicon -->
<link rel="shortcut icon" href="/favicon.ico"/>
<link rel="shortcut icon" href="https://bloggercms.github.io/favicon.ico"/>
<!-- Bootstrap CSS file -->
<link href="https://bloggercms.github.io/js/plugins/bootstrap-3.0.3/css/slate.min.css" rel="stylesheet"/>
<link href="https://bloggercms.github.io/js/plugins/font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://bloggercms.github.io/js/plugins/bootstrap-3.0.3/plugins/social-buttons.css" rel="stylesheet"/>
<!-- syntax highlighter css file -->
<link href="https://bloggercms.github.io/js/plugins/highlight/styles/railscasts.css" rel="stylesheet" />
<!-- lightbox for images -->
<link href="https://bloggercms.github.io/js/plugins/lightbox/ekko-lightbox.min.css" rel="stylesheet" />
<!-- blog custom CSS file -->
<link href="https://bloggercms.github.io/css/style.css" rel="stylesheet"/>
</head><body>
<!-- Header -->
<header class="navbar navbar-default
navbar-fixed-top bs-docs-nav" role="banner">
<div class="container">
<div class="navbar-header">
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="https://bloggercms.github.io/index.html" class="navbar-brand"><i class="fa fa-edit"></i> BloggerCMS Blog</a>
</div>
<nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation">
<div class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="searchQuery form-control" placeholder="Search Posts">
</div>
<button type="button" class="searchButton btn btn-default"><i class="glyphicon glyphicon-search"></i>
Submit
</button>
</div>
<ul class="nav navbar-nav page-links">
<li><a href="https://bloggercms.github.io/page/get-started.html">Get Started</a></li>
<li><a href="https://bloggercms.github.io/page/about.html">About</a></li>
<li><a href="https://bloggercms.github.io/page/showcase.html">Showcase</a></li>
<li><a href="https://bloggercms.github.io/page/support.html">Support</a></li>
<li><a href="https://bloggercms.github.io/page/donations.html">Donations</a></li>
</ul>
</nav>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-md-8 main-content">
<h1>Category Posts</h1>
<hr/>
<br/>
<h3><a href="https://bloggercms.github.io/post/how-to-use-specific-custom-value-in-layouts.html">How to Use Specific Custom Value in Layouts</a></h3>
<span class="glyphicon glyphicon-time"></span> April 11, 2015 10:20 AM
<h3><a href="https://bloggercms.github.io/post/how-to-add-pagination-feature-to-custom-bloggercms-layouts.html">How to Add Pagination Feature to Custom BloggerCMS Layouts</a></h3>
<span class="glyphicon glyphicon-time"></span> April 10, 2015 10:40 AM
<h3><a href="https://bloggercms.github.io/post/how-to-add-search-feature-to-custom-bloggercms-layouts.html">How to Add Search Feature to Custom BloggerCMS Layouts</a></h3>
<span class="glyphicon glyphicon-time"></span> April 09, 2015 04:03 PM
<h3><a href="https://bloggercms.github.io/post/new-layout-initializr.html">New Layout: Initializr</a></h3>
<span class="glyphicon glyphicon-time"></span> April 09, 2015 12:05 AM
</div>
<div class="sidebar col-md-4">
<div class="well text-center">
<a href="https://github.com/sarfraznawaz2005/BloggerCMS" class="btn btn-success"><i class="fa fa-download"></i> Download BloggerCMS</a>
</div>
<!-- Follow Panel -->
<div class="panel panel-primary text-center">
<div class="panel-heading">
<strong>Follow BloggerCMS Blog</strong>
</div>
<div class="panel-body">
<a target="_blank" href="https://bloggercms.github.io/rss.xml" class="btn btn-social-icon btn-outline"><i class="fa fa-rss"></i></a>
<a target="_blank" href="https://github.com/bloggercms/bloggercms.github.io" class="btn btn-social-icon btn-github"><i class="fa fa-github"></i></a>
</div>
</div>
<!-- Latest Posts -->
<div class="panel panel-primary">
<div class="panel-heading">
<strong>Latest Posts</strong>
</div>
<ul class="list-group">
<li class="list-group-item"><a href="https://bloggercms.github.io/post/how-to-use-specific-custom-value-in-layouts.html">How to Use Specific Custom Value in Layouts</a></li>
<li class="list-group-item"><a href="https://bloggercms.github.io/post/bloggercms-added-to-list-of-static-site-generators.html">BloggerCMS Added to List of Static Site Generators</a></li>
<li class="list-group-item"><a href="https://bloggercms.github.io/post/how-to-add-pagination-feature-to-custom-bloggercms-layouts.html">How to Add Pagination Feature to Custom BloggerCMS Layouts</a></li>
<li class="list-group-item"><a href="https://bloggercms.github.io/post/how-to-add-search-feature-to-custom-bloggercms-layouts.html">How to Add Search Feature to Custom BloggerCMS Layouts</a></li>
<li class="list-group-item"><a href="https://bloggercms.github.io/post/how-to-create-a-layout-for-bloggercms.html">How to Create a Layout for BloggerCMS</a></li>
</ul>
</div>
<!-- Categories -->
<div class="panel panel-primary">
<div class="panel-heading">
<strong>Categories</strong>
</div>
<ul class="list-group">
<li class="list-group-item"><a href="https://bloggercms.github.io/category/bloggercms.html">BloggerCMS</a></li>
<li class="list-group-item"><a href="https://bloggercms.github.io/category/layouts.html">Layouts</a></li>
<li class="list-group-item"><a href="https://bloggercms.github.io/category/tutorial.html">Tutorial</a></li>
</ul>
</div>
<!-- Archives -->
<div class="panel panel-primary">
<div class="panel-heading">
<strong>Archives</strong>
</div>
<ul class="archives list-group"><li class="list-group-item archive_link"><a href="https://bloggercms.github.io/archive/april-2015">April 2015</a></li></ul>
</div>
<!-- Tags -->
<div class="panel panel-primary">
<div class="panel-heading">
<strong>Tags Cloud</strong>
</div>
<div class="panel-body">
<ul class="list-inline">
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/admin.html" title="'admin' returned a count of 0">admin</a>
<a style="font-size: 21px" class="tag_cloud" href="https://bloggercms.github.io/tag/bloggercms.html" title="'bloggercms' returned a count of 2">bloggercms</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/cms.html" title="'cms' returned a count of 0">cms</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/custom.html" title="'custom' returned a count of 0">custom</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/disqus.html" title="'disqus' returned a count of 0">disqus</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/image.html" title="'image' returned a count of 0">image</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/imagemanager.html" title="'imagemanager' returned a count of 0">imagemanager</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/initializr.html" title="'initializr' returned a count of 0">initializr</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/intro.html" title="'intro' returned a count of 0">intro</a>
<a style="font-size: 30px" class="tag_cloud" href="https://bloggercms.github.io/tag/layout.html" title="'layout' returned a count of 4">layout</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/page.html" title="'page' returned a count of 0">page</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/pagination.html" title="'pagination' returned a count of 0">pagination</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/paging.html" title="'paging' returned a count of 0">paging</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/php.html" title="'php' returned a count of 0">php</a>
<a style="font-size: 16px" class="tag_cloud" href="https://bloggercms.github.io/tag/post.html" title="'post' returned a count of 1">post</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/search.html" title="'search' returned a count of 0">search</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/settings.html" title="'settings' returned a count of 0">settings</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/template.html" title="'template' returned a count of 0">template</a>
<a style="font-size: 25px" class="tag_cloud" href="https://bloggercms.github.io/tag/tutorial.html" title="'tutorial' returned a count of 3">tutorial</a>
<a style="font-size: 12px" class="tag_cloud" href="https://bloggercms.github.io/tag/value.html" title="'value' returned a count of 0">value</a>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<footer>
<div class="container">
<hr/>
<p class="text-center">Published by <strong><a target="_blank" href="https://github.com/sarfraznawaz2005/BloggerCMS">BloggerCMS</a></strong></p>
</div>
</footer>
<!-- Jquery and Bootstrap Script files -->
<script src="https://bloggercms.github.io/js/jquery-2.0.3.min.js"></script>
<script src="https://bloggercms.github.io/js/plugins/bootstrap-3.0.3/js/bootstrap.min.js"></script>
<script src="https://bloggercms.github.io/js/plugins/highlight/highlight.pack.js"></script>
<script src="https://bloggercms.github.io/js/plugins/lightbox/ekko-lightbox.min.js"></script>
<script>
var __blogURL = 'https://bloggercms.github.io';
</script>
<script src="https://bloggercms.github.io/js/blog.js"></script>
<script src="https://bloggercms.github.io/js/search.js"></script>
</body>
</html> |
var set = new HashSet();
//Array size
var arrElementWidth = 150;
var arrElementHeight = 40;
//Key size
var keyWidth = 50;
var keyMargin = 5;
var width = 800;
var height = DEFAULT_TABLE_SIZE * (arrElementHeight + 5);
//Hash function block size
var blockWidth = keyWidth + keyMargin + arrElementWidth;
var blockHeight = DEFAULT_TABLE_SIZE * (arrElementHeight + 5);
var blockMargin = 30;
var codeDisplayManager = new CodeDisplayManager('javascript', 'hashSet');
var drawingArea;
var hashFunctionBlock;
var bucket;
var keys;
var newestElement;
var arrow;
//Panning
var pan;
$(document).ready(function () {
drawingArea = d3.select("#hash")
.append("svg:svg")
.attr("width", $('#graphics').width())
.attr("height", $('#graphics').height())
.append('g');
hashFunctionBlock = drawingArea.append("g");
keys = drawingArea.append("g");
bucket = drawingArea.append("g");
hashFunctionBlock.attr("id", "hashFunctionBlock");
keys.attr("id", "keys");
bucket.attr("id", "bucket");
hashFunctionBlock.append("rect")
.attr("width", blockWidth)
.attr("height", blockHeight)
.attr("x", width - arrElementWidth - keyWidth - blockWidth - blockMargin)
.attr("fill", "cornflowerBlue");
hashFunctionBlock.append("text")
.attr("width", blockWidth)
.attr("height", blockHeight)
.attr("y", blockHeight - 10)
.attr("x", width + 10 - arrElementWidth - keyWidth - blockWidth - blockMargin)
.text("")
.attr("class", 'noselect');
createKeysAndBuckets(DEFAULT_TABLE_SIZE, "1");
// arrow marker
drawingArea.append('defs').append('marker')
.attr('id', 'end-arrow')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 6)
.attr('markerWidth', 3)
.attr('markerHeight', 3)
.attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M0,-5L10,0L0,5')
.attr('fill', 'red');
arrow = drawingArea.append("path")
.attr("id", "arrow")
.attr("fill", "none")
.attr("stroke", "red")
.attr("stroke-width", "4")
.attr("opacity", "0")
.style('marker-end', 'url(#end-arrow)');
pan = d3.zoom()
.scaleExtent([1 / 10, 1])
.on("zoom", panning);
drawingArea.call(pan);
drawingArea.attr("transform", "translate(50,20) scale(0.70)");
});
function runAdd(x, probing, hashFunc) {
set.probingType = probing == "Quadratic" ? "quadratic" : "linear";
set.hashFunc = hashFunc == "Simple" ? getSimpleHashCode : getHashCode;
codeDisplayManager.loadFunctions('add', 'rehash');
codeDisplayManager.changeFunction('add');
set.add(x);
}
function runRemove(x) {
codeDisplayManager.loadFunctions('remove', 'rehash', 'add');
codeDisplayManager.changeFunction('remove');
set.remove(x);
}
function panning() {
drawingArea.attr("transform", d3.event.transform);
}
function updateArrow(index) {
unhighlightKey();
var targetY = index * (arrElementHeight + 5);
var lineData = [{ "x": arrElementWidth, "y": height / 2 + arrElementHeight / 2 },
{ "x": width + 30 - blockWidth - arrElementWidth - keyWidth - blockMargin, "y": height / 2 + arrElementHeight / 2 },
{ "x": width - 30 - arrElementWidth - keyWidth - blockMargin, "y": targetY + arrElementHeight / 2 },
{ "x": width - arrElementWidth - keyWidth - keyMargin, "y": targetY + arrElementHeight / 2 }];
var lineFunction = d3.line()
.x(function (d) { return d.x; })
.y(function (d) { return d.y; });
appendAnimation(null, [{ e: '#arrow', p: { attr: { d: lineFunction(lineData), opacity: 1 } }, o: { duration: 1 } }], null);
highlightKey(index);
}
function clearHighlight(array) {
appendAnimation(null, [{ e: $(array + " rect"), p: { attr: { fill: "cornflowerBlue" } }, o: { duration: 1 } }], null);
}
function add(value) {
prevOffset = 0;
hideHash();
newestElement = bucket.append("svg:g")
.attr("transform", "translate(0," + height / 2 + ")")
.attr("class", "newElement")
.attr("opacity", 0);
newestElement.append("rect")
.attr("width", arrElementWidth)
.attr("height", arrElementHeight)
.attr("fill", "#9c6dfc");
newestElement.append("text")
.style("text-anchor", "middle")
.attr("x", arrElementWidth / 2)
.attr("y", arrElementHeight / 2 + 7)
.text(value)
.style("font-size", "22px")
.style("font-weight", "bold");
appendAnimation(null, [{ e: newestElement.node(), p: { attr: { opacity: "1" } }, o: { duration: 1 } }], null);
}
function moveToHashFunctionBlock() {
appendAnimation(null, [
{ e: newestElement.node(), p: { x: width + 10 - blockWidth - arrElementWidth - keyWidth - blockMargin }, o: { duration: 1 } },
{ e: $("#arrow"), p: { attr: { opacity: 0, d: "" } }, o: { duration: 1, position: '-=1' } }
], null);
}
function replaceElement(index) {
moveToHashFunctionBlock();
appendAnimation(6, [
{ e: $("#bucket").filter(".element" + index), p: { attr: { opacity: 0 } }, o: { duration: 1 } },
{ e: newestElement.node(), p: { x: width - arrElementWidth, y: index * (arrElementHeight + 5) }, o: { duration: 1, position: '-=1' } },
], codeDisplayManager);
$("#bucket").filter(".element" + index).attr("class", "removed");
$(newestElement).attr("class", "element" + index);
}
function highlightKey(index) {
appendAnimation(null, [{ e: $("#keys rect").filter(".key" + index), p: { attr: { stroke: "red" } }, o: { duration: 1 } }], null);
}
function unhighlightKey() {
appendAnimation(null, [{ e: $("#keys rect"), p: { attr: { stroke: "none" } }, o: { duration: 1 } }], null);
}
function removeElement(index) {
appendAnimation(4, [
{ e: $(".element" + index), p: { attr: { stroke: "red", "stroke-width": "2" } }, o: { duration: 1 } },
{ e: $("#arrow"), p: { attr: { opacity: 0, d: "" } }, o: { duration: 1, position: '-=1' } }
], codeDisplayManager);
}
var prevOffset = 0;
function displayHash(hashValue, length, offset) {
var hashString;
if (set.probingType != "quadratic") {
if (offset == 0) {
hashString = hashValue + " % " + length + " = " + Math.abs(hashValue % length);
}
prevOffset += offset;
hashString = hashValue + " % " + length + " + " + prevOffset + " = " + (Math.abs(hashValue % length) + prevOffset);
} else {
if (offset == 0) {
hashString = hashValue + " % " + length + " = " + Math.abs(hashValue % length);
}
prevOffset += offset;
hashString = hashValue + " % " + length + " + " + offset + " * " + offset + " = " + (Math.abs(hashValue % length) + offset * offset);
}
appendAnimation(null, [
{ e: $("#hashFunctionBlock text"), p: { attr: { stroke: "red" }, text: hashString }, o: { duration: 1 } },
{ e: $("#hashFunctionBlock text"), p: { attr: { stroke: "black" } }, o: { duration: 1 } }
], null);
}
function hideHash() {
appendAnimation(null, [{ e: $("#hashFunctionBlock text"), p: { text: "" }, o: { duration: 1 } }], null);
}
function renewTable(length) {
appendAnimation(null, [
{ e: $("#bucket, #bucket *"), p: { attr: { opacity: 0 } }, o: { duration: 1 } },
{ e: $("#keys, #keys *"), p: { attr: { opacity: 0 } }, o: { duration: 1, position: '-=1' } }
], null);
$("#bucket *").attr("class", "removed");
$("#keys *").attr("class", "removed");
createKeysAndBuckets(length, "0");
appendAnimation(3, [
{ e: $("#bucket, #bucket *").filter(":not(.removed)"), p: { attr: { opacity: 1 } }, o: { duration: 1 } },
{ e: $("#keys, #keys *").filter(":not(.removed)"), p: { attr: { opacity: 1 } }, o: { duration: 1, position: '-=1' } }
], codeDisplayManager);
}
function createKeysAndBuckets(length, opacity) {
for (var i = 0; i < length; i++) {
//Key
var keyPosX = width - arrElementWidth - keyWidth - keyMargin;
var keyPosY = i * (arrElementHeight + 5);
var keyGroup = keys.append("svg:g")
.attr("transform", "translate(" + keyPosX + "," + keyPosY + ")");
keyGroup.append("svg:rect")
.attr("height", arrElementHeight)
.attr("width", keyWidth)
.attr("fill", "cornflowerBlue")
.attr("opacity", opacity)
.attr("class", "key" + i);
keyGroup.append("svg:text")
.text(i)
.attr("x", keyWidth / 2)
.attr("y", arrElementHeight / 2 + 7)
.attr("opacity", opacity)
.attr("text-anchor", "middle")
.style("font-size", "22px")
.style("font-weight", "bold");
//Bucket
var valueGroup = bucket.append("svg:g")
.attr("transform", "translate(" + (width - arrElementWidth) + "," + i * (arrElementHeight + 5) + ")")
.attr("class", "element" + i)
.attr("opacity", opacity);
valueGroup.append("svg:rect")
.attr("width", arrElementWidth)
.attr("height", arrElementHeight)
.attr("fill", "cornflowerBlue");
valueGroup.append("svg:text")
.style("text-anchor", "middle")
.attr("x", arrElementWidth / 2)
.attr("y", arrElementHeight / 2 + 7)
.style("font-size", "22px")
.style("font-weight", "bold");
}
}
function highlightCode(lines, functionName) {
if (functionName)
codeDisplayManager.changeFunction(functionName);
appendCodeLines(lines, codeDisplayManager);
}
|
"use strict";
function Wall(layer, id) {
powerupjs.GameObject.call(this, layer, id);
// Some physical properties of the wall
this.strokeColor = 'none';
this.fillColor = 'none';
this.scoreFrontColor = "#FFC800";
this.scoreSideColor = "#B28C00";
this.defaultFrontColor = '#0018FF';
this.defaultSideColor = '#0010B2';
this.frontColor = this.defaultFrontColor;
this.sideColor = this.defaultSideColor;
this._minVelocity = -250;
this._minDiameterY = 200;
this._maxDiameterY = 300;
this.diameterX = 100;
this.diameterY = 200;
this.wallWidth = this.diameterX;
this.wallThickness = this.wallWidth / 9;
this.smartWall = false;
this.smartWallRate = 2;
this.initX = powerupjs.Game.size.x + 100;
this.position = this.randomHolePosition();
this.velocity = new powerupjs.Vector2(this._minVelocity, 0);
}
Wall.prototype = Object.create(powerupjs.GameObject.prototype);
Object.defineProperty(Wall.prototype, "minDiameterY",
{
get: function () {
return this._minDiameterY;
}
});
Object.defineProperty(Wall.prototype, "maxDiameterY",
{
get: function () {
return this._maxDiameterY;
}
});
Object.defineProperty(Wall.prototype, "resetXOffset",
{
get: function () {
return this.initX - this.diameterX / 2;
}
});
Object.defineProperty(Wall.prototype, "boundingBox",
{
get: function () {
return new powerupjs.Rectangle(this.position.x - this.diameterX / 2,
this.position.y - this.diameterY / 2,
this.diameterX, this.diameterY);
}
});
Wall.prototype.reset = function() {
var playingState = powerupjs.GameStateManager.get(ID.game_state_playing);
this.frontColor = this.defaultFrontColor;
this.sideColor = this.defaultSideColor;
this.diameterY = this.randomHoleSize();
this.position = this.randomHolePosition();
this.scored = false;
// Smart wall = moving hole
if (playingState.score.score >= playingState.initSmartWallScore )
this.smartWall = true;
else
this.smartWall = false;
};
Wall.prototype.update = function(delta) {
//GameObject.prototype.update.call(this,delta);
// Contains all playing objects
var playingState = powerupjs.GameStateManager.get(ID.game_state_playing);
// If wall goes off screen
if (playingState.isOutsideWorld(this)) {
this.reset();
//this.velocity = new Vector2(this._minVelocity - (20 * score.score), 0);
}
// Move the hole
if (this.smartWall)
this.moveHole(delta);
// Determine if user collides with wall.
if (this.position.x <= playingState.user.boundingBox.right &&
this.position.x > playingState.user.boundingBox.center.x) {
if (this.isColliding(playingState.user)) {
playingState.lives -= 1;
playingState.isDying = true;
}
// If no collision and wall is behind user, score it.
} else if (this.position.x <= playingState.user.boundingBox.center.x && !this.scored) {
playingState.score.score += 1;
this.frontColor = this.scoreFrontColor;
this.sideColor = this.scoreSideColor;
this.scored = true;
sounds.beep.play();
}
// Add moving hole
//this.position.y += 1;
};
Wall.prototype.draw = function() {
powerupjs.Canvas2D.drawPath(this.calculateWallPath('topFront'), this.frontColor, this.strokeColor);
powerupjs.Canvas2D.drawPath(this.calculateWallPath('holeLeft'), this.frontColor, this.strokeColor);
powerupjs.Canvas2D.drawPath(this.calculateWallPath('bottomFront'), this.frontColor, this.strokeColor);
powerupjs.Canvas2D.drawPath(this.calculateWallPath('holeSide'), this.sideColor, this.strokeColor);
};
Wall.prototype.moveHole = function(delta) {
if (this.boundingBox.bottom > powerupjs.Game.size.y ||
this.boundingBox.top < 0)
this.smartWallRate *= -1;
this.position.y += this.smartWallRate;
};
Wall.prototype.isColliding = function(user) {
var userCenter = { x : user.boundingBox.center.x,
y : user.boundingBox.center.y};
var holeTop = this.position.y - this.diameterY / 2;
var holeBottom = this.position.y + this.diameterY / 2;
var overlap = this.position.x - userCenter.x;
var theta = Math.acos(overlap / (user.width / 2));
var userTop = userCenter.y - (user.height / 2) * Math.sin(theta);
var userBottom = (user.height / 2) * Math.sin(theta) + userCenter.y;
if (userTop > holeTop && userBottom < holeBottom) {
return false;
} else {
return true;
}
};
Wall.prototype.randomHoleSize = function() {
//console.log(Math.floor(Math.random() * (this.maxDiameterY - this.minDiameterY)) + this.minDiameterY);
return Math.floor(Math.random() * (this.maxDiameterY - this.minDiameterY)) + this.minDiameterY;
};
Wall.prototype.randomHolePosition = function() {
var newY = Math.random() * (powerupjs.Game.size.y - this.diameterY) +
this.diameterY / 2;
return new powerupjs.Vector2(this.initX, newY);
};
/*Wall.prototype.calculateRandomPosition = function() {
//var calcNewY = this.calculateRandomY;
var enemy = this.root.find(ID.enemy1);
if (enemy) {
console.log("here");
var newY = null;
while (! newY || (((newY - this.diameterY / 2) <= enemy.position.y + enemy.height) &&
((newY + this.diameterY / 2) >= enemy.position.y) )) {
newY = this.calculateRandomY();
console.log(newY);
}
return new powerupjs.Vector2(this.initX, newY);
} else {
return new powerupjs.Vector2(this.initX, this.calculateRandomY());
}
};*/
Wall.prototype.calculateWallPath = function(type) {
var xPoints = [];
var yPoints = [];
var pathType = [];
// Default values
// Wall bounds
var thick = this.wallThickness;
var left = this.position.x - this.diameterX / 2;
var right = this.position.x + (this.diameterX / 2) + thick;
var shiftedCenter = left + (this.diameterX / 2) + thick;
var top = 0;
var bottom = powerupjs.Game.size.y;
// Circle bounds
var cBase = this.position.y + this.diameterY / 2;
var cTop = this.position.y - this.diameterY / 2;
var cLeft = shiftedCenter - this.diameterX / 2;
var cRight = shiftedCenter + this.diameterX / 2;
switch(type){
case "holeLeft" :
top = cTop - 5;
bottom = cBase + 5;
right = shiftedCenter;
xPoints = [left, left, right, right,
[cLeft, cLeft, right],
right, left];
yPoints = [top, bottom, bottom, cBase,
[cBase, cTop, cTop],
top, top];
pathType = ['line','line','line','bezierCurve','line', 'line'];
break;
case "holeRight" :
top = cTop - 1;
bottom = cBase + 1;
left = shiftedCenter;
xPoints = [left, left,
[cRight, cRight, left],
left, right, right, left];
yPoints = [top, cTop,
[cTop, cBase, cBase],
bottom, bottom, top, top];
pathType = ['line','bezierCurve','line', 'line', 'line', 'line'];
break;
case "holeSide" :
thick = thick;
right = shiftedCenter;
xPoints = [right - thick,
[cLeft - thick, cLeft - thick, right - thick],
right,
[cLeft, cLeft, right],
right - thick];
yPoints = [cTop,
[cTop, cBase, cBase],
cBase,
[cBase, cTop, cTop],
cTop];
pathType = ['bezierCurve','line','bezierCurve','line'];
break;
case "topFront" :
bottom = cTop;
//right = shiftedCenter + 5;
xPoints = [left, left, right, right, left];
yPoints = [top, bottom, bottom, top, top];
pathType = ['line','line','line','line'];
break;
case "bottomFront" :
top = cBase;
//right = shiftedCenter + 5;
xPoints = [left, left, right, right, left];
yPoints = [top, bottom, bottom, top, top];
pathType = ['line','line','line','line'];
break;
case "rightSide" :
right = right - 1;
left = right;
right = right + thick;
xPoints = [left, left, right, right, left];
yPoints = [top, bottom, bottom, top, top];
pathType = ['line','line','line','line'];
break;
}
return { xPoints : xPoints, yPoints : yPoints,
pathType : pathType };
};
|
### CSS 기초 - STEP4 - 레이아웃
블럭요소을 통해서 실제로 레이아웃하는 방법들을 배웁니다.
기존의 레이아웃 기법과 동시에 새로운 레이아웃 기법도 소개합니다.
#### 미디어와 레이아웃종류
- [미디어의 종류(Media)](../step4/01_media.md)
- [레이아웃 방법(Layout Type)](../step4/02_type.md)
#### 플로트 레이아웃
- [플로트(float)](../step4/03_float.md)
- [클리어(clear)](../step4/04_clear.md)
- [해즈레이아웃(haslayout)](../step4/05_haslayout.md)
#### 포지션 레이아웃
- [포지션(position)](../step4/06_position.md)
- [포지션 위치값(position direction)](../step4/07_position_direction.md)
- [제트인덱스(z-index)](../step4/08_zindex.md)
#### 플랙스 레이아웃 - 부모요소(컨테이너)
- [플랙스(flex)](../step4/09_flex.md)
- [플랙스 위치값(flex-direction)](../step4/10_flex_direction.md)
- [플랙스 줄바꿈방법(flex-wrap)](../step4/11_flex_wrap.md)
- [플랙스 단축선언(flex-flow)](12_flex_flow.md)
- [플랙스 아이템 상하정렬(align-items)](../step4/13_flex_align_items.md) - 한줄
- [플랙스 영역 상하정렬(align-content)](../step4/14_flex_align_content.md) - 멀티라인
- [플랙스 영역 배치방법(justify-content)](../step4/15_flex_justify.md)
#### 플랙스 레이아웃 - 자식요소(아이템)
- [플랙스아이템 가로비율(flex-grow)](../step4/16_flex_grow.md)
- [플랙스아이템 역가로비율(flex-shrink)](../step4/17_flex_shrink.md)
- [플랙스아이템 기본사이즈 설정(flex-basis)](../step4/18_flex_basis.md)
- [플랙스아이템 단축선언(flex)](../step4/19_flex.md)
- [플랙스아이템 상하정렬(align-self)](../step4/20_align_self.md)
- [플랙스아이템 배치(order)](../step4/21_order.md) |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Sep 25 19:59:55 CEST 2011 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package a_vcard.android.syncml.pim
</TITLE>
<META NAME="date" CONTENT="2011-09-25">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package a_vcard.android.syncml.pim";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?a_vcard/android/syncml/pim/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Package<br>a_vcard.android.syncml.pim</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../a_vcard/android/syncml/pim/package-summary.html">a_vcard.android.syncml.pim</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#a_vcard.android.syncml.pim"><B>a_vcard.android.syncml.pim</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#a_vcard.android.syncml.pim.vcard"><B>a_vcard.android.syncml.pim.vcard</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="a_vcard.android.syncml.pim"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../a_vcard/android/syncml/pim/package-summary.html">a_vcard.android.syncml.pim</A> used by <A HREF="../../../../a_vcard/android/syncml/pim/package-summary.html">a_vcard.android.syncml.pim</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../a_vcard/android/syncml/pim/class-use/PropertyNode.html#a_vcard.android.syncml.pim"><B>PropertyNode</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../a_vcard/android/syncml/pim/class-use/VBuilder.html#a_vcard.android.syncml.pim"><B>VBuilder</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../a_vcard/android/syncml/pim/class-use/VNode.html#a_vcard.android.syncml.pim"><B>VNode</B></A></B>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="a_vcard.android.syncml.pim.vcard"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../a_vcard/android/syncml/pim/package-summary.html">a_vcard.android.syncml.pim</A> used by <A HREF="../../../../a_vcard/android/syncml/pim/vcard/package-summary.html">a_vcard.android.syncml.pim.vcard</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../a_vcard/android/syncml/pim/class-use/PropertyNode.html#a_vcard.android.syncml.pim.vcard"><B>PropertyNode</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../a_vcard/android/syncml/pim/class-use/VBuilder.html#a_vcard.android.syncml.pim.vcard"><B>VBuilder</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../a_vcard/android/syncml/pim/class-use/VDataBuilder.html#a_vcard.android.syncml.pim.vcard"><B>VDataBuilder</B></A></B>
<BR>
Store the parse result to custom datastruct: VNode, PropertyNode
Maybe several vcard instance, so use vNodeList to store.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../a_vcard/android/syncml/pim/class-use/VNode.html#a_vcard.android.syncml.pim.vcard"><B>VNode</B></A></B>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?a_vcard/android/syncml/pim/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
require 'spec_helper'
require 'vigilem/win32_api/eventable'
require 'vigilem/win32_api/input_system_handler'
require 'vigilem/core/adapters/adapter'
describe Vigilem::Win32API::Eventable do
before :all do
EventableAdapter = Class.new do
include Vigilem::Core::Adapters::Adapter
include Vigilem::Win32API::Rubyized
include Vigilem::Win32API::Eventable
def initialize(lnk=Vigilem::Win32API::InputSystemHandler.new)
initialize_adapter(lnk)
self.win32_api_rubyized_source = link()
end
end
end
let(:adapt) do
EventableAdapter.new
end
describe 'has_any?' do
it 'checks peek_console_input and if the lpBuffer has any messages' do
allow(adapt).to receive(:peek_console_input) { %w(a b c) }
expect(adapt.has_any?).to be_truthy
end
it 'returns false when peek_console_input lpBuffer is empty' do
allow(adapt).to receive(:peek_console_input) { [] }
expect(adapt.has_any?).to be_falsey
end
end
describe '#read_many_nonblock' do
it 'reads many messages from the input buffer returning if it would block/stopping at limit' do
allow(adapt).to receive(:peek_console_input) { %w(a b c) }
allow(adapt).to receive(:read_console_input).with(:nLength => 1, :blocking => false) { %w(a) }
expect(adapt.read_many_nonblock).to eql(%w(a))
end
end
describe '#read_many' do
it 'reads the default amount of messages from the input buffer' do
allow(adapt).to receive(:read_console_input).with(:nLength => 1, :blocking => true) { %w(a) }
Timeout::timeout(4) {
expect(adapt.read_many).to eql(%w(a))
}
end
it 'blocks until the number passed in is reached' do
allow(adapt).to receive(:read_console_input).with(:nLength => 3, :blocking => true).and_call_original
allow(adapt.send(:link)).to receive(:ReadConsoleInput) { %w(a) }
expect do
Timeout::timeout(4) {
adapt.read_many(3)
}
end.to raise_error(Timeout::Error)
end
it 'reads many messages from the input_buffer' do
allow(adapt).to receive(:read_console_input).with(:nLength => 3, :blocking => true) { %w(a b c) }
Timeout::timeout(4) {
expect(adapt.read_many(3)).to eql(%w(a b c))
}
end
end
describe 'read_one_nonblock' do
it 'reads one message off the input buffer' do
allow(adapt).to receive(:peek_console_input) { %w(a) }
allow(adapt).to receive(:read_console_input) { %w(a) }
expect(adapt.read_one_nonblock).to eql('a')
end
it %q(doesn't block) do
allow(adapt).to receive(:peek_console_input) { [] }
expect(adapt.read_one_nonblock).to eql(nil)
end
end
describe '#read_one' do
it 'reads one message off the input buffer' do
allow(adapt).to receive(:read_console_input) { %w(a) }
expect(adapt.read_one).to eql('a')
end
it %q(blocks when no messages are in the buffer) do
allow(adapt).to receive(:read_console_input).and_call_original
allow(adapt.send(:link)).to receive(:ReadConsoleInput) { sleep 4 }
expect do
Timeout::timeout(3) do
adapt.read_one
end
end.to raise_error(Timeout::Error)
end
context 'event_loop' do
let(:eventable_adapter) do
input_sys = double('InputSystem', :GetStdHandle => 3)
@incr = 0
allow(input_sys).to receive(:PeekConsoleInputW) do |hConsoleInput, lpBuffer, nLength, lpNumberOfEventsRead|
if @incr == 0
lpBuffer.replace(Vigilem::Win32API::PINPUT_RECORD.new(3,
Vigilem::Win32API::INPUT_RECORD[Vigilem::Win32API::KEY_EVENT, {:KeyEvent => [1, 1, 70, 33, {:UnicodeChar => 97}, 32]}]
))
@incr += 1
end
1
end
allow(input_sys).to receive(:ReadConsoleInputW) do |hConsoleInput, lpBuffer, nLength, lpNumberOfEventsRead|
lpBuffer.replace(Vigilem::Win32API::PINPUT_RECORD.new(3,
Vigilem::Win32API::INPUT_RECORD[Vigilem::Win32API::KEY_EVENT, {:KeyEvent => [1, 1, 70, 33, {:UnicodeChar => 97}, 32]}]
))
1
end
EventableAdapter.new(Vigilem::Win32API::InputSystemHandler.new(input_sys))
end
it 'will return one event per event in the win32 event queue' do # to check that there is parity between the input_system and here
expect([eventable_adapter.read_one_nonblock, eventable_adapter.read_one_nonblock]).to match [
instance_of(Vigilem::Win32API::INPUT_RECORD), nil
]
end
end
end
end
|
package cmd
import (
"fmt"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"github.com/ferrariframework/ferrariserver/config"
"github.com/ferrariframework/ferrariserver/grpc/gen"
rpcservices "github.com/ferrariframework/ferrariserver/grpc/services"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
rpcPortKey = "rpc_port"
//TLS
certFileKey = "cert_file"
keyFileKey = "key_file"
tlsKey = "tls"
)
// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Starts the ferrariworker server",
Long: `Starts the ferrariworker server`,
Run: func(cmd *cobra.Command, args []string) {
port := viper.GetInt(rpcPortKey)
tls := viper.GetBool(tlsKey)
certFile := viper.GetString(certFileKey)
keyFile := viper.GetString(keyFileKey)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
grpclog.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
if tls {
creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
if err != nil {
grpclog.Fatalf("Failed to generate credentials %v", err)
}
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
grpcServer := grpc.NewServer(opts...)
gen.RegisterJobServiceServer(grpcServer, rpcservices.NewJobService(config.JobService()))
grpcServer.Serve(lis)
},
}
func init() {
RootCmd.AddCommand(serveCmd)
serveCmd.Flags().IntP(rpcPortKey, "r", 4051, "Port for the rpc service")
serveCmd.Flags().BoolP(tlsKey, "t", false, "Connection uses TLS if true, else plain TCP")
serveCmd.Flags().StringP(certFileKey, "c", "server.pem", "The TLS cert file")
serveCmd.Flags().StringP(keyFileKey, "k", "server.key", "The TLS key file")
viper.BindPFlag(rpcPortKey, serveCmd.Flags().Lookup(rpcPortKey))
viper.BindPFlag(tlsKey, serveCmd.Flags().Lookup(tlsKey))
viper.BindPFlag(certFileKey, serveCmd.Flags().Lookup(certFileKey))
viper.BindPFlag(keyFileKey, serveCmd.Flags().Lookup(keyFileKey))
}
|
package iso20022
// Characteristics of the ownership of an investment account.
type InvestmentAccountOwnershipInformation4 struct {
// Organised structure that is set up for a particular purpose, eg, a business, government body, department, charity, or financial institution.
Organisation *Organisation3 `xml:"Org"`
// Human entity, as distinguished from a corporate entity (which is sometimes referred to as an 'artificial person').
IndividualPerson *IndividualPerson11 `xml:"IndvPrsn"`
// Status of an identity check to prevent money laundering. This includes the counter-terrorism check.
MoneyLaunderingCheck *MoneyLaunderingCheck1Code `xml:"MnyLndrgChck,omitempty"`
// Status of an identity check to prevent money laundering. This includes the counter-terrorism check.
ExtendedMoneyLaunderingCheck *Extended350Code `xml:"XtndedMnyLndrgChck,omitempty"`
// Percentage of ownership or beneficiary ownership of the shares/units in the account. All subsequent subscriptions and or redemptions will be allocated using the same percentage.
OwnershipBeneficiaryRate *PercentageRate `xml:"OwnrshBnfcryRate,omitempty"`
// Unique identification, as assigned by an organisation, to unambiguously identify a party.
ClientIdentification *Max35Text `xml:"ClntId,omitempty"`
// Indicates whether an owner of an investment account may benefit from a fiscal exemption or amnesty for instance for declaring overseas investments.
FiscalExemption *YesNoIndicator `xml:"FsclXmptn,omitempty"`
// Indicates whether the account owner signature is required to authorise transactions on the account.
SignatoryRightIndicator *YesNoIndicator `xml:"SgntryRghtInd,omitempty"`
// Information related to the party profile to be inserted or deleted.
ModifiedInvestorProfileValidation []*ModificationScope11 `xml:"ModfdInvstrPrflVldtn,omitempty"`
}
func (i *InvestmentAccountOwnershipInformation4) AddOrganisation() *Organisation3 {
i.Organisation = new(Organisation3)
return i.Organisation
}
func (i *InvestmentAccountOwnershipInformation4) AddIndividualPerson() *IndividualPerson11 {
i.IndividualPerson = new(IndividualPerson11)
return i.IndividualPerson
}
func (i *InvestmentAccountOwnershipInformation4) SetMoneyLaunderingCheck(value string) {
i.MoneyLaunderingCheck = (*MoneyLaunderingCheck1Code)(&value)
}
func (i *InvestmentAccountOwnershipInformation4) SetExtendedMoneyLaunderingCheck(value string) {
i.ExtendedMoneyLaunderingCheck = (*Extended350Code)(&value)
}
func (i *InvestmentAccountOwnershipInformation4) SetOwnershipBeneficiaryRate(value string) {
i.OwnershipBeneficiaryRate = (*PercentageRate)(&value)
}
func (i *InvestmentAccountOwnershipInformation4) SetClientIdentification(value string) {
i.ClientIdentification = (*Max35Text)(&value)
}
func (i *InvestmentAccountOwnershipInformation4) SetFiscalExemption(value string) {
i.FiscalExemption = (*YesNoIndicator)(&value)
}
func (i *InvestmentAccountOwnershipInformation4) SetSignatoryRightIndicator(value string) {
i.SignatoryRightIndicator = (*YesNoIndicator)(&value)
}
func (i *InvestmentAccountOwnershipInformation4) AddModifiedInvestorProfileValidation() *ModificationScope11 {
newValue := new(ModificationScope11)
i.ModifiedInvestorProfileValidation = append(i.ModifiedInvestorProfileValidation, newValue)
return newValue
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<!-- 引入 echarts.js -->
<script src="//cdn.bootcss.com/echarts/3.6.2/echarts.min.js"></script>
<script src="js/charts_loader.js" type="text/javascript"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 800px;height:600px;"></div>
<script>
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
x轴:年份 <br/>
y轴:评分 <br/>
图元size: 票房 <br/>
图例:导演 <br/>
VisualMap: 票房、评分
</body>
</html>
|
<?php
// AT MINIMUM UNCOMMENT AND CONFIGURE ONE OF THE FOLLOWING OPTIONS:
// OPTION ONE: READ MYSQL CONFIG FROM config.lua - RECOMMENDED
define('TFS_CONFIG', '/home/vagrant/forgottenserver/config.lua');
// OPTION TWO: SPECIFY MYSQL CONNECTION DETAILS HERE
// define('TFS_CONFIG', array('mysqlHost' => '127.0.0.1', 'mysqlDatabase' => 'tfs', 'mysqlUser' => 'tfs', 'mysqlPass' => 'tfs'));
// THIS OPTION IS DISCOURAGED AS SOME CODE MIGHT DEPEND ON OTHER VALUES FROM TFS CONFIG
// IF YOU WANT TO CHANGE SOMETHING ELSE, BE SMART AND FOLLOW THE PATTERN
define('CORS_ALLOW_ORIGIN', '*');
define('ENABLE_DEBUG', true);
|
=begin
#The Plaid API
#The Plaid REST API. Please see https://plaid.com/docs/api for more details.
The version of the OpenAPI document: 2020-09-14_1.79.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.0
=end
require 'date'
require 'time'
module Plaid
# Defines the response schema for `/transfer/get`
class TransferGetResponse
attr_accessor :transfer
# A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive.
attr_accessor :request_id
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'transfer' => :'transfer',
:'request_id' => :'request_id'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'transfer' => :'Transfer',
:'request_id' => :'String'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::TransferGetResponse` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::TransferGetResponse`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'transfer')
self.transfer = attributes[:'transfer']
end
if attributes.key?(:'request_id')
self.request_id = attributes[:'request_id']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @transfer.nil?
invalid_properties.push('invalid value for "transfer", transfer cannot be nil.')
end
if @request_id.nil?
invalid_properties.push('invalid value for "request_id", request_id cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @transfer.nil?
return false if @request_id.nil?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
transfer == o.transfer &&
request_id == o.request_id
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[transfer, request_id].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = Plaid.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
|
export default function createRegistry(repositories) {
const storage = { ...repositories };
const registry = {
register(repositoryName, repository) {
storage[repositoryName] = repository;
return registry;
},
has(repositoryName) {
return !!storage[repositoryName];
},
get(repositoryName) {
return storage[repositoryName];
},
reduce(reducer, initialValue) {
return Object
.keys(storage)
.reduce((previous, repositoryName) => reducer(
previous,
storage[repositoryName],
repositoryName,
), initialValue);
},
};
return registry;
}
|
import-module au
# cd .\copyfilename
$releases = 'http://www.bullzip.com/download.php'
function global:au_SearchReplace {
@{
'tools\chocolateyInstall.ps1' = @{
"(^[$]url32\s*=\s*)('.*')" = "`$1'$($Latest.URL32)'"
"(^[$]checksum32\s*=\s*)('.*')" = "`$1'$($Latest.Checksum32)'"
}
}
}
function global:au_GetLatest {
$download_page = Invoke-WebRequest -Uri $releases -UseBasicParsing
$re = 'copyfilename.*.exe'
$url = $download_page.links | ? href -match $re | select -First 1 -expand href
$url32 = 'http://www.bullzip.com/' + $url
$version = (($url.Substring(26)).replace('.exe','') -replace '_','.')
return @{ URL32 = $url32; Version = $version }
}
update |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 24 16:25:41 2016
@author: pavel
"""
from gi.repository import Gtk
import parameter_types as ptypes
from logger import Logger
logger = Logger.get_logger()
#
import gobject
gobject.threads_init()
#decorator is used to update gtk objects from another thread
def idle_add_decorator(func):
def callback(*args):
gobject.idle_add(func, *args)
return callback
class GTK_Wrapper(object):
def get_gui_object(self):
raise NotImplementedError()
@staticmethod
def get_wrapper(obj):
wrapper = TYPE_MATCHES.get(type(obj), GTK_ReadOnlyWrapper)
return wrapper(obj)
class GTK_ReadOnlyWrapper(GTK_Wrapper):
def __init__(self, obj):
self.label = Gtk.Label()
self.label.set_text(repr(obj))
def get_gui_object(self):
return self.label
class GTK_ParamWrapper(GTK_Wrapper):
def __init__(self, parameter):
self.parameter = parameter
self.container = Gtk.Box(spacing=2)
self.container.set_homogeneous(False)
self._set_name(parameter.get_name())
self.param_gui_obj = None
self._set_gui_obj()
self._append_gui_obj()
def get_gui_object(self):
return self.container
def _set_name(self, name):
name_label = Gtk.Label()
name_label.set_text(name)
self.container.pack_start(name_label, True, True, 0)
def _append_gui_obj(self):
if self.param_gui_obj is not None:
self.container.pack_start(self.param_gui_obj, True, True, 0)
self.param_gui_obj.set_hexpand(True)
#override this with obj and add call
# also set on update callback
def _set_gui_obj(self):
self.param_gui_obj = None
# override this with method
def _on_update(self, widget, parameter_obj):
logger.to_log(widget, parameter_obj)
class GTK_ParamCheckBtn(GTK_ParamWrapper):
def _set_gui_obj(self):
self.param_gui_obj = Gtk.CheckButton()
self.param_gui_obj.set_active(self.parameter.get_val())
self.param_gui_obj.connect("toggled", self._on_update, self.parameter)
def _on_update(self, widget, param):
new_val = widget.get_active()
param.set_val(new_val)
class GTK_ParamTextBox(GTK_ParamWrapper):
def _set_gui_obj(self):
self.param_gui_obj = Gtk.Entry()
self.param_gui_obj.set_text(str(self.parameter.get_val()))
self.param_gui_obj.connect("changed", self._on_update, self.parameter)
def _on_update(self, widget, param):
new_val = widget.get_text()
if not param.set_val(new_val):
#if impossible to set new value restore previous one
widget.set_text(str(param.get_val()))
logger.to_log(new_val, widget)
class GTK_ParamList(GTK_ParamWrapper):
def _set_gui_obj(self):
#value to select by default
active_val = self.parameter.get_val()
active_ind = 0
counter = 0
store = Gtk.ListStore(str)
for val in self.parameter.allowed_vals():
store.append([str(val)])
if val == active_val:
active_ind = counter
counter += 1
self.param_gui_obj = Gtk.ComboBox.new_with_model_and_entry(store)
self.param_gui_obj.set_entry_text_column(0)
self.param_gui_obj.set_active(active_ind)
self.param_gui_obj.connect("changed", self._on_update, self.parameter)
def _on_update(self, combobox, param):
model = combobox.get_model()
active = combobox.get_active()
if active is not None and active >= 0:
new_val = model[active][0]
param.set_val(new_val)
logger.to_log(new_val, combobox)
class GTK_ParamSlider(GTK_ParamWrapper):
from math import log10
NUM_STEPS = 100
ORIENTATION = Gtk.Orientation.HORIZONTAL
def _set_gui_obj(self):
#(initial value, min value, max value,
# step increment - press cursor keys to see!,
# page increment - click around the handle to see!,
init_val = self.parameter.get_val()
min_val, max_val = self.parameter.get_range()
step = float(max_val - min_val) / GTK_ParamSlider.NUM_STEPS
adj = Gtk.Adjustment(init_val, min_val, max_val, step, step, 0)
self.param_gui_obj = Gtk.Scale(orientation=GTK_ParamSlider.ORIENTATION,
adjustment = adj)
self.param_gui_obj.connect("value-changed", self._on_update, self.parameter)
self.param_gui_obj.set_digits(self._num_digits(step))
def _on_update(self, widget, param):
new_val = widget.get_value()
param.set_val(new_val)
logger.to_log(new_val, widget)
#print dir(self)
#print dir(super(GTK_ParamSlider, self))
#print dir(param)
#new_val = self.adj.get_value()
#print new_val
def _num_digits(self, step):
#return the number of decimal places to display based on step
remainder = abs(step - round(step))
remainder_log = - GTK_ParamSlider.log10(remainder)
return max(1, int(remainder_log))
TYPE_MATCHES = {ptypes.Parameter:GTK_ParamTextBox,
ptypes.BoolParameter:GTK_ParamCheckBtn,
ptypes.ListParameter:GTK_ParamList,
ptypes.RangeParameter:GTK_ParamSlider,
ptypes.RangeParameterFit:GTK_ParamSlider} |
/**
* Created by cc on 15-8-1.
*/
angular.module('app.services').factory('loginWithCode', ['app.api.http', '$ionicPopup','Storage','ENV','$state', function (http, $ionicPopup,Storage,ENV,$state) {
var dataJSON = {}
function login(){
if(ENV.code){
http.get('loginWithCode', {code:ENV.code}).success(function (data, status, headers, config) {
console.log("loginWithCode:回调返回数据:"+JSON.stringify(data))
if(data.status == 200){
openIdLogin(data)
}
})
}
}
function openIdLogin(data){
if(data.user){
Storage.setUserInfo(data.user);
}
if(data.authInfo){
Storage.setAccessToken(data.authInfo);
}
if(data.openId){
Storage.set("openId",{openId:data.openId})
dataJSON['openId'] = data.openId
}
//自动登陆后,如果在登陆,注册,或忘记密码页面则跳到个人中心
if(data.user && data.authInfo &&
($state.$current.name == 'forgetPass' ||
$state.$current.name == 'login' ||
$state.$current.name == 'signup')){
$state.go('tabs.usercenterMine')
}
}
return {
login:function(){
login()
},
addOpenId:function(params){
console.log("addOpenId:"+JSON.stringify(params))
return angular.extend({openId:dataJSON.openId},params)
}
}
}]); |
<?php
/**
* @package Oink.Services.Interfaces
*/
interface ICallbackService {
/**
* Method to authenticate parnet or child and returns a token to use in subsequent calls
* @return Object containing information about call status, the user type and the token
*/
public function GetCallbackTransactionStatus();
/**
* Method to authenticate parnet or child and returns a token to use in subsequent calls
* @return Object containing information about call status, the user type and the token
*/
public function GetCallbackAddressInformation();
}
?> |
# boot
netboot test
|
module Clockpuncher
module Freshbooks
class TimeEntryRequest < Request
self.resource = :time_entry
self.action = :get
property :time_entry_id, :required => true, :from => :id
end
end
end
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>What Sunrise Is It?</title>
<meta name="description" content="What Sunrise Is It? See what our Sunrise looks like from Earth right now."/>
<meta name="mobile-web-app-capable" content="yes">
<link rel="stylesheet" type="text/css" href="assets/style.css"/>
<link rel="icon" sizes="128x128" href="assets/favicon.png">
<script src="assets/script.js" defer></script>
</head>
<body>
<h2 class="not-centered" id="time">...</h2>
<div id="image"></div>
<div id="next-image"></div>
<a href="https://github.com/rthbound/WhatSunriseIsIt" title="Fork this project on GitHub"><img id="github-badge" src="assets/fork.png" alt="Fork this project on GitHub" /></a>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-41441385-1");
pageTracker._trackPageview();
} catch(err) {}
</script>
</body>
</html>
|
# StarOS-cactipy
Cisco StarOS poll scripts. Output is consumed by Cacti rrdtool to be parsed and displayed in Cacti dashboard.
|
lookup = {}
lookup = dict()
lookup = {'age': 42, 'loc': 'Italy'}
lookup = dict(age=42, loc='Italy')
print(lookup)
print(lookup['loc'])
lookup['cat'] = 'cat'
if 'cat' in lookup:
print(lookup['cat'])
class Wizard:
# This actually creates a key value dictionary
def __init__(self, name, level):
self.level = level
self.name = name
# There is an implicit dictionary that stores this data
gandolf = Wizard('Gladolf', 42)
print(gandolf.__dict__)
# The takeway is that all objects are built around the concept of dictionary data structures
# Here is another example
import collections
User = collections.namedtuple('User', 'id, name, email')
users = [
User(1, 'user1', 'user1@test.com'),
User(2, 'user2', 'user2@test.com'),
User(3, 'user3', 'user3@test.com'),
]
lookup = dict()
for u in users:
lookup[u.email] = u
print(lookup['user2@test.com']) |
import React, { PropTypes, Component } from 'react';
import { View, ScrollView, Text, TouchableOpacity, Keyboard, ListView, Platform,
AsyncStorage } from 'react-native';
import getEmojiData from './data';
import ScrollableTabView from 'react-native-scrollable-tab-view';
const STORAGE_KEY = 'RNEI-latest';
class EmojiSelector extends Component {
constructor(props) {
super(props);
this.state = {
visible: props.defaultVisible || false,
height: (props.defaultVisible || false) ? props.containerHeight : 0,
emoji: [],
latest: [],
counts: {}
};
}
componentWillMount() {
this.setState({
emoji: getEmojiData()
});
if (this.props.history) {
AsyncStorage.getItem(STORAGE_KEY).then( value => {
if (value) {
var counts = JSON.parse(value);
this.setState({
counts: counts || {}
}, () => {
this.refreshLatest()
})
}
});
}
}
saveCounts() {
if (this.props.history) {
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(this.state.counts));
}
}
render() {
const { headerStyle, containerBackgroundColor, emojiSize, onPick, tabBorderColor } = this.props;
return (
<View style={[{height: this.state.height, overflow: 'hidden'}]}>
<ScrollableTabView
tabBarUnderlineStyle={{
backgroundColor: this.props.tabBorderColor
}}
tabBarTextStyle={styles.tabBarText}
style={styles.picker}
>
{this.state.latest.length?
<EmojiCategory
key={'latest'}
tabLabel={'🕰'}
emojiSize={emojiSize}
items={this.state.latest}
onPick={this.onPress.bind(this)}
/>
:null}
{this.state.emoji.map((category, idx) => (
<EmojiCategory
key={idx}
tabLabel={category.items[0]}
headerStyle={headerStyle}
emojiSize={emojiSize}
name={category.category}
items={category.items}
onPick={this.onPress.bind(this)}
/>
))}
</ScrollableTabView>
</View>
);
}
onPress(em) {
if (this.props.onPick) {
this.props.onPick(em);
} else if (this.onPick) {
this.onPick(em);
}
this.increaseCount(em);
}
show() {
this.setState({visible: true, height: this.props.containerHeight});
}
hide() {
this.setState({visible: false, height: 0});
}
increaseCount(em) {
if (!this.props.history) return;
var counts = this.state.counts;
if (!counts[em]) {
counts[em] = 0;
}
counts[em] ++ ;
this.setState({
counts
}, () => {
this.refreshLatest();
this.saveCounts();
})
}
refreshLatest() {
if (!this.props.history) return;
var latest = this.state.latest;
var counts = this.state.counts;
var sortable = [];
Object.keys(counts).map(em => {
sortable.push([em, counts[em]]);
});
sortable.sort((a, b) => {
return b[1] - a[1];
});
latest = sortable.map(s => {
return s[0];
});
this.setState({
latest
})
}
}
EmojiSelector.propTypes = {
onPick: PropTypes.func,
headerStyle: PropTypes.object,
containerHeight: PropTypes.number.isRequired,
containerBackgroundColor: PropTypes.string.isRequired,
emojiSize: PropTypes.number.isRequired,
};
EmojiSelector.defaultProps = {
containerHeight: 240,
containerBackgroundColor: 'rgba(0, 0, 0, 0.1)',
tabBorderColor: "#09837d",
emojiSize: 40,
history: true
};
class EmojiCategory extends Component {
constructor(props) {
super(props);
this.state={
items:[...props.items]
};
}
componentDidMount() {
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
dataSource: ds.cloneWithRows(this.props.items)
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.items!=this.state.items) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(nextProps.items),
items: [...nextProps.items]
});
}
}
render() {
if (!this.state.dataSource) {
return null;
}
const { emojiSize, name, items, onPick } = this.props;
return (
<View style={styles.categoryTab}>
<ListView contentContainerStyle={styles.categoryItems}
dataSource={this.state.dataSource}
renderRow={this._renderRow.bind(this)}
initialListSize={1000}
/>
</View>
);
}
_renderRow(item) {
var size = this.props.emojiSize;
// const fontSize = Platform.OS == 'android' ? size / 5 * 3 : size / 4 * 3;
const fontSize = Platform.OS == 'android' ? size / 4 * 3 : size / 4 * 3;
const width = Platform.OS == 'android' ? size + 8 : size;
return (
<TouchableOpacity style={{ flex: 0, height: size, width }} onPress={() => this.props.onPick(item)}>
<View style={{ flex: 0, height: size, width, justifyContent: 'center' }}>
<Text style={{ flex: 0, fontSize, paddingBottom: 2, color: 'black' }}>
{item}
</Text>
</View>
</TouchableOpacity>
)
}
}
const styles = {
picker: {
// flex: 1,
borderTopWidth: 1,
borderTopColor: "#ddd",
},
categoryTab: {
flex: 1,
paddingHorizontal: 5,
justifyContent: 'center'
// paddingLeft: Platform.OS=='android' ? 20 : 5,
// paddingTop: 42,
},
categoryItems: {
// flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
},
tabBarText: {
fontSize: Platform.OS == 'android' ? 26 : 24,
}
};
export default EmojiSelector;
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('course_selection', '0018_auto_20150830_0319'),
]
operations = [
migrations.AlterUniqueTogether(
name='friend_relationship',
unique_together=None,
),
migrations.RemoveField(
model_name='friend_relationship',
name='from_user',
),
migrations.RemoveField(
model_name='friend_relationship',
name='to_user',
),
migrations.RemoveField(
model_name='nice_user',
name='friends',
),
migrations.DeleteModel(
name='Friend_Relationship',
),
]
|
# Event Model
JavaScript UI and DOM homeworks
## Task 1
Create a function that takes an id or DOM element and:
* If an id is provided, select the element
* Finds all elements with class `button` or `content` within the provided element
* Change the content of all `.button` elements with "hide"
* When a `.button` is clicked:
* Find the topmost `.content` element, that is before another `.button` and:
* If the `.content` is visible:
* Hide the `.content`
* Change the content of the `.button` to "show"
* If the `.content` is hidden:
* Show the `.content`
* Change the content of the `.button` to "hide"
* If there isn't a `.content` element **after the clicked `.button`** and **before other `.button`**, do nothing
* Throws if:
* The provided DOM element is non-existant
* The id is neither a string nor a DOM element
|
# == Schema Information
#
# Table name: follows
#
# id :integer not null, primary key
# follower_type :string(255)
# follower_id :integer
# followable_type :string(255)
# followable_id :integer
# created_at :datetime
#
class Follow < Socialization::ActiveRecordStores::Follow
end
|
from django.conf.urls import url
from .views import (
semseterResultxlsx,
)
urlpatterns=[
url(r'^semester-xlsx/(?P<collegeCode>\d+)/(?P<branchCode>\d+)/(?P<yearOfJoining>\d+)/(?P<semester>\d+)/$',semseterResultxlsx,name='semseterResultxlsx')
]
|
<?php
namespace spec\PSB\Core\Persistence;
use PhpSpec\ObjectBehavior;
use PSB\Core\Persistence\EnabledPersistence;
use PSB\Core\Persistence\StorageType;
use spec\PSB\Core\Persistence\EnabledPersistenceSpec\TestDefinition;
/**
* @mixin EnabledPersistence
*/
class EnabledPersistenceSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->beConstructedWith(new TestDefinition());
$this->shouldHaveType('PSB\Core\Persistence\EnabledPersistence');
}
function it_contains_the_class_name_set_at_construction(TestDefinition $definition)
{
$this->beConstructedWith($definition);
$this->getDefinition()->shouldReturn($definition);
}
function it_contains_the_storage_type_set_at_construction()
{
$this->beConstructedWith(new TestDefinition(), StorageType::OUTBOX());
$this->getSelectedStorageType()->shouldBeLike(StorageType::OUTBOX());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NumberText;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
int number = 123;
Console.WriteLine(number.ToText());
int number1 = 123123;
Console.WriteLine(number1.ToText());
int number2 = 123;
Console.WriteLine(number2.ToText(StringLanguage.English));
int number3 = 123000;
Console.WriteLine(number3.ToText(StringLanguage.English));
Console.ReadLine();
}
}
}
|
#import "MOBProjection.h"
@interface MOBProjectionEPSG5786 : MOBProjection
@end
|
class G5::Jobbing::JobRetriever
include G5::Jobbing::JobFetcher
attr_accessor :location_setting_urns
def initialize(params={})
self.location_setting_urns = params[:location_setting_urns]
end
def current
fetch_get jobs_url_for_locations
end
def perform
warn "[DEPRECATION] `perform` is deprecated. Please use `current` instead."
current
end
def latest_successful
query_options = {
state: "completed_with_no_errors",
location_setting_urn: locations_as_parameter,
distinct_attr: "location_setting_urn"
}
fetch_get(jobs_base_url, query_options)
end
def jobs_url_for_locations
"#{jobs_base_url}?current=true&location_setting_urn=#{locations_as_parameter}"
end
def locations_as_parameter
"[#{self.location_setting_urns.join(',')}]"
end
end
|
<?php require_once __DIR__ . '/../vendor/autoload.php'; ?>
<?php $minifier = (new \Minifine\Factory())->build(__DIR__, true); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Minifine</title>
<?= $minifier->css(['/css/bootstrap.min.css', '/css/custom.css'], '/css/styles.min.css'); ?>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Minifine</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Documentation <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/documentation/installation.php">Installation</a></li>
<li><a href="/documentation/basic-usage.php">Basic usage</a></li>
<li><a href="/documentation/advanced-usage.php">Advanced usage</a></li>
<li class="divider"></li>
<li><a href="/documentation/contributing.php">Contributing</a></li>
</ul>
</li>
<li><a href="/minify-js-and-css-development.php">Development environment example</a></li>
<li><a href="/minify-js-and-css-production.php">Production environment example</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="https://github.com/PeeHaa/Minifine" target="_blank"><span class="hidden-sm hidden-md hidden-lg">Project on GitHub </span><span class="glyphicon glyphicon-cloud-download"></span></a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<section>
<div class="row">
<div class="col-lg-12">
<h1>Minifine</h1>
<p>Minifine combines and minifies your javascript, css and html files used in your web application on the fly.</p>
</div>
</div>
</section>
<section>
<div class="row">
<div class="col-lg-12">
<h2>Usage</h2>
<p>To start using using Minifine using the default minifiers simply use the factory to create a new Minifine instance:</p>
<code>$minifier = (new \Minifine\Factory())->build(__DIR__, true);</code>
<p>To combine and minify for example multiple stylesheet simply run the following code:</p>
<code><?= $minifier->css(['/css/bootstrap.min.css', '/css/custom.css'], '/css/min.css'); ?></code>
<p>Combining and minifying javascript files works in exactly the same way:</p>
<code><?= $minifier->js(['/js/bootstrap.min.js', '/js/custom.js'], '/js/min.js'); ?></code>
</div>
</div>
</section>
<section>
<div class="row">
<div class="col-lg-12">
<h2>Examples</h2>
<p><a href="/minify-js-and-css-development.php">Minifiy JS and CSS on development environments</a></p>
<p><a href="/minify-js-and-css-production.php">Minifiy JS and CSS on production environments</a></p>
</div>
</div>
</section>
</div>
<?= $minifier->js(['/js/jquery-1.11.2.min.js', '/js/bootstrap.min.js', '/js/custom.js'], '/js/main.min.js'); ?>
</body>
</html>
|
{% extends request.base_template %}
{% load i18n %}
{% block page_title %} {% trans "Privacy" %} - {% endblock %}
{% block unsupported_browser_warning %}{% endblock %}
{% block content %}
<h1>{% trans "Privacy Policy" %}</h1>
<p>{% trans "TODO: get content" %}</p>
{% endblock %} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AssaultBird2454.VPTU.ServerConsole
{
public partial class Administration : Form
{
public Administration()
{
InitializeComponent();
}
}
}
|
using Harmony;
namespace ResourceReplacer {
public static class Patcher {
private const string HarmonyId = "boformer.ResourceReplacer";
public static void Apply() {
HarmonyInstance.Create(HarmonyId).PatchAll(typeof(Patcher).Assembly);
}
public static void Revert() {
HarmonyInstance.Create(HarmonyId).UnpatchAll(HarmonyId);
}
}
}
|
//
//
//
#include "network.hpp"
#include "session.hpp"
namespace led_d
{
network_t::network_t (asio::io_service &io_service,
core::port_t::value_t port,
queue_t &queue)
: m_acceptor (io_service, asio::ip::tcp::endpoint (asio::ip::tcp::v4 (), port)),
m_socket (io_service),
m_queue (queue)
{
do_accept ();
}
void network_t::do_accept ()
{
m_acceptor.async_accept
(m_socket,
[this] (std::error_code err_code)
{
if (!err_code) {
std::make_shared<session_t>(std::move (m_socket), m_queue)->start ();
}
do_accept ();
}
);
}
} // namespace led_d
|
require File.expand_path('spec_helper', File.dirname(__FILE__))
require File.expand_path('model_factory', File.dirname(__FILE__))
module ModelMatchers
class HavePage
def initialize(path)
@category = path
end
def matches?(article)
@article = article
article.categories.map { |c| c.path }.include?(@category)
end
def failure_message
"expected '#{@article.path}' to be assigned to #{@category}"
end
def negative_failure_message
"'#{@article.path}' should not be assigned to #{@category}"
end
end
def be_in_category(path)
HavePage.new(path)
end
end
shared_context "Page testing" do
include Webrat::Matchers
def create_page(options)
super(options.merge(ext: @extension))
end
before(:each) do
stub_configuration
end
after(:each) do
remove_temp_directory
Nesta::FileModel.purge_cache
end
end
shared_examples_for "Page" do
include ModelFactory
include ModelMatchers
it "should be findable" do
create_page(heading: 'Apple', path: 'the-apple')
Nesta::Page.find_all.should have(1).item
end
it "should return the filename for a path" do
create_page(heading: 'Banana', path: 'banana')
Nesta::Page.find_file_for_path('banana').should =~ /banana.#{@extension}$/
end
it "should return nil for files that don't exist" do
Nesta::Page.find_file_for_path('foobar').should be_nil
end
it "should find by path" do
create_page(heading: 'Banana', path: 'banana')
Nesta::Page.find_by_path('banana').heading.should == 'Banana'
end
it "should find index page by path" do
create_page(heading: 'Banana', path: 'banana/index')
Nesta::Page.find_by_path('banana').heading.should == 'Banana'
end
it "should respond to #parse_metadata, returning hash of key/value" do
page = create_page(heading: 'Banana', path: 'banana')
metadata = page.parse_metadata('My key: some value')
metadata['my key'].should == 'some value'
end
it "should be parseable if metadata is invalid" do
dodgy_metadata = "Key: value\nKey without value\nAnother key: value"
create_page(heading: 'Banana', path: 'banana') do |path|
text = File.read(path)
File.open(path, 'w') do |file|
file.puts(dodgy_metadata)
file.write(text)
end
end
Nesta::Page.find_by_path('banana')
end
describe "for home page" do
it "should set title to heading" do
create_page(heading: 'Home', path: 'index')
Nesta::Page.find_by_path('/').title.should == 'Home'
end
it "should respect title metadata" do
create_page(path: 'index', metadata: { 'title' => 'Specific title' })
Nesta::Page.find_by_path('/').title.should == 'Specific title'
end
it "should set title to site title by default" do
create_page(path: 'index')
Nesta::Page.find_by_path('/').title.should == 'My blog'
end
it "should set permalink to empty string" do
create_page(path: 'index')
Nesta::Page.find_by_path('/').permalink.should == ''
end
it "should set abspath to /" do
create_page(path: 'index')
Nesta::Page.find_by_path('/').abspath.should == '/'
end
end
it "should not find nonexistent page" do
Nesta::Page.find_by_path("no-such-page").should be_nil
end
it "should ensure file exists on instantiation" do
lambda {
Nesta::Page.new("no-such-file")
}.should raise_error(Sinatra::NotFound)
end
it "should reload cached files when modified" do
create_page(path: "a-page", heading: "Version 1")
now = Time.now
File.stub(:mtime).and_return(now - 1)
Nesta::Page.find_by_path("a-page")
create_page(path: "a-page", heading: "Version 2")
File.stub(:mtime).and_return(now)
Nesta::Page.find_by_path("a-page").heading.should == "Version 2"
end
it "should have default priority of 0 in category" do
page = create_page(metadata: { 'categories' => 'some-page' })
page.priority('some-page').should == 0
page.priority('another-page').should be_nil
end
it "should read priority from category metadata" do
page = create_page(metadata: {
'categories' => ' some-page:1, another-page , and-another :-1 '
})
page.priority('some-page').should == 1
page.priority('another-page').should == 0
page.priority('and-another').should == -1
end
describe "with assigned pages" do
before(:each) do
@category = create_category
create_article(heading: 'Article 1', path: 'article-1')
create_article(
heading: 'Article 2',
path: 'article-2',
metadata: {
'date' => '30 December 2008',
'categories' => @category.path
}
)
@article = create_article(
heading: 'Article 3',
path: 'article-3',
metadata: {
'date' => '31 December 2008',
'categories' => @category.path
}
)
@category1 = create_category(
path: 'category-1',
heading: 'Category 1',
metadata: { 'categories' => @category.path }
)
@category2 = create_category(
path: 'category-2',
heading: 'Category 2',
metadata: { 'categories' => @category.path }
)
@category3 = create_category(
path: 'category-3',
heading: 'Category 3',
metadata: { 'categories' => "#{@category.path}:1" }
)
end
it "should find articles" do
@category.articles.should have(2).items
end
it "should order articles by reverse chronological order" do
@category.articles.first.path.should == @article.path
end
it "should find pages" do
@category.pages.should have(3).items
end
it "should sort pages by priority" do
@category.pages.index(@category3).should == 0
end
it "should order pages by heading if priority not set" do
pages = @category.pages
pages.index(@category1).should < pages.index(@category2)
end
it "should not find pages scheduled in the future" do
future_date = (Time.now + 172800).strftime("%d %B %Y")
article = create_article(heading: "Article 4",
path: "foo/article-4",
metadata: { "date" => future_date })
Nesta::Page.find_articles.detect{|a| a == article}.should be_nil
end
end
describe "with pages in draft" do
before(:each) do
@category = create_category
@draft = create_page(heading: 'Forthcoming content',
path: 'foo/in-draft',
metadata: {
'categories' => @category.path,
'flags' => 'draft'
})
Nesta::App.stub(:production?).and_return(true)
end
it "should not find assigned drafts" do
@category.pages.should_not include(@draft)
end
it "should not find drafts by path" do
Nesta::Page.find_by_path('foo/in-draft').should be_nil
end
end
describe "when finding articles" do
before(:each) do
create_article(heading: "Article 1", path: "article-1")
create_article(heading: "Article 2",
path: "article-2",
metadata: { "date" => "31 December 2008" })
create_article(heading: "Article 3",
path: "foo/article-3",
metadata: { "date" => "30 December 2008" })
end
it "should only find pages with dates" do
articles = Nesta::Page.find_articles
articles.size.should > 0
Nesta::Page.find_articles.each { |page| page.date.should_not be_nil }
end
it "should return articles in reverse chronological order" do
article1, article2 = Nesta::Page.find_articles[0..1]
article1.date.should > article2.date
end
end
it "should be able to find parent page" do
category = create_category(path: 'parent')
article = create_article(path: 'parent/child')
article.parent.should == category
end
describe "(with deep index page)" do
it "should be able to find index parent" do
home = create_category(path: 'index', heading: 'Home')
category = create_category(path: 'parent')
category.parent.should == home
home.parent.should be_nil
end
it "should be able to find parent of index" do
category = create_category(path: "parent")
index = create_category(path: "parent/child/index")
index.parent.should == category
end
it "should be able to find permalink of index" do
index = create_category(path: "parent/child/index")
index.permalink.should == 'child'
end
end
describe "(with missing nested page)" do
it "should consider grandparent to be parent" do
grandparent = create_category(path: 'grandparent')
child = create_category(path: 'grandparent/parent/child')
child.parent.should == grandparent
end
it "should consider grandparent home page to be parent" do
home = create_category(path: 'index')
child = create_category(path: 'parent/child')
child.parent.should == home
end
end
describe "when assigned to categories" do
before(:each) do
create_category(heading: "Apple", path: "the-apple")
create_category(heading: "Banana", path: "banana")
@article = create_article(
metadata: { "categories" => "banana, the-apple" })
end
it "should be possible to list the categories" do
@article.categories.should have(2).items
@article.should be_in_category("the-apple")
@article.should be_in_category("banana")
@article.should_not be_in_category("orange")
end
it "should sort categories by link text" do
create_category(heading: "Orange",
metadata: { "link text" => "A citrus fruit" },
path: "orange")
article = create_article(metadata: { "categories" => "apple, orange" })
@article.categories.first.link_text.should == "Apple"
article.categories.first.link_text.should == "A citrus fruit"
end
it "should not be assigned to non-existant category" do
delete_page(:category, "banana", @extension)
@article.should_not be_in_category("banana")
end
end
it "should set parent to nil when at root" do
create_category(path: "top-level").parent.should be_nil
end
describe "when not assigned to category" do
it "should have empty category list" do
article = create_article
Nesta::Page.find_by_path(article.path).categories.should be_empty
end
end
describe "with no content" do
it "should produce no HTML output" do
create_article do |path|
file = File.open(path, 'w')
file.close
end
Nesta::Page.find_all.first.to_html.should match(/^\s*$/)
end
end
describe "without metadata" do
before(:each) do
create_article
@article = Nesta::Page.find_all.first
end
it "should use default layout" do
@article.layout.should == :layout
end
it "should use default template" do
@article.template.should == :page
end
it "should parse heading correctly" do
@article.to_html.should have_selector("h1", content: "My article")
end
it "should use heading as link text" do
@article.link_text.should == "My article"
end
it "should have default read more link text" do
@article.read_more.should == "Continue reading"
end
it "should not have description" do
@article.description.should be_nil
end
it "should not have keywords" do
@article.keywords.should be_nil
end
end
describe "with metadata" do
before(:each) do
@layout = 'my_layout'
@template = 'my_template'
@date = '07 September 2009'
@keywords = 'things, stuff'
@description = 'Page about stuff'
@summary = 'Multiline\n\nsummary'
@read_more = 'Continue at your leisure'
@skillz = 'ruby, guitar, bowstaff'
@link_text = 'Link to stuff page'
@article = create_article(metadata: {
'date' => @date.gsub('September', 'Sep'),
'description' => @description,
'flags' => 'draft, orange',
'keywords' => @keywords,
'layout' => @layout,
'read more' => @read_more,
'skillz' => @skillz,
'summary' => @summary,
'template' => @template,
'link text' => @link_text,
})
end
it "should override default layout" do
@article.layout.should == @layout.to_sym
end
it "should override default template" do
@article.template.should == @template.to_sym
end
it "should set permalink to basename of filename" do
@article.permalink.should == 'my-article'
end
it "should set path from filename" do
@article.path.should == 'article-prefix/my-article'
end
it "should retrieve heading" do
@article.heading.should == 'My article'
end
it "should be possible to convert an article to HTML" do
@article.to_html.should have_selector("h1", content: "My article")
end
it "should not include metadata in the HTML" do
@article.to_html.should_not have_selector("p:contains('Date')")
end
it "should not include heading in body markup" do
@article.body_markup.should_not include("My article")
end
it "should not include heading in body" do
@article.body.should_not have_selector("h1", content: "My article")
end
it "should retrieve description from metadata" do
@article.description.should == @description
end
it "should retrieve keywords from metadata" do
@article.keywords.should == @keywords
end
it "should retrieve date published from metadata" do
@article.date.strftime("%d %B %Y").should == @date
end
it "should retrieve read more link from metadata" do
@article.read_more.should == @read_more
end
it "should retrieve summary text from metadata" do
@article.summary.should match(/#{@summary.split('\n\n').first}/)
end
it "should treat double newline chars as paragraph break in summary" do
@article.summary.should match(/#{@summary.split('\n\n').last}/)
end
it "should allow access to metadata" do
@article.metadata('skillz').should == @skillz
end
it "should allow access to flags" do
@article.should be_flagged_as('draft')
@article.should be_flagged_as('orange')
end
it "should know whether or not it's a draft" do
@article.should be_draft
end
it "should allow link text to be specified explicitly" do
@article.link_text.should == @link_text
end
end
describe "when checking last modification time" do
before(:each) do
create_article
@article = Nesta::Page.find_all.first
end
it "should check filesystem" do
mock_file_stat(:should_receive, @article.filename, "3 January 2009")
@article.last_modified.should == Time.parse("3 January 2009")
end
end
describe "with no heading" do
before(:each) do
@no_heading_page = create_page(path: 'page-with-no-heading')
end
it "should raise a HeadingNotSet exception if you call heading" do
lambda do
@no_heading_page.heading
end.should raise_error(Nesta::HeadingNotSet, /page-with-no-heading/);
end
it "should raise a LinkTextNotSet exception if you call link_text" do
lambda do
@no_heading_page.link_text
end.should raise_error(Nesta::LinkTextNotSet, /page-with-no-heading/);
end
end
end
describe "All types of page" do
include ModelFactory
include_context "Page testing"
it "should still return top level menu items" do
# Page.menu_items is deprecated; we're keeping it for the moment so
# that we don't break themes or code in a local app.rb (just yet).
page1 = create_category(path: "page-1")
page2 = create_category(path: "page-2")
create_menu([page1.path, page2.path].join("\n"))
Nesta::Page.menu_items.should == [page1, page2]
end
end
describe "Markdown page" do
include ModelFactory
before(:each) do
@extension = :md
end
include_context "Page testing"
it_should_behave_like "Page"
it "should set heading from first h1 tag" do
page = create_page(
path: "a-page",
heading: "First heading",
content: "# Second heading"
)
page.heading.should == "First heading"
end
it "should ignore trailing # characters in headings" do
article = create_article(heading: 'With trailing #')
article.heading.should == 'With trailing'
end
end
describe "Haml page" do
include ModelFactory
before(:each) do
@extension = :haml
end
include_context "Page testing"
it_should_behave_like "Page"
it "should set heading from first h1 tag" do
page = create_page(
path: "a-page",
heading: "First heading",
content: "%h1 Second heading"
)
page.heading.should == "First heading"
end
it "should wrap <p> tags around one line summary text" do
page = create_page(
path: "a-page",
heading: "First para",
metadata: { "Summary" => "Wrap me" }
)
page.summary.should include("<p>Wrap me</p>")
end
it "should wrap <p> tags around multiple lines of summary text" do
page = create_page(
path: "a-page",
heading: "First para",
metadata: { "Summary" => 'Wrap me\nIn paragraph tags' }
)
page.summary.should include("<p>Wrap me</p>")
page.summary.should include("<p>In paragraph tags</p>")
end
end
describe "Textile page" do
include ModelFactory
before(:each) do
@extension = :textile
end
include_context "Page testing"
it_should_behave_like "Page"
it "should set heading from first h1 tag" do
page = create_page(
path: "a-page",
heading: "First heading",
content: "h1. Second heading"
)
page.heading.should == "First heading"
end
end
describe "Menu" do
include ModelFactory
before(:each) do
stub_configuration
@page = create_page(path: "page-1")
end
after(:each) do
remove_temp_directory
Nesta::FileModel.purge_cache
end
it "should find top level menu items" do
text = [@page.path, "no-such-page"].join("\n")
create_menu(text)
Nesta::Menu.top_level.should == [@page]
end
it "should find all items in the menu" do
create_menu(@page.path)
Nesta::Menu.full_menu.should == [@page]
Nesta::Menu.for_path('/').should == [@page]
end
describe "with nested sub menus" do
before(:each) do
(2..6).each do |i|
instance_variable_set("@page#{i}", create_page(path: "page-#{i}"))
end
text = <<-EOF
#{@page.path}
#{@page2.path}
#{@page3.path}
#{@page4.path}
#{@page5.path}
#{@page6.path}
EOF
create_menu(text)
end
it "should return top level menu items" do
Nesta::Menu.top_level.should == [@page, @page5]
end
it "should return full tree of menu items" do
Nesta::Menu.full_menu.should ==
[@page, [@page2, [@page3, @page4]], @page5, [@page6]]
end
it "should return part of the tree of menu items" do
Nesta::Menu.for_path(@page2.path).should == [@page2, [@page3, @page4]]
end
it "should deem menu for path that isn't in menu to be nil" do
Nesta::Menu.for_path('wibble').should be_nil
end
end
end
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ChangeDetectionStrategy, ViewEncapsulation} from '../../core';
import {InterpolationConfig} from '../../ml_parser/interpolation_config';
import * as o from '../../output/output_ast';
import {ParseSourceSpan} from '../../parse_util';
import * as t from '../r3_ast';
import {R3DependencyMetadata} from '../r3_factory';
/**
* Information needed to compile a directive for the render3 runtime.
*/
export interface R3DirectiveMetadata {
/**
* Name of the directive type.
*/
name: string;
/**
* An expression representing a reference to the directive itself.
*/
type: o.Expression;
/**
* Number of generic type parameters of the type itself.
*/
typeArgumentCount: number;
/**
* A source span for the directive type.
*/
typeSourceSpan: ParseSourceSpan;
/**
* Dependencies of the directive's constructor.
*/
deps: R3DependencyMetadata[]|null;
/**
* Unparsed selector of the directive, or `null` if there was no selector.
*/
selector: string|null;
/**
* Information about the content queries made by the directive.
*/
queries: R3QueryMetadata[];
/**
* Mappings indicating how the directive interacts with its host element (host bindings,
* listeners, etc).
*/
host: {
/**
* A mapping of attribute binding keys to unparsed expressions.
*/
attributes: {[key: string]: string};
/**
* A mapping of event binding keys to unparsed expressions.
*/
listeners: {[key: string]: string};
/**
* A mapping of property binding keys to unparsed expressions.
*/
properties: {[key: string]: string};
};
/**
* Information about usage of specific lifecycle events which require special treatment in the
* code generator.
*/
lifecycle: {
/**
* Whether the directive uses NgOnChanges.
*/
usesOnChanges: boolean;
};
/**
* A mapping of input field names to the property names.
*/
inputs: {[field: string]: string | [string, string]};
/**
* A mapping of output field names to the property names.
*/
outputs: {[field: string]: string};
/**
* Whether or not the component or directive inherits from another class
*/
usesInheritance: boolean;
/**
* Reference name under which to export the directive's type in a template,
* if any.
*/
exportAs: string|null;
/**
* The list of providers defined in the directive.
*/
providers: o.Expression|null;
}
/**
* Information needed to compile a component for the render3 runtime.
*/
export interface R3ComponentMetadata extends R3DirectiveMetadata {
/**
* Information about the component's template.
*/
template: {
/**
* Parsed nodes of the template.
*/
nodes: t.Node[];
};
/**
* Information about the view queries made by the component.
*/
viewQueries: R3QueryMetadata[];
/**
* A map of pipe names to an expression referencing the pipe type which are in the scope of the
* compilation.
*/
pipes: Map<string, o.Expression>;
/**
* A list of directive selectors and an expression referencing the directive type which are in the
* scope of the compilation.
*/
directives: {selector: string, expression: o.Expression}[];
/**
* Whether to wrap the 'directives' and/or `pipes` array, if one is generated, in a closure.
*
* This is done when the directives or pipes contain forward references.
*/
wrapDirectivesAndPipesInClosure: boolean;
/**
* A collection of styling data that will be applied and scoped to the component.
*/
styles: string[];
/**
* An encapsulation policy for the template and CSS styles. One of:
* - `ViewEncapsulation.Native`: Use shadow roots. This works only if natively available on the
* platform (note that this is marked the as the "deprecated shadow DOM" as of Angular v6.1.
* - `ViewEncapsulation.Emulated`: Use shimmed CSS that emulates the native behavior.
* - `ViewEncapsulation.None`: Use global CSS without any encapsulation.
* - `ViewEncapsulation.ShadowDom`: Use the latest ShadowDOM API to natively encapsulate styles
* into a shadow root.
*/
encapsulation: ViewEncapsulation;
/**
* A collection of animation triggers that will be used in the component template.
*/
animations: o.Expression|null;
/**
* The list of view providers defined in the component.
*/
viewProviders: o.Expression|null;
/**
* Path to the .ts file in which this template's generated code will be included, relative to
* the compilation root. This will be used to generate identifiers that need to be globally
* unique in certain contexts (such as g3).
*/
relativeContextFilePath: string;
/**
* Whether translation variable name should contain external message id
* (used by Closure Compiler's output of `goog.getMsg` for transition period).
*/
i18nUseExternalIds: boolean;
/**
* Overrides the default interpolation start and end delimiters ({{ and }}).
*/
interpolation: InterpolationConfig;
/**
* Strategy used for detecting changes in the component.
*/
changeDetection?: ChangeDetectionStrategy;
}
/**
* Information needed to compile a query (view or content).
*/
export interface R3QueryMetadata {
/**
* Name of the property on the class to update with query results.
*/
propertyName: string;
/**
* Whether to read only the first matching result, or an array of results.
*/
first: boolean;
/**
* Either an expression representing a type for the query predicate, or a set of string selectors.
*/
predicate: o.Expression|string[];
/**
* Whether to include only direct children or all descendants.
*/
descendants: boolean;
/**
* An expression representing a type to read from each matched node, or null if the default value
* for a given node is to be returned.
*/
read: o.Expression|null;
}
/**
* Output of render3 directive compilation.
*/
export interface R3DirectiveDef {
expression: o.Expression;
type: o.Type;
statements: o.Statement[];
}
/**
* Output of render3 component compilation.
*/
export interface R3ComponentDef {
expression: o.Expression;
type: o.Type;
statements: o.Statement[];
}
|
def get_dom_node(react_element)
rendered_element = `React.addons.TestUtils.renderIntoDocument(#{react_element})`
React.find_dom_node rendered_element
end
def get_jq_node(react_element)
dom_node = get_dom_node react_element
dom_node ? Element.find(dom_node) : nil
end
def find_element_jq_node(react_element, element_type)
jq_dom_node = get_jq_node react_element
return nil unless jq_dom_node
elements = jq_dom_node.find(element_type)
elements.any? ? elements : nil
end
def change_value_in_element(element, value, element_type=:select)
rendered = `React.addons.TestUtils.renderIntoDocument(#{element})`
parent_node = React.find_dom_node rendered
element = Element.find(parent_node).find(element_type)
element_native = element.get()[0]
`React.addons.TestUtils.Simulate.change(#{element_native}, {target: {value: #{value}}})`
end
RSpec::Matchers.define :contain_dom_element do |element_type|
match do |react_element|
@element = find_element_jq_node react_element, element_type
next false unless @element
# Don't make the test get the type exactly right
@element.value.to_s == @expected_value.to_s
end
failure_message do |react_element|
if @element
"Found element, but value was '#{@element.value}' and we expected '#{@expected_value}'"
else
"Expected rendered element to contain a #{element_type}, but it did not, did contain this: #{Native(get_dom_node(react_element)).outerHTML}"
end
end
chain :with_selected_value do |expected_value|
@expected_value = expected_value
end
end
|
version https://git-lfs.github.com/spec/v1
oid sha256:07f4bf13ba69118ebd88b07b6c66f211f610acc3cdf0a9322352a6b8100ba3ce
size 682
|
//
// OWClient.h
// OzoneWeather
//
// Created by Suzanne Kiihne on 09/05/2014.
// Copyright (c) 2014 Suzanne Kiihne. All rights reserved.
//
#import <Foundation/Foundation.h>
@import CoreLocation;
#import <ReactiveCocoa/ReactiveCocoa/ReactiveCocoa.h>
@interface OWClient : NSObject
- (RACSignal *)fetchCurrentConditionsForLocation:(CLLocationCoordinate2D)coordinate;
- (RACSignal *)fetchHourlyForecastForLocation:(CLLocationCoordinate2D)coordinate;
- (RACSignal *)fetchDailyForecastForLocation:(CLLocationCoordinate2D)coordinate;
- (RACSignal *)fetchOzoneForecastForLocation:(CLLocation*)location;
@end
|
'use strict';
// dts
import {IGlobalSumanObj} from "suman-types/dts/global";
import {IIntegrantsMessage, ISumanModuleExtended} from "suman-types/dts/index-init";
// polyfills
const process = require('suman-browser-polyfills/modules/process');
const global = require('suman-browser-polyfills/modules/global');
// core
import domain = require('domain');
import util = require('util');
import EE = require('events');
// npm
import chalk from 'chalk';
import * as fnArgs from 'function-arguments';
import * as su from 'suman-utils';
// project
const _suman: IGlobalSumanObj = global.__suman = (global.__suman || {});
if (!('integrantHashKeyVals' in _suman)) {
Object.defineProperty(_suman, 'integrantHashKeyVals', {
writable: false,
value: {}
});
}
const {acquirePreDeps} = require('../acquire-dependencies/acquire-pre-deps');
import {constants} from '../config/suman-constants';
import integrantInjector from '../injection/integrant-injector';
const IS_SUMAN_SINGLE_PROCESS = process.env.SUMAN_SINGLE_PROCESS === 'yes';
import {getClient} from './socketio-child-client';
let integPreConfiguration: any = null;
/////////////////////////////////////////////////////////////////////////////////////////////
export const handleIntegrants = function (integrants: Array<string>, $oncePost: Array<string>,
integrantPreFn: Function, $module: ISumanModuleExtended) {
let integrantsFn: Function = null;
let integrantsReady: boolean = null;
let postOnlyReady: boolean = null;
const waitForResponseFromRunnerRegardingPostList = $oncePost.length > 0;
const waitForIntegrantResponses = integrants.length > 0;
if (waitForIntegrantResponses || IS_SUMAN_SINGLE_PROCESS) {
integrantsReady = false;
}
if (waitForResponseFromRunnerRegardingPostList) {
postOnlyReady = false;
}
let client: SocketIOClient.Socket, usingRunner = _suman.usingRunner;
if (integrants.length < 1) {
if (usingRunner) {
// we should start establishing a connection now, to get ahead of things
getClient();
}
integrantsFn = function () {
return Promise.resolve({});
}
}
else if (usingRunner) {
client = getClient();
integrantsFn = function () {
return new Promise(function (resolve, reject) {
let oncePreVals: any;
let integrantMessage = function (msg: IIntegrantsMessage) {
if (msg.info === 'all-integrants-ready') {
oncePreVals = JSON.parse(msg.val);
integrantsReady = true;
if (postOnlyReady !== false) {
resolve(oncePreVals);
}
}
else if (msg.info === 'integrant-error') {
reject(msg);
}
else if (msg.info === 'once-post-received') {
// note: we need to make sure the runner received the "post" requirements of this test
// before this process exits
postOnlyReady = true;
if (integrantsReady !== false) {
resolve(oncePreVals);
}
}
};
const INTEGRANT_INFO = constants.runner_message_type.INTEGRANT_INFO;
client.on(INTEGRANT_INFO, integrantMessage);
client.emit(INTEGRANT_INFO, {
type: INTEGRANT_INFO,
msg: integrants,
oncePost: $oncePost,
expectedExitCode: _suman.expectedExitCode,
expectedTimeout: _suman.expectedTimeout,
childId: process.env.SUMAN_CHILD_ID
});
});
}
}
else {
integrantsFn = function () {
//declared at top of file
if (!integPreConfiguration) {
const args = fnArgs(integrantPreFn);
const ret = integrantPreFn.apply(null, integrantInjector(args, null));
if (ret && su.isObject(ret.dependencies)) {
integPreConfiguration = ret.dependencies;
}
else {
throw new Error(' => <suman.once.pre.js> file does not export an object with a property called "dependencies"...\n' +
(ret ? `Exported properties are ${util.inspect(Object.keys(ret))}` : ''));
}
}
return new Promise(function (resolve, reject) {
const d = domain.create();
d.once('error', function (err: Error) {
_suman.log.error(chalk.magenta('Your test was looking to source the following integrant dependencies:\n',
chalk.cyan(util.inspect(integrants)), '\n', 'But there was a problem.'));
err = new Error('Suman fatal error => there was a problem verifying the ' +
'integrants listed in test file "' + $module.filename + '"\n' + (err.stack || err));
_suman.log.error(err.stack || err);
_suman.writeTestError(err.stack || err);
process.exit(constants.EXIT_CODES.INTEGRANT_VERIFICATION_FAILURE);
});
d.run(function () {
if (!integPreConfiguration) {
throw new Error('suman implementation error, missing definition.');
}
// with suman single process, or not, we acquire integrants the same way
acquirePreDeps(integrants, integPreConfiguration).then(function (vals: Object) {
d.exit();
resolve(Object.freeze(vals));
},
function (err: Error) {
d.exit();
reject(err);
});
});
});
}
}
return integrantsFn;
};
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# run as:
# python web2py.py -S eden -M -R applications/eden/static/scripts/tools/build.sahana.py
# or
# python web2py.py -S eden -M -R applications/eden/static/scripts/tools/build.sahana.py -A gis
#
#
# Built with code/inspiration from MapFish, OpenLayers & Michael Crute
#
try:
theme = settings.get_theme()
except:
print "ERROR: File now needs to be run in the web2py environment in order to pick up which theme to build"
exit()
import os
import sys
import shutil
SCRIPTPATH = os.path.join(request.folder, "static", "scripts", "tools")
os.chdir(SCRIPTPATH)
sys.path.append("./")
# For JS
import getopt
import jsmin, mergejs
# For CSS
import re
def mergeCSS(inputFilenames, outputFilename):
output = ""
for inputFilename in inputFilenames:
output += open(inputFilename, "r").read()
open(outputFilename, "w").write(output)
return outputFilename
def cleanline(theLine):
""" Kills line breaks, tabs, and double spaces """
p = re.compile("(\n|\r|\t|\f|\v)+")
m = p.sub("", theLine)
# Kills double spaces
p = re.compile("( )+")
m = p.sub(" ", m)
# Removes last semicolon before }
p = re.compile("(; }|;})+")
m = p.sub("}", m)
# Removes space before {
p = re.compile("({ )+")
m = p.sub("{", m)
# Removes all comments
p = re.compile("/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/")
m = p.sub("", m)
# Strip off the Charset
p = re.compile("@CHARSET .*;")
m = p.sub("", m)
# Strip spaces before the {
p = re.compile(" {")
m = p.sub("{", m)
# Strip space after :
p = re.compile(": ")
m = p.sub(":", m)
# Strip space after ,
p = re.compile(", ")
m = p.sub(",", m)
# Strip space after ;
p = re.compile("; ")
m = p.sub(";", m)
return m
def compressCSS(inputFilename, outputFilename):
theFile = open(inputFilename, "r").read()
output = ""
for line in theFile:
output = output + cleanline(line)
# Once more, clean the entire file string
_output = cleanline(output)
open(outputFilename, "w").write(_output)
return
def dojs(dogis = False, warnings = True):
""" Minifies the JavaScript """
# Do we have local version of the Closure Compiler available?
use_compressor = "jsmin" # Fallback
try:
import closure
use_compressor = "closure"
print "using local Closure Compiler"
except Exception, E:
print "No closure (%s)" % E
print "Download from http://closure-compiler.googlecode.com/files/compiler-latest.zip"
try:
import closure_ws
use_compressor = "closure_ws"
print "Using Closure via Web Service - limited to files < 1Mb!"
except ImportError:
print "No closure_ws"
if use_compressor == "closure":
if not warnings:
closure.extra_params = "--warning_level QUIET"
minimize = closure.minimize
elif use_compressor == "closure_ws":
minimize = closure_ws.minimize
elif use_compressor == "jsmin":
minimize = jsmin.jsmin
sourceDirectory = ".."
configFilename = "sahana.js.cfg"
outputFilename = "S3.min.js"
# Merge JS files
print "Merging Core libraries."
merged = mergejs.run(sourceDirectory, None, configFilename)
# Compress JS files
print "Compressing - JS"
minimized = minimize(merged)
# Add license
print "Adding license file."
minimized = open("license.txt").read() + minimized
# Print to output files
print "Writing to %s." % outputFilename
open(outputFilename, "w").write(minimized)
# Remove old JS files
print "Deleting %s." % outputFilename
try:
os.remove("../S3/%s" % outputFilename)
except:
pass
# Move new JS files
print "Moving new JS files"
shutil.move(outputFilename, "../S3")
# dataTables
print "Compressing dataTables"
sourceDirectorydataTables = ".."
configFilenamedataTables = "sahana.js.dataTables.cfg"
outputFilenamedataTables = "s3.dataTables.min.js"
mergeddataTables = mergejs.run(sourceDirectorydataTables,
None,
configFilenamedataTables)
minimizeddataTables = minimize(mergeddataTables)
open(outputFilenamedataTables, "w").write(minimizeddataTables)
try:
os.remove("../S3/%s" % outputFilenamedataTables)
except:
pass
shutil.move(outputFilenamedataTables, "../S3")
# Vulnerability
print "Compressing Vulnerability"
sourceDirectoryVulnerability = ".."
configFilenameVulnerability = "sahana.js.vulnerability.cfg"
outputFilenameVulnerability = "s3.vulnerability.min.js"
mergedVulnerability = mergejs.run(sourceDirectoryVulnerability,
None,
configFilenameVulnerability)
minimizedVulnerability = minimize(mergedVulnerability)
open(outputFilenameVulnerability, "w").write(minimizedVulnerability)
try:
os.remove("../S3/%s" % outputFilenameVulnerability)
except:
pass
shutil.move(outputFilenameVulnerability, "../S3")
print "Compressing Vulnerability GIS"
sourceDirectoryVulnerability = "../../themes/Vulnerability/js"
configFilenameVulnerability = "sahana.js.vulnerability_gis.cfg"
outputFilenameVulnerability = "OpenLayers.js"
mergedVulnerability = mergejs.run(sourceDirectoryVulnerability,
None,
configFilenameVulnerability)
minimizedVulnerability = minimize(mergedVulnerability)
open(outputFilenameVulnerability, "w").write(minimizedVulnerability)
try:
os.remove("../../themes/Vulnerability/js/%s" % outputFilenameVulnerability)
except:
pass
shutil.move(outputFilenameVulnerability, "../../themes/Vulnerability/js")
# Single scripts
for filename in [
"contacts",
"embed_component",
"inline_component",
"locationselector.widget",
"popup",
"report",
"select_person",
"timeline",
]:
print "Compressing s3.%s.js" % filename
inputFilename = os.path.join("..", "S3", "s3.%s.js" % filename)
outputFilename = "s3.%s.min.js" % filename
input = open(inputFilename, "r").read()
minimized = minimize(input)
open(outputFilename, "w").write(minimized)
try:
os.remove("../S3/%s" % outputFilename)
except:
pass
shutil.move(outputFilename, "../S3")
if dogis:
sourceDirectoryGIS = "../S3"
sourceDirectoryOpenLayers = "../gis/openlayers/lib"
sourceDirectoryOpenLayersExten = "../gis"
sourceDirectoryMGRS = "../gis"
sourceDirectoryGeoExt = "../gis/GeoExt/lib"
sourceDirectoryGeoExtux = "../gis/GeoExt/ux"
sourceDirectoryGxp = "../gis/gxp"
#sourceDirectoryGeoExplorer = "../gis/GeoExplorer"
configFilenameGIS = "sahana.js.gis.cfg"
configFilenameOpenLayers = "sahana.js.ol.cfg"
configFilenameOpenLayersExten = "sahana.js.ol_exten.cfg"
configFilenameMGRS = "sahana.js.mgrs.cfg"
configFilenameGeoExt = "sahana.js.geoext.cfg"
configFilenameGeoExtux = "sahana.js.geoextux.cfg"
configFilenameGxpMin = "sahana.js.gxp.cfg"
configFilenameGxpFull = "sahana.js.gxpfull.cfg"
#configFilenameGeoExplorer = "sahana.js.geoexplorer.cfg"
outputFilenameGIS = "s3.gis.min.js"
outputFilenameOpenLayers = "OpenLayers.js"
outputFilenameMGRS = "MGRS.min.js"
outputFilenameGeoExt = "GeoExt.js"
outputFilenameGxp = "gxp.js"
#outputFilenameGeoExplorer = "GeoExplorer.js"
# Merge GIS JS Files
print "Merging GIS scripts."
mergedGIS = mergejs.run(sourceDirectoryGIS,
None,
configFilenameGIS)
print "Merging OpenLayers libraries."
mergedOpenLayers = mergejs.run(sourceDirectoryOpenLayers,
None,
configFilenameOpenLayers)
mergedOpenLayersExten = mergejs.run(sourceDirectoryOpenLayersExten,
None,
configFilenameOpenLayersExten)
print "Merging MGRS libraries."
mergedMGRS = mergejs.run(sourceDirectoryMGRS,
None,
configFilenameMGRS)
print "Merging GeoExt libraries."
mergedGeoExt = mergejs.run(sourceDirectoryGeoExt,
None,
configFilenameGeoExt)
mergedGeoExtux = mergejs.run(sourceDirectoryGeoExtux,
None,
configFilenameGeoExtux)
print "Merging gxp libraries."
mergedGxpMin = mergejs.run(sourceDirectoryGxp,
None,
configFilenameGxpMin)
mergedGxpFull = mergejs.run(sourceDirectoryGxp,
None,
configFilenameGxpFull)
#print "Merging GeoExplorer libraries."
#mergedGeoExplorer = mergejs.run(sourceDirectoryGeoExplorer,
# None,
# configFilenameGeoExplorer)
# Compress JS files
print "Compressing - GIS JS"
minimizedGIS = minimize(mergedGIS)
print "Compressing - OpenLayers JS"
if use_compressor == "closure_ws":
# Limited to files < 1Mb!
minimizedOpenLayers = jsmin.jsmin("%s\n%s" % (mergedOpenLayers,
mergedOpenLayersExten))
else:
minimizedOpenLayers = minimize("%s\n%s" % (mergedOpenLayers,
mergedOpenLayersExten))
print "Compressing - MGRS JS"
minimizedMGRS = minimize(mergedMGRS)
print "Compressing - GeoExt JS"
minimizedGeoExt = minimize("%s\n%s\n%s" % (mergedGeoExt,
mergedGeoExtux,
mergedGxpMin))
print "Compressing - gxp JS"
minimizedGxp = minimize(mergedGxpFull)
#print "Compressing - GeoExplorer JS"
#minimizedGeoExplorer = minimize(mergedGeoExplorer)
# Add license
#minimizedGIS = open("license.gis.txt").read() + minimizedGIS
# Print to output files
print "Writing to %s." % outputFilenameGIS
open(outputFilenameGIS, "w").write(minimizedGIS)
print "Writing to %s." % outputFilenameOpenLayers
open(outputFilenameOpenLayers, "w").write(minimizedOpenLayers)
print "Writing to %s." % outputFilenameMGRS
open(outputFilenameMGRS, "w").write(minimizedMGRS)
print "Writing to %s." % outputFilenameGeoExt
open(outputFilenameGeoExt, "w").write(minimizedGeoExt)
print "Writing to %s." % outputFilenameGxp
open(outputFilenameGxp, "w").write(minimizedGxp)
#print "Writing to %s." % outputFilenameGeoExplorer
#open(outputFilenameGeoExplorer, "w").write(minimizedGeoExplorer)
# Move new JS files
print "Deleting %s." % outputFilenameGIS
try:
os.remove("../S3/%s" % outputFilenameGIS)
except:
pass
print "Moving new GIS JS files"
shutil.move(outputFilenameGIS, "../S3")
print "Deleting %s." % outputFilenameOpenLayers
try:
os.remove("../gis/%s" % outputFilenameOpenLayers)
except:
pass
print "Moving new OpenLayers JS files"
shutil.move(outputFilenameOpenLayers, "../gis")
print "Deleting %s." % outputFilenameMGRS
try:
os.remove("../gis/%s" % outputFilenameMGRS)
except:
pass
print "Moving new MGRS JS files"
shutil.move(outputFilenameMGRS, "../gis")
print "Deleting %s." % outputFilenameGeoExt
try:
os.remove("../gis/%s" % outputFilenameGeoExt)
except:
pass
print "Moving new GeoExt JS files"
shutil.move(outputFilenameGeoExt, "../gis")
print "Deleting %s." % outputFilenameGxp
try:
os.remove("../gis/%s" % outputFilenameGxp)
except:
pass
print "Moving new gxp JS files"
shutil.move(outputFilenameGxp, "../gis")
#print "Deleting %s." % outputFilenameGeoExplorer
#try:
# os.remove("../gis/%s" % outputFilenameGeoExplorer)
#except:
# pass
#print "Moving new GeoExplorer JS files"
#shutil.move(outputFilenameGeoExplorer, "../gis")
def docss():
""" Compresses the CSS files """
listCSS = []
theme = settings.get_theme()
print "Using theme %s" % theme
css_cfg = os.path.join("..", "..", "..", "private", "templates", theme, "css.cfg")
f = open(css_cfg, "r")
files = f.readlines()
f.close()
for file in files[:-1]:
p = re.compile("(\n|\r|\t|\f|\v)+")
file = p.sub("", file)
listCSS.append("../../styles/%s" % file)
outputFilenameCSS = "eden.min.css"
# Merge CSS files
print "Merging Core styles."
mergedCSS = mergeCSS(listCSS, outputFilenameCSS)
# Compress CSS files
print "Writing to %s." % outputFilenameCSS
compressCSS(mergedCSS, outputFilenameCSS)
# Move files to correct locations
print "Deleting %s." % outputFilenameCSS
try:
os.remove("../../themes/%s/%s" % (theme, outputFilenameCSS))
except:
pass
print "Moving new %s." % outputFilenameCSS
shutil.move(outputFilenameCSS, "../../themes/%s" % theme)
def main(argv):
try:
parameter1 = argv[0]
except:
parameter1 = "ALL"
try:
if(argv[1] == "DOGIS"):
parameter2 = True
else:
parameter2 = False
except:
parameter2 = True
closure_warnings = True
if "NOWARN" in argv:
closure_warnings = False
if parameter1 in ("ALL", "NOWARN"):
dojs(warnings=closure_warnings)
docss()
else:
if parameter1 == "CSS":
docss()
else:
dojs(parameter2, warnings=closure_warnings)
docss()
print "Done."
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
|
import * as React from 'react';
import {Items,Item,Row,Col,Table,Code} from 'yrui';
let thead=[{
key:'key',
value:'参数',
},{
key:'expr',
value:'说明',
},{
key:'type',
value:'类型',
},{
key:'values',
value:'可选值',
},{
key:'default',
value:'默认值',
}];
//
let route=[{
key:'url',
expr:'路径',
type:'string',
values:'-',
default:'-',
},{
key:'component',
expr:'页面组件',
type:'object|function',
values:'-',
default:'-',
},{
key:'asyncComponent',
expr:'按需加载组件',
type:'function',
values:'-',
default:'-',
},{
key:'name',
expr:'标题',
type:'string',
values:'-',
default:'-',
},{
key:'icon',
expr:'路由左侧图标',
type:'string',
values:'-',
default:'-',
},{
key:'noMenu',
expr:'不显示菜单栏',
type:'boolean',
values:'-',
default:'false',
},{
key:'noFrame',
expr:'不显框架信息',
type:'boolean',
values:'-',
default:'false',
},{
key:'child',
expr:'子路由',
type:'array',
values:'-',
default:'-',
}];
//
let brand=[{
key:'logo',
expr:'是否在brand上显示logo',
type:'string',
values:'-',
default:'-',
},{
key:'title',
expr:'标题',
type:'string',
values:'-',
default:'-',
},{
key:'subtitle',
expr:'副标题',
type:'string',
values:'-',
default:'-',
}];
//
let navbar=[{
key:'leftNav',
expr:'头部左侧内容',
type:'array',
values:'-',
default:'-',
},{
key:'rightNav',
expr:'头部右侧内容',
type:'array',
values:'-',
default:'-',
},{
key:'click',
expr:'返回当前点击nav的数据(click(v))',
type:'function',
values:'-',
default:'-',
},{
key:'collapse',
expr:'左侧菜单栏切换事件',
type:'function',
values:'-',
default:'-',
}];
//
let leftNav=[{
key:'name',
expr:'下拉菜单名',
type:'string',
values:'-',
default:'-',
},{
key:'icon',
expr:'下拉菜单图标',
type:'string',
values:'-',
default:'-',
},{
key:'img',
expr:'下拉菜单图标',
type:'string',
values:'-',
default:'-',
},{
key:'animate',
expr:'下拉菜单动画',
type:'string',
values:'up/down/left/right',
default:'up',
},{
key:'msg',
expr:'下拉菜单消息提示',
type:'string',
values:'-',
default:'-',
},{
key:'drop',
expr:'下拉菜单内容',
type:'function|string',
values:'-',
default:'-',
},{
key:'url',
expr:'菜单链接',
type:'string',
values:'-',
default:'javascript:;',
}];
//
let sidebar=[{
key:'projectList',
expr:'项目列表',
type:'array',
values:'-',
default:'-',
},{
key:'showSidebarTitle',
expr:'是否隐藏侧边栏title',
type:'boolean',
values:'true/false',
default:'false',
},{
key:'userInfo',
expr:'用户信息展示',
type:'object',
values:'-',
default:'-',
}];
let userinfo=[{
key:'name',
expr:'已登陆用户名',
type:'string',
values:'-',
default:'-',
},{
key:'logo',
expr:'已登陆用户头像',
type:'string|object',
values:'-',
default:'-',
},{
key:'email',
expr:'已登陆用户邮箱',
type:'string',
values:'-',
default:'-',
}];
//
let main=[{
key:'showBreadcrumb',
expr:'是否显示面包屑',
type:'boolean',
values:'true/false',
default:'true',
},{
key:'showPagetitle',
expr:'是否显示面包屑上面标题',
type:'boolean',
values:'true/false',
default:'false',
}];
//
let routers=[{
key:'routers',
expr:'路由表',
type:'array',
values:'-',
default:'-',
},{
key:'horizontal',
expr:'是否为水平菜单栏',
type:'boolean',
values:'true/false',
default:'false',
},{
key:'brand',
expr:'头部brand配置',
type:'object',
values:'-',
default:'-',
},{
key:'navbar',
expr:'头部nav配置',
type:'object',
values:'-',
default:'-',
},{
key:'main',
expr:'主页面头部配置',
type:'object',
values:'-',
default:'-',
},{
key:'sidebar',
expr:'左侧边栏配置',
type:'object',
values:'-',
default:'-',
},{
key:'rightbar',
expr:'右侧边栏配置',
type:'object|string',
values:'-',
default:'-',
},{
key:'footer',
expr:'底部栏配置',
type:'object|string',
values:'-',
default:'-',
},{
key:'browserRouter',
expr:'是否是真实路径',
type:'boolean',
values:'true/false',
default:'false',
},{
key:'routeAnimate',
expr:'路由切换动画',
type:'string',
values:'scale/down/right/no',
default:'scale',
},{
key:'theme',
expr:'用户自定义主题',
type:'string',
values:'-',
default:'-',
}];
//
let others=[{
key:'rightbar',
expr:'右侧边栏',
type:'object|string',
values:'-',
default:'-',
},{
key:'footer',
expr:'底部栏配置',
type:'object|string',
values:'-',
default:'-',
},{
key:'browserRouter',
expr:'是否是真实路径',
type:'boolean',
values:'true/false',
default:'false',
},{
key:'routeAnimate',
expr:'路由切换动画',
type:'string',
values:'scale/down/right/no',
default:'scale',
},{
key:'horizontal',
expr:'是否为水平菜单栏',
type:'boolean',
values:'true/false',
default:'false',
},{
key:'theme',
expr:'用户自定义主题',
type:'string',
values:'-',
default:'-',
}];
const t=`const app={
brand:{
title:'Phoenix',//
subtitle:'UI Demo',//
logo:require('./styles/images/usr.jpg'),//
},
navbar:{
leftNav:null,
rightNav:null,
click:(v)=>{console.log(v);},//点击头部菜单事件
collapse:()=>{console.log('collapse');},//左侧菜单栏切换事件
},
sidebar:{
projectList:null,//菜单项目列表,可忽略
showSidebarTitle:false,//显示侧边栏标题
userInfo:null,//用户信息
},
rightbar:'<h2>111</h2>',//右侧边栏component
main:{
showBreadcrumb:true,//显示面包屑
showPagetitle:false,//显示头部标题
},
footer:'<p>版权所有 © 2017-2020 Phoenix 团队</p>',//底部栏component
routers:sidebarMenu,//侧边栏,路由
routeAnimate:'scale',//路由切换动画,设置为'no'取消动画效果
browserRouter:false,//是否使用真实路径
horizontal:false,//是否为水平菜单栏
theme:'',//用户自定义主题
};
<Router {...app} />
`;
export default class Frame extends React.Component {
render() {
return (
<Items>
<Item>
<Row>
<Col span={12}>
<h2>routers配置</h2>
<Table thead={thead} tbody={routers} />
</Col>
</Row>
<Row gutter={8}>
<Col span={12}>
<div className="txt-area">
<h2>配置</h2>
{/*<p>brand navbar sidebar rightbar main</p>*/}
<Code title="demo" code={t} />
</div>
</Col>
</Row>
<Row gutter={8}>
<Col span={12}>
<h2>route配置</h2>
<Table thead={thead} tbody={route} />
</Col>
</Row>
<Row gutter={8}>
<Col span={12}>
<h2>brand配置</h2>
<Table thead={thead} tbody={brand} />
</Col>
</Row>
<Row gutter={8}>
<Col span={12}>
<h2>navbar配置</h2>
<Table thead={thead} tbody={navbar} />
</Col>
</Row>
<Row gutter={8}>
<Col span={12}>
<h2>sidebar配置</h2>
<Table thead={thead} tbody={sidebar} />
</Col>
</Row>
<Row gutter={8}>
<Col span={12}>
<h2>userinfo配置</h2>
<Table thead={thead} tbody={userinfo} />
</Col>
</Row>
<Row gutter={8}>
<Col span={12}>
<h2>main配置</h2>
<Table thead={thead} tbody={main} />
</Col>
</Row>
<Row gutter={8}>
<Col span={12}>
<h2>leftNav、leftNav配置</h2>
<Table thead={thead} tbody={leftNav} />
</Col>
</Row>
</Item>
</Items>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.