file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
pipeline.py | from pymuse.pipelinestages.pipeline_stage import PipelineStage
from pymuse.utils.stoppablequeue import StoppableQueue
from pymuse.signal import Signal
from pymuse.constants import PIPELINE_QUEUE_SIZE
class PipelineFork():
"""
This class is used to fork a Pipeline. Ex.: PipelineFork([stage1, stage2], [stage3]) fork the pipeline
in two paths and has two outputs (stage2 and stage3). It is used during the construction of Pipeline.
"""
def | (self, *branches):
self.forked_branches: list = list(branches)
class Pipeline():
"""
This class create a multithreaded pipeline. It automatically links together every contiguous stages.
E.g.: Pipeline(Signal(), PipelineStage(), PipelineFork([PipelineStage(), PipelineStage()], [PipelineStage()] ))
"""
def __init__(self, input_signal: Signal, *stages):
self._output_queues = []
self._stages: list = list(stages)
self._link_stages(self._stages)
self._stages[0]._queue_in = input_signal.signal_queue
def get_output_queue(self, queue_index=0) -> StoppableQueue:
"""Return a ref to the queue given by queue_index"""
return self._output_queues[queue_index]
def read_output_queue(self, queue_index=0):
"""Wait to read a data in a queue given by queue_index"""
return self._output_queues[queue_index].get()
def start(self):
"""Start all pipelines stages."""
self._start(self._stages)
def shutdown(self):
""" shutdowns every child thread (PipelineStage)"""
self._shutdown(self._stages)
def join(self):
"""Ensure every thread (PipelineStage) of the pipeline are done"""
for stage in self._stages:
stage.join()
def _link_pipeline_fork(self, stages: list, index: int):
for fork in stages[index].forked_branches:
stages[index - 1].add_queue_out(fork[0].queue_in)
self._link_stages(fork)
def _link_stages(self, stages: list):
for i in range(1, len(stages)):
if type(stages[i]) == PipelineFork:
self._link_pipeline_fork(stages, i)
else:
stages[i - 1].add_queue_out(stages[i].queue_in)
if issubclass(type(stages[-1]), PipelineStage):
output_queue = StoppableQueue(PIPELINE_QUEUE_SIZE)
stages[-1].add_queue_out(output_queue)
self._output_queues.append(output_queue)
def _start(self, stages: list):
for stage in stages:
if type(stage) == PipelineFork:
for forked_branch in stage.forked_branches:
self._start(forked_branch)
else:
stage.start()
def _shutdown(self, stages: list):
for stage in stages:
if type(stage) == PipelineFork:
for forked_branch in stage.forked_branches:
self._shutdown(forked_branch)
else:
stage.shutdown()
| __init__ | identifier_name |
group_dao.py | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides the data access object (DAO) for Groups."""
from Queue import Queue
from google.cloud.security.common.data_access import dao
from google.cloud.security.common.data_access.sql_queries import select_data
from google.cloud.security.common.util import log_util
# TODO: The next editor must remove this disable and correct issues.
# pylint: disable=missing-type-doc,missing-return-type-doc
LOGGER = log_util.get_logger(__name__)
MY_CUSTOMER = 'my_customer'
class GroupDao(dao.Dao):
"""Data access object (DAO) for Groups."""
def get_all_groups(self, resource_name, timestamp):
"""Get all the groups.
Args:
resource_name: String of the resource name.
timestamp: The timestamp of the snapshot.
Returns:
A tuple of the groups as dict.
"""
sql = select_data.GROUPS.format(timestamp)
return self.execute_sql_with_fetch(resource_name, sql, None)
def get_group_id(self, resource_name, group_email, timestamp):
"""Get the group_id for the specified group_email.
Args:
resource_name: String of the resource name.
group_email: String of the group email.
timestamp: The timestamp of the snapshot.
Returns:
String of the group id.
"""
sql = select_data.GROUP_ID.format(timestamp)
result = self.execute_sql_with_fetch(resource_name, sql, (group_email,))
return result[0].get('group_id')
def | (self, resource_name, group_id, timestamp):
"""Get the members of a group.
Args:
resource_name: String of the resource name.
group_id: String of the group id.
timestamp: The timestamp of the snapshot.
Returns:
A tuple of group members in dict format.
({'group_id': '00lnxb',
'member_email': 'foo@mygbiz.com',
'member_id': '11111',
'member_role': 'OWNER',
'member_type': 'USER'}, ...)
"""
sql = select_data.GROUP_MEMBERS.format(timestamp)
return self.execute_sql_with_fetch(resource_name, sql, (group_id,))
def get_recursive_members_of_group(self, group_email, timestamp):
"""Get all the recursive members of a group.
Args:
group_email: String of the group email.
timestamp: The timestamp of the snapshot.
Returns:
A list of group members in dict format.
[{'group_id': '00lnxb',
'member_email': 'foo@mygbiz.com',
'member_id': '11111',
'member_role': 'OWNER',
'member_type': 'USER'}, ...]
"""
all_members = []
queue = Queue()
group_id = self.get_group_id('group', group_email, timestamp)
queue.put(group_id)
while not queue.empty():
group_id = queue.get()
members = self.get_group_members('group_members', group_id,
timestamp)
for member in members:
all_members.append(member)
if member.get('member_type') == 'GROUP':
queue.put(member.get('member_id'))
return all_members
| get_group_members | identifier_name |
group_dao.py | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides the data access object (DAO) for Groups."""
from Queue import Queue
from google.cloud.security.common.data_access import dao
from google.cloud.security.common.data_access.sql_queries import select_data
from google.cloud.security.common.util import log_util
# TODO: The next editor must remove this disable and correct issues.
# pylint: disable=missing-type-doc,missing-return-type-doc
LOGGER = log_util.get_logger(__name__)
MY_CUSTOMER = 'my_customer'
class GroupDao(dao.Dao):
"""Data access object (DAO) for Groups."""
def get_all_groups(self, resource_name, timestamp):
"""Get all the groups.
Args:
resource_name: String of the resource name.
timestamp: The timestamp of the snapshot.
Returns:
A tuple of the groups as dict.
"""
sql = select_data.GROUPS.format(timestamp)
return self.execute_sql_with_fetch(resource_name, sql, None)
def get_group_id(self, resource_name, group_email, timestamp):
"""Get the group_id for the specified group_email.
Args:
resource_name: String of the resource name.
group_email: String of the group email.
timestamp: The timestamp of the snapshot.
Returns:
String of the group id.
"""
sql = select_data.GROUP_ID.format(timestamp)
result = self.execute_sql_with_fetch(resource_name, sql, (group_email,))
return result[0].get('group_id')
def get_group_members(self, resource_name, group_id, timestamp):
"""Get the members of a group.
Args:
resource_name: String of the resource name.
group_id: String of the group id.
timestamp: The timestamp of the snapshot.
Returns:
A tuple of group members in dict format.
({'group_id': '00lnxb',
'member_email': 'foo@mygbiz.com',
'member_id': '11111',
'member_role': 'OWNER',
'member_type': 'USER'}, ...)
"""
sql = select_data.GROUP_MEMBERS.format(timestamp)
return self.execute_sql_with_fetch(resource_name, sql, (group_id,))
def get_recursive_members_of_group(self, group_email, timestamp):
"""Get all the recursive members of a group.
Args:
group_email: String of the group email.
timestamp: The timestamp of the snapshot.
Returns:
A list of group members in dict format.
[{'group_id': '00lnxb',
'member_email': 'foo@mygbiz.com',
'member_id': '11111',
'member_role': 'OWNER',
'member_type': 'USER'}, ...]
"""
all_members = []
queue = Queue()
group_id = self.get_group_id('group', group_email, timestamp)
queue.put(group_id)
while not queue.empty():
group_id = queue.get()
members = self.get_group_members('group_members', group_id,
timestamp)
for member in members:
all_members.append(member)
if member.get('member_type') == 'GROUP':
|
return all_members
| queue.put(member.get('member_id')) | conditional_block |
group_dao.py | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides the data access object (DAO) for Groups."""
from Queue import Queue
from google.cloud.security.common.data_access import dao
from google.cloud.security.common.data_access.sql_queries import select_data
from google.cloud.security.common.util import log_util
# TODO: The next editor must remove this disable and correct issues.
# pylint: disable=missing-type-doc,missing-return-type-doc
LOGGER = log_util.get_logger(__name__)
MY_CUSTOMER = 'my_customer'
class GroupDao(dao.Dao):
"""Data access object (DAO) for Groups."""
def get_all_groups(self, resource_name, timestamp):
"""Get all the groups.
Args: | timestamp: The timestamp of the snapshot.
Returns:
A tuple of the groups as dict.
"""
sql = select_data.GROUPS.format(timestamp)
return self.execute_sql_with_fetch(resource_name, sql, None)
def get_group_id(self, resource_name, group_email, timestamp):
"""Get the group_id for the specified group_email.
Args:
resource_name: String of the resource name.
group_email: String of the group email.
timestamp: The timestamp of the snapshot.
Returns:
String of the group id.
"""
sql = select_data.GROUP_ID.format(timestamp)
result = self.execute_sql_with_fetch(resource_name, sql, (group_email,))
return result[0].get('group_id')
def get_group_members(self, resource_name, group_id, timestamp):
"""Get the members of a group.
Args:
resource_name: String of the resource name.
group_id: String of the group id.
timestamp: The timestamp of the snapshot.
Returns:
A tuple of group members in dict format.
({'group_id': '00lnxb',
'member_email': 'foo@mygbiz.com',
'member_id': '11111',
'member_role': 'OWNER',
'member_type': 'USER'}, ...)
"""
sql = select_data.GROUP_MEMBERS.format(timestamp)
return self.execute_sql_with_fetch(resource_name, sql, (group_id,))
def get_recursive_members_of_group(self, group_email, timestamp):
"""Get all the recursive members of a group.
Args:
group_email: String of the group email.
timestamp: The timestamp of the snapshot.
Returns:
A list of group members in dict format.
[{'group_id': '00lnxb',
'member_email': 'foo@mygbiz.com',
'member_id': '11111',
'member_role': 'OWNER',
'member_type': 'USER'}, ...]
"""
all_members = []
queue = Queue()
group_id = self.get_group_id('group', group_email, timestamp)
queue.put(group_id)
while not queue.empty():
group_id = queue.get()
members = self.get_group_members('group_members', group_id,
timestamp)
for member in members:
all_members.append(member)
if member.get('member_type') == 'GROUP':
queue.put(member.get('member_id'))
return all_members | resource_name: String of the resource name. | random_line_split |
group_dao.py | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provides the data access object (DAO) for Groups."""
from Queue import Queue
from google.cloud.security.common.data_access import dao
from google.cloud.security.common.data_access.sql_queries import select_data
from google.cloud.security.common.util import log_util
# TODO: The next editor must remove this disable and correct issues.
# pylint: disable=missing-type-doc,missing-return-type-doc
LOGGER = log_util.get_logger(__name__)
MY_CUSTOMER = 'my_customer'
class GroupDao(dao.Dao):
| """Data access object (DAO) for Groups."""
def get_all_groups(self, resource_name, timestamp):
"""Get all the groups.
Args:
resource_name: String of the resource name.
timestamp: The timestamp of the snapshot.
Returns:
A tuple of the groups as dict.
"""
sql = select_data.GROUPS.format(timestamp)
return self.execute_sql_with_fetch(resource_name, sql, None)
def get_group_id(self, resource_name, group_email, timestamp):
"""Get the group_id for the specified group_email.
Args:
resource_name: String of the resource name.
group_email: String of the group email.
timestamp: The timestamp of the snapshot.
Returns:
String of the group id.
"""
sql = select_data.GROUP_ID.format(timestamp)
result = self.execute_sql_with_fetch(resource_name, sql, (group_email,))
return result[0].get('group_id')
def get_group_members(self, resource_name, group_id, timestamp):
"""Get the members of a group.
Args:
resource_name: String of the resource name.
group_id: String of the group id.
timestamp: The timestamp of the snapshot.
Returns:
A tuple of group members in dict format.
({'group_id': '00lnxb',
'member_email': 'foo@mygbiz.com',
'member_id': '11111',
'member_role': 'OWNER',
'member_type': 'USER'}, ...)
"""
sql = select_data.GROUP_MEMBERS.format(timestamp)
return self.execute_sql_with_fetch(resource_name, sql, (group_id,))
def get_recursive_members_of_group(self, group_email, timestamp):
"""Get all the recursive members of a group.
Args:
group_email: String of the group email.
timestamp: The timestamp of the snapshot.
Returns:
A list of group members in dict format.
[{'group_id': '00lnxb',
'member_email': 'foo@mygbiz.com',
'member_id': '11111',
'member_role': 'OWNER',
'member_type': 'USER'}, ...]
"""
all_members = []
queue = Queue()
group_id = self.get_group_id('group', group_email, timestamp)
queue.put(group_id)
while not queue.empty():
group_id = queue.get()
members = self.get_group_members('group_members', group_id,
timestamp)
for member in members:
all_members.append(member)
if member.get('member_type') == 'GROUP':
queue.put(member.get('member_id'))
return all_members | identifier_body | |
core.py | # Copyright 2017 Erik Tollerud
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function, unicode_literals # just in case, for py2 to be py3-ish
import pkgutil, io
import numpy as np
from matplotlib import image, cm
from matplotlib import pyplot as plt
__all__ = ['get_cat_num', 'n_cats', 'catter']
# N_cats x 72 x 72, 0 is transparent, 1 is full-cat
_CAT_DATA = np.load(io.BytesIO(pkgutil.get_data('catterplot', 'data/cats.npy')))
def get_cat_num(i):
return _CAT_DATA[i]
def n_cats():
return len(_CAT_DATA)
def catter(x, y, s=40, c=None, cat='random', alpha=1, ax=None, cmap=None,
aspects='auto'):
"""
A catter plot (scatter plot with cats). Most arguments are interpreted
the same as the matplotlib `scatter` function, except that ``s`` is the
*data* size of the symbol (not pixel). Additional kwargs include:
``cat`` can be:
* int : the index of the cat symbol to use - you can use
``catterplot.n_cats()`` to get the number of cats available
* a squence of ints : must match the data, but otherwise interpreted as for
a scalar
* 'random'/'rand' : random cats
``ax`` can be:
* None: use the current default (pyplot) axes
* an `Axes` : random cats
``aspects`` can be:
* 'auto': the cats length-to-width is set to be square given the spread of
inputs
* a float: the height/width of the cats. If not 1, ``s`` is interpreted as
the geometric mean of the sizes
* a sequence of floats: much match data, gives height/width
"""
if ax is None:
ax = plt.gca()
if c is not None:
if cmap is None:
cmap = plt.rcParams['image.cmap']
smap = cm.ScalarMappable(cmap=cmap)
rgba = smap.to_rgba(c)
else:
rgba = np.ones((len(x), 4))
rgba[:, 3] *= alpha
if np.isscalar(s) or s.shape==tuple():
s = np.ones(len(x))*s
# otherwise assume shapes match
if cat in ('rand', 'random'):
cats = np.random.randint(n_cats(), size=len(x))
else:
try:
cats = np.ones(len(x)) * cat
except TypeError as e:
raise TypeError('`cat` argument needs to be "random", a scalar, or match the input.', e)
if aspects == 'auto':
aspects = np.ptp(y)/np.ptp(x)
if np.isscalar(aspects) or aspects.shape==tuple():
aspects = np.ones(len(x)) * aspects
ims = []
for xi, yi, si, ci, cati, aspecti in zip(x, y, s, rgba, cats, aspects):
data = get_cat_num(cati)
offsetx = si * aspecti**-0.5 / (2 * data.shape[0])
offsety = si * aspecti**0.5 / (2 * data.shape[1])
im = image.AxesImage(ax, extent=(xi - offsetx, xi + offsetx,
yi - offsety, yi + offsety))
if c is None:
# defaults to fading "black"
|
else:
# leave just the alpha to control the fading
cdata = np.ones(data.shape)
imarr = np.transpose([cdata*ci[0], cdata*ci[1], cdata*ci[2],
data*ci[3]], (1, 2, 0))
im.set_data(imarr)
ims.append(im)
for im in ims:
ax.add_image(im)
#ax.autoscale_view()
# for some reason autoscaling fails for images. So we'll just force it via
# scatter...
sc = plt.scatter(x, y)
sc.remove()
return ims
| cdata = 1-data | conditional_block |
core.py | # Copyright 2017 Erik Tollerud
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function, unicode_literals # just in case, for py2 to be py3-ish
import pkgutil, io
import numpy as np
from matplotlib import image, cm
from matplotlib import pyplot as plt
__all__ = ['get_cat_num', 'n_cats', 'catter']
# N_cats x 72 x 72, 0 is transparent, 1 is full-cat
_CAT_DATA = np.load(io.BytesIO(pkgutil.get_data('catterplot', 'data/cats.npy')))
def get_cat_num(i):
|
def n_cats():
return len(_CAT_DATA)
def catter(x, y, s=40, c=None, cat='random', alpha=1, ax=None, cmap=None,
aspects='auto'):
"""
A catter plot (scatter plot with cats). Most arguments are interpreted
the same as the matplotlib `scatter` function, except that ``s`` is the
*data* size of the symbol (not pixel). Additional kwargs include:
``cat`` can be:
* int : the index of the cat symbol to use - you can use
``catterplot.n_cats()`` to get the number of cats available
* a squence of ints : must match the data, but otherwise interpreted as for
a scalar
* 'random'/'rand' : random cats
``ax`` can be:
* None: use the current default (pyplot) axes
* an `Axes` : random cats
``aspects`` can be:
* 'auto': the cats length-to-width is set to be square given the spread of
inputs
* a float: the height/width of the cats. If not 1, ``s`` is interpreted as
the geometric mean of the sizes
* a sequence of floats: much match data, gives height/width
"""
if ax is None:
ax = plt.gca()
if c is not None:
if cmap is None:
cmap = plt.rcParams['image.cmap']
smap = cm.ScalarMappable(cmap=cmap)
rgba = smap.to_rgba(c)
else:
rgba = np.ones((len(x), 4))
rgba[:, 3] *= alpha
if np.isscalar(s) or s.shape==tuple():
s = np.ones(len(x))*s
# otherwise assume shapes match
if cat in ('rand', 'random'):
cats = np.random.randint(n_cats(), size=len(x))
else:
try:
cats = np.ones(len(x)) * cat
except TypeError as e:
raise TypeError('`cat` argument needs to be "random", a scalar, or match the input.', e)
if aspects == 'auto':
aspects = np.ptp(y)/np.ptp(x)
if np.isscalar(aspects) or aspects.shape==tuple():
aspects = np.ones(len(x)) * aspects
ims = []
for xi, yi, si, ci, cati, aspecti in zip(x, y, s, rgba, cats, aspects):
data = get_cat_num(cati)
offsetx = si * aspecti**-0.5 / (2 * data.shape[0])
offsety = si * aspecti**0.5 / (2 * data.shape[1])
im = image.AxesImage(ax, extent=(xi - offsetx, xi + offsetx,
yi - offsety, yi + offsety))
if c is None:
# defaults to fading "black"
cdata = 1-data
else:
# leave just the alpha to control the fading
cdata = np.ones(data.shape)
imarr = np.transpose([cdata*ci[0], cdata*ci[1], cdata*ci[2],
data*ci[3]], (1, 2, 0))
im.set_data(imarr)
ims.append(im)
for im in ims:
ax.add_image(im)
#ax.autoscale_view()
# for some reason autoscaling fails for images. So we'll just force it via
# scatter...
sc = plt.scatter(x, y)
sc.remove()
return ims
| return _CAT_DATA[i] | identifier_body |
core.py | # Copyright 2017 Erik Tollerud
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function, unicode_literals # just in case, for py2 to be py3-ish
import pkgutil, io
| import numpy as np
from matplotlib import image, cm
from matplotlib import pyplot as plt
__all__ = ['get_cat_num', 'n_cats', 'catter']
# N_cats x 72 x 72, 0 is transparent, 1 is full-cat
_CAT_DATA = np.load(io.BytesIO(pkgutil.get_data('catterplot', 'data/cats.npy')))
def get_cat_num(i):
return _CAT_DATA[i]
def n_cats():
return len(_CAT_DATA)
def catter(x, y, s=40, c=None, cat='random', alpha=1, ax=None, cmap=None,
aspects='auto'):
"""
A catter plot (scatter plot with cats). Most arguments are interpreted
the same as the matplotlib `scatter` function, except that ``s`` is the
*data* size of the symbol (not pixel). Additional kwargs include:
``cat`` can be:
* int : the index of the cat symbol to use - you can use
``catterplot.n_cats()`` to get the number of cats available
* a squence of ints : must match the data, but otherwise interpreted as for
a scalar
* 'random'/'rand' : random cats
``ax`` can be:
* None: use the current default (pyplot) axes
* an `Axes` : random cats
``aspects`` can be:
* 'auto': the cats length-to-width is set to be square given the spread of
inputs
* a float: the height/width of the cats. If not 1, ``s`` is interpreted as
the geometric mean of the sizes
* a sequence of floats: much match data, gives height/width
"""
if ax is None:
ax = plt.gca()
if c is not None:
if cmap is None:
cmap = plt.rcParams['image.cmap']
smap = cm.ScalarMappable(cmap=cmap)
rgba = smap.to_rgba(c)
else:
rgba = np.ones((len(x), 4))
rgba[:, 3] *= alpha
if np.isscalar(s) or s.shape==tuple():
s = np.ones(len(x))*s
# otherwise assume shapes match
if cat in ('rand', 'random'):
cats = np.random.randint(n_cats(), size=len(x))
else:
try:
cats = np.ones(len(x)) * cat
except TypeError as e:
raise TypeError('`cat` argument needs to be "random", a scalar, or match the input.', e)
if aspects == 'auto':
aspects = np.ptp(y)/np.ptp(x)
if np.isscalar(aspects) or aspects.shape==tuple():
aspects = np.ones(len(x)) * aspects
ims = []
for xi, yi, si, ci, cati, aspecti in zip(x, y, s, rgba, cats, aspects):
data = get_cat_num(cati)
offsetx = si * aspecti**-0.5 / (2 * data.shape[0])
offsety = si * aspecti**0.5 / (2 * data.shape[1])
im = image.AxesImage(ax, extent=(xi - offsetx, xi + offsetx,
yi - offsety, yi + offsety))
if c is None:
# defaults to fading "black"
cdata = 1-data
else:
# leave just the alpha to control the fading
cdata = np.ones(data.shape)
imarr = np.transpose([cdata*ci[0], cdata*ci[1], cdata*ci[2],
data*ci[3]], (1, 2, 0))
im.set_data(imarr)
ims.append(im)
for im in ims:
ax.add_image(im)
#ax.autoscale_view()
# for some reason autoscaling fails for images. So we'll just force it via
# scatter...
sc = plt.scatter(x, y)
sc.remove()
return ims | random_line_split | |
core.py | # Copyright 2017 Erik Tollerud
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function, unicode_literals # just in case, for py2 to be py3-ish
import pkgutil, io
import numpy as np
from matplotlib import image, cm
from matplotlib import pyplot as plt
__all__ = ['get_cat_num', 'n_cats', 'catter']
# N_cats x 72 x 72, 0 is transparent, 1 is full-cat
_CAT_DATA = np.load(io.BytesIO(pkgutil.get_data('catterplot', 'data/cats.npy')))
def get_cat_num(i):
return _CAT_DATA[i]
def n_cats():
return len(_CAT_DATA)
def | (x, y, s=40, c=None, cat='random', alpha=1, ax=None, cmap=None,
aspects='auto'):
"""
A catter plot (scatter plot with cats). Most arguments are interpreted
the same as the matplotlib `scatter` function, except that ``s`` is the
*data* size of the symbol (not pixel). Additional kwargs include:
``cat`` can be:
* int : the index of the cat symbol to use - you can use
``catterplot.n_cats()`` to get the number of cats available
* a squence of ints : must match the data, but otherwise interpreted as for
a scalar
* 'random'/'rand' : random cats
``ax`` can be:
* None: use the current default (pyplot) axes
* an `Axes` : random cats
``aspects`` can be:
* 'auto': the cats length-to-width is set to be square given the spread of
inputs
* a float: the height/width of the cats. If not 1, ``s`` is interpreted as
the geometric mean of the sizes
* a sequence of floats: much match data, gives height/width
"""
if ax is None:
ax = plt.gca()
if c is not None:
if cmap is None:
cmap = plt.rcParams['image.cmap']
smap = cm.ScalarMappable(cmap=cmap)
rgba = smap.to_rgba(c)
else:
rgba = np.ones((len(x), 4))
rgba[:, 3] *= alpha
if np.isscalar(s) or s.shape==tuple():
s = np.ones(len(x))*s
# otherwise assume shapes match
if cat in ('rand', 'random'):
cats = np.random.randint(n_cats(), size=len(x))
else:
try:
cats = np.ones(len(x)) * cat
except TypeError as e:
raise TypeError('`cat` argument needs to be "random", a scalar, or match the input.', e)
if aspects == 'auto':
aspects = np.ptp(y)/np.ptp(x)
if np.isscalar(aspects) or aspects.shape==tuple():
aspects = np.ones(len(x)) * aspects
ims = []
for xi, yi, si, ci, cati, aspecti in zip(x, y, s, rgba, cats, aspects):
data = get_cat_num(cati)
offsetx = si * aspecti**-0.5 / (2 * data.shape[0])
offsety = si * aspecti**0.5 / (2 * data.shape[1])
im = image.AxesImage(ax, extent=(xi - offsetx, xi + offsetx,
yi - offsety, yi + offsety))
if c is None:
# defaults to fading "black"
cdata = 1-data
else:
# leave just the alpha to control the fading
cdata = np.ones(data.shape)
imarr = np.transpose([cdata*ci[0], cdata*ci[1], cdata*ci[2],
data*ci[3]], (1, 2, 0))
im.set_data(imarr)
ims.append(im)
for im in ims:
ax.add_image(im)
#ax.autoscale_view()
# for some reason autoscaling fails for images. So we'll just force it via
# scatter...
sc = plt.scatter(x, y)
sc.remove()
return ims
| catter | identifier_name |
DayPicker.js | import React from 'react';
import { storiesOf } from '@kadira/storybook';
import DayPicker from '../src/components/DayPicker';
import moment from 'moment-jalaali'
import {
VERTICAL_ORIENTATION,
VERTICAL_SCROLLABLE,
} from '../constants';
const TestPrevIcon = props => (
<span style={{
border: '1px solid #dce0e0',
backgroundColor: '#fff',
color: '#484848',
padding: '3px'
}}
>
Prev
</span>
);
const TestNextIcon = props => (
<span style={{
border: '1px solid #dce0e0',
backgroundColor: '#fff',
color: '#484848',
padding: '3px'
}}
>
Next
</span>
);
storiesOf('DayPicker', module)
.addWithInfo('default', () => (
<DayPicker />
))
.addWithInfo('Gregorian Datepicker', () => (
<DayPicker monthFormat="YYYY MMMM" inFarsi={false} />
))
.addWithInfo('more than one month', () => (
<DayPicker numberOfMonths={2} />
))
.addWithInfo('vertical', () => (
<DayPicker
numberOfMonths={2}
orientation={VERTICAL_ORIENTATION}
/>
))
.addWithInfo('vertically scrollable with 12 months', () => (
<div style={{
height: '568px',
width: '320px',
}}>
<DayPicker
numberOfMonths={12}
orientation={VERTICAL_SCROLLABLE}
/>
</div>
))
.addWithInfo('with custom arrows', () => (
<DayPicker
navPrev={<TestPrevIcon />} | />
))
.addWithInfo('with custom details', () => (
<DayPicker
renderDay={day => (day.day() % 6 === 5 ? '😻' : day.format('D'))}
/>
))
.addWithInfo('vertical with fixed-width container', () => (
<div style={{ width: '400px' }}>
<DayPicker
numberOfMonths={2}
orientation={VERTICAL_ORIENTATION}
/>
</div>
)); | navNext={<TestNextIcon />} | random_line_split |
AlertMessageView_spec.js | define(
[
'views/AlertMessageView',
'lib/Mediator'
],
function (AlertMessageView, Mediator) { |
beforeEach(function () {
resultsCollection = new Backbone.Collection();
mediator = new Mediator();
});
it('should initially be hidden', function () {
view = new AlertMessageView().render();
expect(view.$el.find('.alert')).toHaveClass('hidden');
});
it('should become visible when a new message arrives', function () {
view = new AlertMessageView();
view.setMediator(mediator);
mediator.trigger('app:alert', {title: 'x', content: 'y'});
expect(view.$el.find('.alert')).not.toHaveClass('hidden');
});
it('should close it when a user clicks the X', function () {
view = new AlertMessageView().render();
view.setMediator(mediator);
view.removeAlertMessage();
expect(view.$el.find('.alert')).toHaveClass('hidden');
});
});
}); |
describe('AlertMessageView', function () {
var resultsCollection, view, mediator; | random_line_split |
zipping_list.py | import sys
import random
from linked_list_prototype import ListNode
from reverse_linked_list_iterative import reverse_linked_list
# @include
def zipping_linked_list(L):
if not L or not L.next:
return L
# Finds the second half of L.
slow = fast = L
while fast and fast.next:
slow, fast = slow.next, fast.next.next
first_half_head = L
second_half_head = slow.next
slow.next = None # Splits the list into two lists.
second_half_head = reverse_linked_list(second_half_head)
# Interleave the first half and the reversed of the second half.
first_half_iter, second_half_iter = first_half_head, second_half_head
while second_half_iter:
second_half_iter.next, first_half_iter.next, second_half_iter = (
first_half_iter.next, second_half_iter, second_half_iter.next)
first_half_iter = first_half_iter.next.next
return first_half_head
# @exclude
def main():
head = None
if len(sys.argv) > 2:
for i in sys.argv[1:]:
curr = ListNode(int(i), head)
head = curr
else:
|
curr = zipping_linked_list(head)
idx = 0
while curr:
if len(sys.argv) <= 2:
if idx & 1:
assert pre + curr.data == n
idx += 1
print(curr.data)
pre = curr.data
curr = curr.next
if __name__ == '__main__':
main()
| n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 1000)
for i in reversed(range(n + 1)):
curr = ListNode(i, head)
head = curr | conditional_block |
zipping_list.py | import sys
import random
from linked_list_prototype import ListNode
from reverse_linked_list_iterative import reverse_linked_list
# @include
def zipping_linked_list(L):
if not L or not L.next:
return L
# Finds the second half of L.
slow = fast = L
while fast and fast.next:
slow, fast = slow.next, fast.next.next
first_half_head = L
second_half_head = slow.next
slow.next = None # Splits the list into two lists.
second_half_head = reverse_linked_list(second_half_head)
# Interleave the first half and the reversed of the second half.
first_half_iter, second_half_iter = first_half_head, second_half_head
while second_half_iter:
second_half_iter.next, first_half_iter.next, second_half_iter = (
first_half_iter.next, second_half_iter, second_half_iter.next)
first_half_iter = first_half_iter.next.next
return first_half_head
# @exclude
def main():
head = None
if len(sys.argv) > 2:
for i in sys.argv[1:]:
curr = ListNode(int(i), head)
head = curr
else:
n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 1000)
for i in reversed(range(n + 1)):
curr = ListNode(i, head)
head = curr
curr = zipping_linked_list(head)
idx = 0 | if len(sys.argv) <= 2:
if idx & 1:
assert pre + curr.data == n
idx += 1
print(curr.data)
pre = curr.data
curr = curr.next
if __name__ == '__main__':
main() | while curr: | random_line_split |
zipping_list.py | import sys
import random
from linked_list_prototype import ListNode
from reverse_linked_list_iterative import reverse_linked_list
# @include
def zipping_linked_list(L):
if not L or not L.next:
return L
# Finds the second half of L.
slow = fast = L
while fast and fast.next:
slow, fast = slow.next, fast.next.next
first_half_head = L
second_half_head = slow.next
slow.next = None # Splits the list into two lists.
second_half_head = reverse_linked_list(second_half_head)
# Interleave the first half and the reversed of the second half.
first_half_iter, second_half_iter = first_half_head, second_half_head
while second_half_iter:
second_half_iter.next, first_half_iter.next, second_half_iter = (
first_half_iter.next, second_half_iter, second_half_iter.next)
first_half_iter = first_half_iter.next.next
return first_half_head
# @exclude
def | ():
head = None
if len(sys.argv) > 2:
for i in sys.argv[1:]:
curr = ListNode(int(i), head)
head = curr
else:
n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 1000)
for i in reversed(range(n + 1)):
curr = ListNode(i, head)
head = curr
curr = zipping_linked_list(head)
idx = 0
while curr:
if len(sys.argv) <= 2:
if idx & 1:
assert pre + curr.data == n
idx += 1
print(curr.data)
pre = curr.data
curr = curr.next
if __name__ == '__main__':
main()
| main | identifier_name |
zipping_list.py | import sys
import random
from linked_list_prototype import ListNode
from reverse_linked_list_iterative import reverse_linked_list
# @include
def zipping_linked_list(L):
if not L or not L.next:
return L
# Finds the second half of L.
slow = fast = L
while fast and fast.next:
slow, fast = slow.next, fast.next.next
first_half_head = L
second_half_head = slow.next
slow.next = None # Splits the list into two lists.
second_half_head = reverse_linked_list(second_half_head)
# Interleave the first half and the reversed of the second half.
first_half_iter, second_half_iter = first_half_head, second_half_head
while second_half_iter:
second_half_iter.next, first_half_iter.next, second_half_iter = (
first_half_iter.next, second_half_iter, second_half_iter.next)
first_half_iter = first_half_iter.next.next
return first_half_head
# @exclude
def main():
|
if __name__ == '__main__':
main()
| head = None
if len(sys.argv) > 2:
for i in sys.argv[1:]:
curr = ListNode(int(i), head)
head = curr
else:
n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 1000)
for i in reversed(range(n + 1)):
curr = ListNode(i, head)
head = curr
curr = zipping_linked_list(head)
idx = 0
while curr:
if len(sys.argv) <= 2:
if idx & 1:
assert pre + curr.data == n
idx += 1
print(curr.data)
pre = curr.data
curr = curr.next | identifier_body |
input.rs | //! Provides utilities for tracking the state of various input devices
use cable_math::Vec2;
const MOUSE_KEYS: usize = 5;
const KEYBOARD_KEYS: usize = 256; // This MUST be `u8::max_value() + 1`
/// Passed to `Window::poll_events` each frame to get updated.
#[derive(Clone)]
pub struct Input {
/// The position of the mouse, in window space
pub mouse_pos: Vec2<f32>,
/// The amount `mouse_pos` has changed since last frame
/// TODO document whether this stays constant if the mouse is grabbed
pub mouse_delta: Vec2<f32>,
/// The amount of movement directly reported by the mouse sensor. Should be used for e.g. first
/// person cameras in games.
pub raw_mouse_delta: Vec2<f32>,
/// Units scrolled in the last frame. 1.0 corresponds to one tick of the wheel
pub mouse_scroll: f32,
/// The state of mouse keys. 0 is left, 1 is right, 2 is middle. 3 and 4 are usually the keys
/// for clicking the mousewheel laterally, for mice that have such keys. Sometimes they are
/// also placed on the side of the mouse.
///
/// On linux, 3 and 4 are always `Up`, because these codes are used for the scroll wheel
/// internally.
pub mouse_keys: [KeyState; MOUSE_KEYS],
/// The state of keyboard keys. Can also be accessed more ergonomically throug the
/// `Input::key()` method
pub keys: [KeyState; KEYBOARD_KEYS],
/// Cleared each frame. Contains typed characters in the order they where typed
pub type_buffer: String,
pub window_has_keyboard_focus: bool,
pub received_events_this_frame: bool,
#[cfg(feature = "gamepad")]
pub gamepads: [Gamepad; 4],
}
impl Input {
pub fn new() -> Input {
Input {
mouse_pos: Vec2::ZERO,
mouse_delta: Vec2::ZERO,
raw_mouse_delta: Vec2::ZERO,
mouse_scroll: 0.0,
mouse_keys: [KeyState::Up; MOUSE_KEYS],
keys: [KeyState::Up; KEYBOARD_KEYS],
type_buffer: String::with_capacity(10),
window_has_keyboard_focus: false,
received_events_this_frame: false,
#[cfg(feature = "gamepad")]
gamepads: [Default::default(), Default::default(), Default::default(), Default::default()],
}
}
// Called by `Window::poll_events` in the platform layer
pub(crate) fn refresh(&mut self) {
self.mouse_delta = Vec2::ZERO;
self.raw_mouse_delta = Vec2::ZERO;
self.mouse_scroll = 0.0;
self.type_buffer.clear();
for state in self.mouse_keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state != KeyState::PressedRepeat);
}
for state in self.keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
if *state == KeyState::PressedRepeat { *state = KeyState::Down; }
}
#[cfg(feature = "gamepad")]
for gamepad in self.gamepads.iter_mut() {
if gamepad.connected {
for state in gamepad.buttons.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state != KeyState::PressedRepeat);
}
} else {
gamepad.buttons = [KeyState::Up; GAMEPAD_BUTTON_COUNT];
gamepad.left = Vec2::ZERO;
gamepad.right = Vec2::ZERO;
gamepad.left_trigger = 0.0;
gamepad.right_trigger = 0.0;
}
}
self.received_events_this_frame = false;
}
/// The state of the given keyboard key. Note that `Key` represent scancodes.
/// See [`Key`](enum.Key.html) for more info
pub fn key(&self, key: Key) -> KeyState {
self.keys[key as usize]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KeyState {
/// The button is not held down.
Up,
/// The button is being held down. In the previous frame it was not held down.
Pressed,
/// The button is being held down, and its repeat action triggered
PressedRepeat,
/// The button is being held down.
Down,
/// The button is not being held down. In the previous frame it was held down.
Released,
}
impl Default for KeyState {
fn default() -> KeyState { KeyState::Up }
}
impl KeyState {
/// Returns true if the button is being held down (`Down` or `Pressed`) and
/// false otherwise (`Up`, `Released` or `PressedRepeat`).
pub fn down(self) -> bool {
match self {
KeyState::Up | KeyState::Released => false,
KeyState::Down | KeyState::Pressed | KeyState::PressedRepeat => true,
}
}
/// Returns true if the button is not being held down (`Up` or `Released`) and
/// false otherwise (`Down` or `Pressed`).
pub fn up(self) -> bool {
!self.down()
}
/// Returns true if the button is being held down, but was not held down in the last
/// frame (`Pressed`)
pub fn pressed(self) -> bool { self == KeyState::Pressed }
/// Returns true either if this button is being held down and was not held down in the
/// last frame (`Pressed`), or if the repeat action has been triggered by the key being
/// held down for an extended amount of time (`PressedRepeat`).
pub fn pressed_repeat(self) -> bool {
self == KeyState::Pressed || self == KeyState::PressedRepeat
}
/// Returns true if the button is being not held down, but was held down in the last
/// frame (`Released`)
pub fn released(self) -> bool { self == KeyState::Released }
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position
/// on the keyboard, rather than a specific symbol. These can be used as parameters
/// to [`InputManager::key`](struct.InputManager.html#method.key). The names are
/// based on the american keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "linux")]
#[repr(u8)]
pub enum Key {
Key1 = 0xa, Key2 = 0xb, Key3 = 0xc, Key4 = 0xd, Key5 = 0xe,
Key6 = 0xf, Key7 = 0x10, Key8 = 0x11, Key9 = 0x12, Key0 = 0x13,
Q = 0x18, W = 0x19, E = 0x1a, R = 0x1b, T = 0x1c, Y = 0x1d, U = 0x1e, I = 0x1f, O = 0x20, P = 0x21,
A = 0x26, S = 0x27, D = 0x28, F = 0x29, G = 0x2a, H = 0x2b, J = 0x2c, K = 0x2d, L = 0x2e,
Z = 0x34, X = 0x35, C = 0x36, V = 0x37, B = 0x38, N = 0x39, M = 0x3a,
Space = 0x41,
Escape = 0x9, Grave = 0x31, Tab = 0x17, CapsLock = 0x42,
LShift = 0x32, LCtrl = 0x25, LAlt = 0x40,
RAlt = 0x6c, RMeta = 0x86, RCtrl = 0x69, RShift = 0x3e, Return = 0x24, Back = 0x16,
Right = 0x72, Left = 0x71, Down = 0x74, Up = 0x6f,
Insert = 0x76, Delete = 0x77, Home = 0x6e, End = 0x73, PageUp = 0x70, PageDown = 0x75,
F1 = 0x43, F2 = 0x44, F3 = 0x45, F4 = 0x46, F5 = 0x47, F6 = 0x48,
F7 = 0x49, F8 = 0x4a, F9 = 0x4b, F10 = 0x4c, F11 = 0x5f, F12 = 0x60,
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position on the
/// keyboard, rather than a specific symbol. These can be used as parameters to
/// [`InputManager::key`](struct.InputManager.html#method.key). The names are based on the american
/// keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "windows")]
#[repr(u8)]
pub enum Key {
Key1 = 0x2, Key2 = 0x3, Key3 = 0x4, Key4 = 0x5, Key5 = 0x6,
Key6 = 0x7, Key7 = 0x8, Key8 = 0x9, Key9 = 0xa, Key0 = 0xb,
Q = 0x10, W = 0x11, E = 0x12, R = 0x13, T = 0x14, Y = 0x15, U = 0x16, I = 0x17, O = 0x18, P = 0x19,
A = 0x1e, S = 0x1f, D = 0x20, F = 0x21, G = 0x22, H = 0x23, J = 0x24, K = 0x25, L = 0x26,
Z = 0x2c, X = 0x2d, C = 0x2e, V = 0x2f, B = 0x30, N = 0x31, M = 0x32,
Space = 0x39, | Tab = 0xf,
// CapsLock = 0x42,
LShift = 0x2a,
LCtrl = 0x1d,
// LAlt = 0x40,
// RAlt = 0x6c,
// RMeta = 0x86,
// RCtrl = 0x1d, // Same scancode as LCtrl :/
RShift = 0x36,
Return = 0x1c,
Back = 0xe,
Right = 0x4d, Left = 0x4b, Down = 0x50, Up = 0x48,
Insert = 0x52, Delete = 0x53, Home = 0x47, End = 0x4f, PageUp = 0x49, PageDown = 0x51,
F1 = 0x3b, F2 = 0x3c, F3 = 0x3d, F4 = 0x3e, F5 = 0x3f, F6 = 0x40,
F7 = 0x41, F8 = 0x42, F9 = 0x43, F10 = 0x44, F11 = 0x57, F12 = 0x58,
}
#[cfg(feature = "gamepad")]
#[derive(Clone, Default)]
pub struct Gamepad {
pub connected: bool,
pub buttons: [KeyState; GAMEPAD_BUTTON_COUNT],
pub left: Vec2<f32>,
pub right: Vec2<f32>,
pub left_trigger: f32,
pub right_trigger: f32,
}
#[cfg(feature = "gamepad")]
const GAMEPAD_BUTTON_COUNT: usize = 24;
#[cfg(feature = "gamepad")]
#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum GamepadButton {
DpadUp = 0,
DpadDown,
DpadLeft,
DpadRight,
LeftUp,
LeftDown,
LeftRight,
LeftLeft,
RightUp,
RightDown,
RightRight,
RightLeft,
Start,
Back,
LeftStick,
RightStick,
LeftBumper,
RightBumper,
LeftTrigger,
RightTrigger,
A, B, X, Y,
}
#[cfg(feature = "gamepad")]
impl Gamepad {
pub fn button(&self, button: GamepadButton) -> KeyState {
self.buttons[button as usize]
}
} |
Escape = 0x1,
// Grave = 0x31, | random_line_split |
input.rs |
//! Provides utilities for tracking the state of various input devices
use cable_math::Vec2;
const MOUSE_KEYS: usize = 5;
const KEYBOARD_KEYS: usize = 256; // This MUST be `u8::max_value() + 1`
/// Passed to `Window::poll_events` each frame to get updated.
#[derive(Clone)]
pub struct Input {
/// The position of the mouse, in window space
pub mouse_pos: Vec2<f32>,
/// The amount `mouse_pos` has changed since last frame
/// TODO document whether this stays constant if the mouse is grabbed
pub mouse_delta: Vec2<f32>,
/// The amount of movement directly reported by the mouse sensor. Should be used for e.g. first
/// person cameras in games.
pub raw_mouse_delta: Vec2<f32>,
/// Units scrolled in the last frame. 1.0 corresponds to one tick of the wheel
pub mouse_scroll: f32,
/// The state of mouse keys. 0 is left, 1 is right, 2 is middle. 3 and 4 are usually the keys
/// for clicking the mousewheel laterally, for mice that have such keys. Sometimes they are
/// also placed on the side of the mouse.
///
/// On linux, 3 and 4 are always `Up`, because these codes are used for the scroll wheel
/// internally.
pub mouse_keys: [KeyState; MOUSE_KEYS],
/// The state of keyboard keys. Can also be accessed more ergonomically throug the
/// `Input::key()` method
pub keys: [KeyState; KEYBOARD_KEYS],
/// Cleared each frame. Contains typed characters in the order they where typed
pub type_buffer: String,
pub window_has_keyboard_focus: bool,
pub received_events_this_frame: bool,
#[cfg(feature = "gamepad")]
pub gamepads: [Gamepad; 4],
}
impl Input {
pub fn new() -> Input {
Input {
mouse_pos: Vec2::ZERO,
mouse_delta: Vec2::ZERO,
raw_mouse_delta: Vec2::ZERO,
mouse_scroll: 0.0,
mouse_keys: [KeyState::Up; MOUSE_KEYS],
keys: [KeyState::Up; KEYBOARD_KEYS],
type_buffer: String::with_capacity(10),
window_has_keyboard_focus: false,
received_events_this_frame: false,
#[cfg(feature = "gamepad")]
gamepads: [Default::default(), Default::default(), Default::default(), Default::default()],
}
}
// Called by `Window::poll_events` in the platform layer
pub(crate) fn refresh(&mut self) {
self.mouse_delta = Vec2::ZERO;
self.raw_mouse_delta = Vec2::ZERO;
self.mouse_scroll = 0.0;
self.type_buffer.clear();
for state in self.mouse_keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state != KeyState::PressedRepeat);
}
for state in self.keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
if *state == KeyState::PressedRepeat { *state = KeyState::Down; }
}
#[cfg(feature = "gamepad")]
for gamepad in self.gamepads.iter_mut() {
if gamepad.connected | else {
gamepad.buttons = [KeyState::Up; GAMEPAD_BUTTON_COUNT];
gamepad.left = Vec2::ZERO;
gamepad.right = Vec2::ZERO;
gamepad.left_trigger = 0.0;
gamepad.right_trigger = 0.0;
}
}
self.received_events_this_frame = false;
}
/// The state of the given keyboard key. Note that `Key` represent scancodes.
/// See [`Key`](enum.Key.html) for more info
pub fn key(&self, key: Key) -> KeyState {
self.keys[key as usize]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KeyState {
/// The button is not held down.
Up,
/// The button is being held down. In the previous frame it was not held down.
Pressed,
/// The button is being held down, and its repeat action triggered
PressedRepeat,
/// The button is being held down.
Down,
/// The button is not being held down. In the previous frame it was held down.
Released,
}
impl Default for KeyState {
fn default() -> KeyState { KeyState::Up }
}
impl KeyState {
/// Returns true if the button is being held down (`Down` or `Pressed`) and
/// false otherwise (`Up`, `Released` or `PressedRepeat`).
pub fn down(self) -> bool {
match self {
KeyState::Up | KeyState::Released => false,
KeyState::Down | KeyState::Pressed | KeyState::PressedRepeat => true,
}
}
/// Returns true if the button is not being held down (`Up` or `Released`) and
/// false otherwise (`Down` or `Pressed`).
pub fn up(self) -> bool {
!self.down()
}
/// Returns true if the button is being held down, but was not held down in the last
/// frame (`Pressed`)
pub fn pressed(self) -> bool { self == KeyState::Pressed }
/// Returns true either if this button is being held down and was not held down in the
/// last frame (`Pressed`), or if the repeat action has been triggered by the key being
/// held down for an extended amount of time (`PressedRepeat`).
pub fn pressed_repeat(self) -> bool {
self == KeyState::Pressed || self == KeyState::PressedRepeat
}
/// Returns true if the button is being not held down, but was held down in the last
/// frame (`Released`)
pub fn released(self) -> bool { self == KeyState::Released }
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position
/// on the keyboard, rather than a specific symbol. These can be used as parameters
/// to [`InputManager::key`](struct.InputManager.html#method.key). The names are
/// based on the american keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "linux")]
#[repr(u8)]
pub enum Key {
Key1 = 0xa, Key2 = 0xb, Key3 = 0xc, Key4 = 0xd, Key5 = 0xe,
Key6 = 0xf, Key7 = 0x10, Key8 = 0x11, Key9 = 0x12, Key0 = 0x13,
Q = 0x18, W = 0x19, E = 0x1a, R = 0x1b, T = 0x1c, Y = 0x1d, U = 0x1e, I = 0x1f, O = 0x20, P = 0x21,
A = 0x26, S = 0x27, D = 0x28, F = 0x29, G = 0x2a, H = 0x2b, J = 0x2c, K = 0x2d, L = 0x2e,
Z = 0x34, X = 0x35, C = 0x36, V = 0x37, B = 0x38, N = 0x39, M = 0x3a,
Space = 0x41,
Escape = 0x9, Grave = 0x31, Tab = 0x17, CapsLock = 0x42,
LShift = 0x32, LCtrl = 0x25, LAlt = 0x40,
RAlt = 0x6c, RMeta = 0x86, RCtrl = 0x69, RShift = 0x3e, Return = 0x24, Back = 0x16,
Right = 0x72, Left = 0x71, Down = 0x74, Up = 0x6f,
Insert = 0x76, Delete = 0x77, Home = 0x6e, End = 0x73, PageUp = 0x70, PageDown = 0x75,
F1 = 0x43, F2 = 0x44, F3 = 0x45, F4 = 0x46, F5 = 0x47, F6 = 0x48,
F7 = 0x49, F8 = 0x4a, F9 = 0x4b, F10 = 0x4c, F11 = 0x5f, F12 = 0x60,
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position on the
/// keyboard, rather than a specific symbol. These can be used as parameters to
/// [`InputManager::key`](struct.InputManager.html#method.key). The names are based on the american
/// keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "windows")]
#[repr(u8)]
pub enum Key {
Key1 = 0x2, Key2 = 0x3, Key3 = 0x4, Key4 = 0x5, Key5 = 0x6,
Key6 = 0x7, Key7 = 0x8, Key8 = 0x9, Key9 = 0xa, Key0 = 0xb,
Q = 0x10, W = 0x11, E = 0x12, R = 0x13, T = 0x14, Y = 0x15, U = 0x16, I = 0x17, O = 0x18, P = 0x19,
A = 0x1e, S = 0x1f, D = 0x20, F = 0x21, G = 0x22, H = 0x23, J = 0x24, K = 0x25, L = 0x26,
Z = 0x2c, X = 0x2d, C = 0x2e, V = 0x2f, B = 0x30, N = 0x31, M = 0x32,
Space = 0x39,
Escape = 0x1,
// Grave = 0x31,
Tab = 0xf,
// CapsLock = 0x42,
LShift = 0x2a,
LCtrl = 0x1d,
// LAlt = 0x40,
// RAlt = 0x6c,
// RMeta = 0x86,
// RCtrl = 0x1d, // Same scancode as LCtrl :/
RShift = 0x36,
Return = 0x1c,
Back = 0xe,
Right = 0x4d, Left = 0x4b, Down = 0x50, Up = 0x48,
Insert = 0x52, Delete = 0x53, Home = 0x47, End = 0x4f, PageUp = 0x49, PageDown = 0x51,
F1 = 0x3b, F2 = 0x3c, F3 = 0x3d, F4 = 0x3e, F5 = 0x3f, F6 = 0x40,
F7 = 0x41, F8 = 0x42, F9 = 0x43, F10 = 0x44, F11 = 0x57, F12 = 0x58,
}
#[cfg(feature = "gamepad")]
#[derive(Clone, Default)]
pub struct Gamepad {
pub connected: bool,
pub buttons: [KeyState; GAMEPAD_BUTTON_COUNT],
pub left: Vec2<f32>,
pub right: Vec2<f32>,
pub left_trigger: f32,
pub right_trigger: f32,
}
#[cfg(feature = "gamepad")]
const GAMEPAD_BUTTON_COUNT: usize = 24;
#[cfg(feature = "gamepad")]
#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum GamepadButton {
DpadUp = 0,
DpadDown,
DpadLeft,
DpadRight,
LeftUp,
LeftDown,
LeftRight,
LeftLeft,
RightUp,
RightDown,
RightRight,
RightLeft,
Start,
Back,
LeftStick,
RightStick,
LeftBumper,
RightBumper,
LeftTrigger,
RightTrigger,
A, B, X, Y,
}
#[cfg(feature = "gamepad")]
impl Gamepad {
pub fn button(&self, button: GamepadButton) -> KeyState {
self.buttons[button as usize]
}
}
| {
for state in gamepad.buttons.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state != KeyState::PressedRepeat);
}
} | conditional_block |
input.rs |
//! Provides utilities for tracking the state of various input devices
use cable_math::Vec2;
const MOUSE_KEYS: usize = 5;
const KEYBOARD_KEYS: usize = 256; // This MUST be `u8::max_value() + 1`
/// Passed to `Window::poll_events` each frame to get updated.
#[derive(Clone)]
pub struct Input {
/// The position of the mouse, in window space
pub mouse_pos: Vec2<f32>,
/// The amount `mouse_pos` has changed since last frame
/// TODO document whether this stays constant if the mouse is grabbed
pub mouse_delta: Vec2<f32>,
/// The amount of movement directly reported by the mouse sensor. Should be used for e.g. first
/// person cameras in games.
pub raw_mouse_delta: Vec2<f32>,
/// Units scrolled in the last frame. 1.0 corresponds to one tick of the wheel
pub mouse_scroll: f32,
/// The state of mouse keys. 0 is left, 1 is right, 2 is middle. 3 and 4 are usually the keys
/// for clicking the mousewheel laterally, for mice that have such keys. Sometimes they are
/// also placed on the side of the mouse.
///
/// On linux, 3 and 4 are always `Up`, because these codes are used for the scroll wheel
/// internally.
pub mouse_keys: [KeyState; MOUSE_KEYS],
/// The state of keyboard keys. Can also be accessed more ergonomically throug the
/// `Input::key()` method
pub keys: [KeyState; KEYBOARD_KEYS],
/// Cleared each frame. Contains typed characters in the order they where typed
pub type_buffer: String,
pub window_has_keyboard_focus: bool,
pub received_events_this_frame: bool,
#[cfg(feature = "gamepad")]
pub gamepads: [Gamepad; 4],
}
impl Input {
pub fn new() -> Input {
Input {
mouse_pos: Vec2::ZERO,
mouse_delta: Vec2::ZERO,
raw_mouse_delta: Vec2::ZERO,
mouse_scroll: 0.0,
mouse_keys: [KeyState::Up; MOUSE_KEYS],
keys: [KeyState::Up; KEYBOARD_KEYS],
type_buffer: String::with_capacity(10),
window_has_keyboard_focus: false,
received_events_this_frame: false,
#[cfg(feature = "gamepad")]
gamepads: [Default::default(), Default::default(), Default::default(), Default::default()],
}
}
// Called by `Window::poll_events` in the platform layer
pub(crate) fn refresh(&mut self) {
self.mouse_delta = Vec2::ZERO;
self.raw_mouse_delta = Vec2::ZERO;
self.mouse_scroll = 0.0;
self.type_buffer.clear();
for state in self.mouse_keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state != KeyState::PressedRepeat);
}
for state in self.keys.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
if *state == KeyState::PressedRepeat { *state = KeyState::Down; }
}
#[cfg(feature = "gamepad")]
for gamepad in self.gamepads.iter_mut() {
if gamepad.connected {
for state in gamepad.buttons.iter_mut() {
if *state == KeyState::Released { *state = KeyState::Up; }
if *state == KeyState::Pressed { *state = KeyState::Down; }
assert!(*state != KeyState::PressedRepeat);
}
} else {
gamepad.buttons = [KeyState::Up; GAMEPAD_BUTTON_COUNT];
gamepad.left = Vec2::ZERO;
gamepad.right = Vec2::ZERO;
gamepad.left_trigger = 0.0;
gamepad.right_trigger = 0.0;
}
}
self.received_events_this_frame = false;
}
/// The state of the given keyboard key. Note that `Key` represent scancodes.
/// See [`Key`](enum.Key.html) for more info
pub fn key(&self, key: Key) -> KeyState {
self.keys[key as usize]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KeyState {
/// The button is not held down.
Up,
/// The button is being held down. In the previous frame it was not held down.
Pressed,
/// The button is being held down, and its repeat action triggered
PressedRepeat,
/// The button is being held down.
Down,
/// The button is not being held down. In the previous frame it was held down.
Released,
}
impl Default for KeyState {
fn default() -> KeyState { KeyState::Up }
}
impl KeyState {
/// Returns true if the button is being held down (`Down` or `Pressed`) and
/// false otherwise (`Up`, `Released` or `PressedRepeat`).
pub fn down(self) -> bool {
match self {
KeyState::Up | KeyState::Released => false,
KeyState::Down | KeyState::Pressed | KeyState::PressedRepeat => true,
}
}
/// Returns true if the button is not being held down (`Up` or `Released`) and
/// false otherwise (`Down` or `Pressed`).
pub fn | (self) -> bool {
!self.down()
}
/// Returns true if the button is being held down, but was not held down in the last
/// frame (`Pressed`)
pub fn pressed(self) -> bool { self == KeyState::Pressed }
/// Returns true either if this button is being held down and was not held down in the
/// last frame (`Pressed`), or if the repeat action has been triggered by the key being
/// held down for an extended amount of time (`PressedRepeat`).
pub fn pressed_repeat(self) -> bool {
self == KeyState::Pressed || self == KeyState::PressedRepeat
}
/// Returns true if the button is being not held down, but was held down in the last
/// frame (`Released`)
pub fn released(self) -> bool { self == KeyState::Released }
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position
/// on the keyboard, rather than a specific symbol. These can be used as parameters
/// to [`InputManager::key`](struct.InputManager.html#method.key). The names are
/// based on the american keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "linux")]
#[repr(u8)]
pub enum Key {
Key1 = 0xa, Key2 = 0xb, Key3 = 0xc, Key4 = 0xd, Key5 = 0xe,
Key6 = 0xf, Key7 = 0x10, Key8 = 0x11, Key9 = 0x12, Key0 = 0x13,
Q = 0x18, W = 0x19, E = 0x1a, R = 0x1b, T = 0x1c, Y = 0x1d, U = 0x1e, I = 0x1f, O = 0x20, P = 0x21,
A = 0x26, S = 0x27, D = 0x28, F = 0x29, G = 0x2a, H = 0x2b, J = 0x2c, K = 0x2d, L = 0x2e,
Z = 0x34, X = 0x35, C = 0x36, V = 0x37, B = 0x38, N = 0x39, M = 0x3a,
Space = 0x41,
Escape = 0x9, Grave = 0x31, Tab = 0x17, CapsLock = 0x42,
LShift = 0x32, LCtrl = 0x25, LAlt = 0x40,
RAlt = 0x6c, RMeta = 0x86, RCtrl = 0x69, RShift = 0x3e, Return = 0x24, Back = 0x16,
Right = 0x72, Left = 0x71, Down = 0x74, Up = 0x6f,
Insert = 0x76, Delete = 0x77, Home = 0x6e, End = 0x73, PageUp = 0x70, PageDown = 0x75,
F1 = 0x43, F2 = 0x44, F3 = 0x45, F4 = 0x46, F5 = 0x47, F6 = 0x48,
F7 = 0x49, F8 = 0x4a, F9 = 0x4b, F10 = 0x4c, F11 = 0x5f, F12 = 0x60,
}
/// Codes for most keys. Note that these are scancodes, so they refer to a position on the
/// keyboard, rather than a specific symbol. These can be used as parameters to
/// [`InputManager::key`](struct.InputManager.html#method.key). The names are based on the american
/// keyboard layout.
///
/// Scancodes are target specific, so the values asigned to each enum name might vary from platform
/// to platform. On some platforms not all keys are available. Check the source code for more
/// detailed information on this.
#[derive(Debug, Copy, Clone)]
#[cfg(target_os = "windows")]
#[repr(u8)]
pub enum Key {
Key1 = 0x2, Key2 = 0x3, Key3 = 0x4, Key4 = 0x5, Key5 = 0x6,
Key6 = 0x7, Key7 = 0x8, Key8 = 0x9, Key9 = 0xa, Key0 = 0xb,
Q = 0x10, W = 0x11, E = 0x12, R = 0x13, T = 0x14, Y = 0x15, U = 0x16, I = 0x17, O = 0x18, P = 0x19,
A = 0x1e, S = 0x1f, D = 0x20, F = 0x21, G = 0x22, H = 0x23, J = 0x24, K = 0x25, L = 0x26,
Z = 0x2c, X = 0x2d, C = 0x2e, V = 0x2f, B = 0x30, N = 0x31, M = 0x32,
Space = 0x39,
Escape = 0x1,
// Grave = 0x31,
Tab = 0xf,
// CapsLock = 0x42,
LShift = 0x2a,
LCtrl = 0x1d,
// LAlt = 0x40,
// RAlt = 0x6c,
// RMeta = 0x86,
// RCtrl = 0x1d, // Same scancode as LCtrl :/
RShift = 0x36,
Return = 0x1c,
Back = 0xe,
Right = 0x4d, Left = 0x4b, Down = 0x50, Up = 0x48,
Insert = 0x52, Delete = 0x53, Home = 0x47, End = 0x4f, PageUp = 0x49, PageDown = 0x51,
F1 = 0x3b, F2 = 0x3c, F3 = 0x3d, F4 = 0x3e, F5 = 0x3f, F6 = 0x40,
F7 = 0x41, F8 = 0x42, F9 = 0x43, F10 = 0x44, F11 = 0x57, F12 = 0x58,
}
#[cfg(feature = "gamepad")]
#[derive(Clone, Default)]
pub struct Gamepad {
pub connected: bool,
pub buttons: [KeyState; GAMEPAD_BUTTON_COUNT],
pub left: Vec2<f32>,
pub right: Vec2<f32>,
pub left_trigger: f32,
pub right_trigger: f32,
}
#[cfg(feature = "gamepad")]
const GAMEPAD_BUTTON_COUNT: usize = 24;
#[cfg(feature = "gamepad")]
#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum GamepadButton {
DpadUp = 0,
DpadDown,
DpadLeft,
DpadRight,
LeftUp,
LeftDown,
LeftRight,
LeftLeft,
RightUp,
RightDown,
RightRight,
RightLeft,
Start,
Back,
LeftStick,
RightStick,
LeftBumper,
RightBumper,
LeftTrigger,
RightTrigger,
A, B, X, Y,
}
#[cfg(feature = "gamepad")]
impl Gamepad {
pub fn button(&self, button: GamepadButton) -> KeyState {
self.buttons[button as usize]
}
}
| up | identifier_name |
insert.rs | use redox::*;
use super::*; | pub enum InsertMode {
Append,
Insert,
Replace,
}
#[derive(Clone, PartialEq, Copy)]
/// The insert options
pub struct InsertOptions {
/// The mode type
pub mode: InsertMode,
}
impl Editor {
/// Insert text
pub fn insert(&mut self, c: Key) {
let x = self.x();
let y = self.y();
match c {
Key::Char('\n') => {
let ln = self.text[y].clone();
let (slice, _) = ln.as_slices();
let first_part = (&slice[..x]).clone();
let second_part = (&slice[x..]).clone();
self.text[y] = VecDeque::from_iter(first_part.iter().map(|x| *x));
self.text.insert(y + 1, VecDeque::from_iter(second_part.iter().map(|x| *x)));
self.next();
},
Key::Escape => { // Escape key
self.cursor_mut().mode = Mode::Command(CommandMode::Normal);
},
Key::Backspace => { // Backspace
if self.x() != 0 || self.y() != 0 {
self.previous();
self.delete();
}
},
Key::Char(ch) => {
self.text[y].insert(x, ch);
self.next();
}
_ => {},
}
}
} | use core::iter::FromIterator;
#[derive(Clone, PartialEq, Copy)]
/// The type of the insert mode | random_line_split |
insert.rs | use redox::*;
use super::*;
use core::iter::FromIterator;
#[derive(Clone, PartialEq, Copy)]
/// The type of the insert mode
pub enum InsertMode {
Append,
Insert,
Replace,
}
#[derive(Clone, PartialEq, Copy)]
/// The insert options
pub struct | {
/// The mode type
pub mode: InsertMode,
}
impl Editor {
/// Insert text
pub fn insert(&mut self, c: Key) {
let x = self.x();
let y = self.y();
match c {
Key::Char('\n') => {
let ln = self.text[y].clone();
let (slice, _) = ln.as_slices();
let first_part = (&slice[..x]).clone();
let second_part = (&slice[x..]).clone();
self.text[y] = VecDeque::from_iter(first_part.iter().map(|x| *x));
self.text.insert(y + 1, VecDeque::from_iter(second_part.iter().map(|x| *x)));
self.next();
},
Key::Escape => { // Escape key
self.cursor_mut().mode = Mode::Command(CommandMode::Normal);
},
Key::Backspace => { // Backspace
if self.x() != 0 || self.y() != 0 {
self.previous();
self.delete();
}
},
Key::Char(ch) => {
self.text[y].insert(x, ch);
self.next();
}
_ => {},
}
}
}
| InsertOptions | identifier_name |
insert.rs | use redox::*;
use super::*;
use core::iter::FromIterator;
#[derive(Clone, PartialEq, Copy)]
/// The type of the insert mode
pub enum InsertMode {
Append,
Insert,
Replace,
}
#[derive(Clone, PartialEq, Copy)]
/// The insert options
pub struct InsertOptions {
/// The mode type
pub mode: InsertMode,
}
impl Editor {
/// Insert text
pub fn insert(&mut self, c: Key) {
let x = self.x();
let y = self.y();
match c {
Key::Char('\n') => {
let ln = self.text[y].clone();
let (slice, _) = ln.as_slices();
let first_part = (&slice[..x]).clone();
let second_part = (&slice[x..]).clone();
self.text[y] = VecDeque::from_iter(first_part.iter().map(|x| *x));
self.text.insert(y + 1, VecDeque::from_iter(second_part.iter().map(|x| *x)));
self.next();
},
Key::Escape => { // Escape key
self.cursor_mut().mode = Mode::Command(CommandMode::Normal);
},
Key::Backspace => { // Backspace
if self.x() != 0 || self.y() != 0 {
self.previous();
self.delete();
}
},
Key::Char(ch) => |
_ => {},
}
}
}
| {
self.text[y].insert(x, ch);
self.next();
} | conditional_block |
discovery_utils.ts | /**
* @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 {Injector} from '../../di/injector';
import {assertLView} from '../assert';
import {discoverLocalRefs, getComponentAtNodeIndex, getDirectivesAtNodeIndex, getLContext} from '../context_discovery';
import {NodeInjector} from '../di';
import {DebugNode, buildDebugNode} from '../instructions/lview_debug';
import {LContext} from '../interfaces/context';
import {DirectiveDef} from '../interfaces/definition';
import {TElementNode, TNode, TNodeProviderIndexes} from '../interfaces/node';
import {isLView} from '../interfaces/type_checks';
import {CLEANUP, CONTEXT, FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, TVIEW, T_HOST} from '../interfaces/view';
import {stringifyForError} from './misc_utils';
import {getLViewParent, getRootContext} from './view_traversal_utils';
import {getTNode, unwrapRNode} from './view_utils';
/**
* Retrieves the component instance associated with a given DOM element.
*
* @usageNotes
* Given the following DOM structure:
* ```html
* <my-app>
* <div>
* <child-comp></child-comp>
* </div>
* </my-app>
* ```
* Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
* associated with this DOM element.
*
* Calling the function on `<my-app>` will return the `MyApp` instance.
*
*
* @param element DOM element from which the component should be retrieved.
* @returns Component instance associated with the element or `null` if there
* is no component associated with it.
*
* @publicApi
* @globalApi ng
*/
export function getComponent<T>(element: Element): T|null {
assertDomElement(element);
const context = loadLContext(element, false);
if (context === null) return null;
if (context.component === undefined) {
context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView);
}
return context.component as T;
}
/**
* If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
* view that the element is part of. Otherwise retrieves the instance of the component whose view
* owns the element (in this case, the result is the same as calling `getOwningComponent`).
*
* @param element Element for which to get the surrounding component instance.
* @returns Instance of the component that is around the element or null if the element isn't
* inside any component.
*
* @publicApi
* @globalApi ng
*/
export function getContext<T>(element: Element): T|null {
assertDomElement(element);
const context = loadLContext(element, false);
return context === null ? null : context.lView[CONTEXT] as T;
}
/**
* Retrieves the component instance whose view contains the DOM element.
*
* For example, if `<child-comp>` is used in the template of `<app-comp>`
* (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
* would return `<app-comp>`.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Component instance whose view owns the DOM element or null if the element is not
* part of a component view.
*
* @publicApi
* @globalApi ng
*/
export function getOwningComponent<T>(elementOrDir: Element | {}): T|null {
const context = loadLContext(elementOrDir, false);
if (context === null) return null;
let lView = context.lView;
let parent: LView|null;
ngDevMode && assertLView(lView);
while (lView[HOST] === null && (parent = getLViewParent(lView) !)) {
// As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf`
lView = parent;
}
return lView[FLAGS] & LViewFlags.IsRoot ? null : lView[CONTEXT] as T;
}
/**
* Retrieves all root components associated with a DOM element, directive or component instance.
* Root components are those which have been bootstrapped by Angular.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Root components associated with the target object.
*
* @publicApi
* @globalApi ng
*/
export function getRootComponents(elementOrDir: Element | {}): {}[] {
return [...getRootContext(elementOrDir).components];
}
/**
* Retrieves an `Injector` associated with an element, component or directive instance.
*
* @param elementOrDir DOM element, component or directive instance for which to
* retrieve the injector.
* @returns Injector associated with the element, component or directive instance.
*
* @publicApi
* @globalApi ng
*/
export function getInjector(elementOrDir: Element | {}): Injector {
const context = loadLContext(elementOrDir, false);
if (context === null) return Injector.NULL;
const tNode = context.lView[TVIEW].data[context.nodeIndex] as TElementNode;
return new NodeInjector(tNode, context.lView);
}
/**
* Retrieve a set of injection tokens at a given DOM node.
*
* @param element Element for which the injection tokens should be retrieved.
*/
export function getInjectionTokens(element: Element): any[] {
const context = loadLContext(element, false);
if (context === null) return [];
const lView = context.lView;
const tView = lView[TVIEW];
const tNode = tView.data[context.nodeIndex] as TNode;
const providerTokens: any[] = [];
const startIndex = tNode.providerIndexes & TNodeProviderIndexes.ProvidersStartIndexMask;
const endIndex = tNode.directiveEnd;
for (let i = startIndex; i < endIndex; i++) {
let value = tView.data[i];
if (isDirectiveDefHack(value)) {
// The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
// design flaw. We should always store same type so that we can be monomorphic. The issue
// is that for Components/Directives we store the def instead the type. The correct behavior
// is that we should always be storing injectable type in this location.
value = value.type;
}
providerTokens.push(value);
}
return providerTokens;
}
/**
* Retrieves directive instances associated with a given DOM element. Does not include
* component instances.
*
* @usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <button my-button></button>
* <my-comp></my-comp>
* </my-app>
* ```
* Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
* directive that is associated with the DOM element.
*
* Calling `getDirectives` on `<my-comp>` will return an empty array.
*
* @param element DOM element for which to get the directives.
* @returns Array of directives associated with the element.
*
* @publicApi
* @globalApi ng
*/
export function getDirectives(element: Element): {}[] {
const context = loadLContext(element) !;
if (context.directives === undefined) {
context.directives = getDirectivesAtNodeIndex(context.nodeIndex, context.lView, false);
}
// The `directives` in this case are a named array called `LComponentView`. Clone the
// result so we don't expose an internal data structure in the user's console.
return context.directives === null ? [] : [...context.directives];
}
/**
* Returns LContext associated with a target passed as an argument.
* Throws if a given target doesn't have associated LContext.
*/
export function loadLContext(target: {}): LContext;
export function loadLContext(target: {}, throwOnNotFound: false): LContext|null;
export function loadLContext(target: {}, throwOnNotFound: boolean = true): LContext|null {
const context = getLContext(target);
if (!context && throwOnNotFound) {
throw new Error(
ngDevMode ? `Unable to find context associated with ${stringifyForError(target)}` :
'Invalid ng target');
}
return context;
}
/**
* Retrieve map of local references.
*
* The references are retrieved as a map of local reference name to element or directive instance.
*
* @param target DOM element, component or directive instance for which to retrieve
* the local references.
*/
export function getLocalRefs(target: {}): {[key: string]: any} {
const context = loadLContext(target, false);
if (context === null) return {};
if (context.localRefs === undefined) {
context.localRefs = discoverLocalRefs(context.lView, context.nodeIndex);
}
return context.localRefs || {};
}
/**
* Retrieves the host element of a component or directive instance.
* The host element is the DOM element that matched the selector of the directive.
*
* @param componentOrDirective Component or directive instance for which the host
* element should be retrieved.
* @returns Host element of the target.
*
* @publicApi
* @globalApi ng
*/
export function getHostElement(componentOrDirective: {}): Element {
return getLContext(componentOrDirective) !.native as never as Element;
}
/**
* Retrieves the rendered text for a given component.
*
* This function retrieves the host element of a component and
* and then returns the `textContent` for that element. This implies
* that the text returned will include re-projected content of
* the component as well.
*
* @param component The component to return the content text for.
*/
export function getRenderedText(component: any): string {
const hostElement = getHostElement(component);
return hostElement.textContent || '';
}
export function loadLContextFromNode(node: Node): LContext {
if (!(node instanceof Node)) throw new Error('Expecting instance of DOM Element');
return loadLContext(node) !;
}
/**
* Event listener configuration returned from `getListeners`.
* @publicApi
*/
export interface Listener {
/** Name of the event listener. */
name: string;
/** Element that the listener is bound to. */
element: Element;
/** Callback that is invoked when the event is triggered. */
callback: (value: any) => any;
/** Whether the listener is using event capturing. */
useCapture: boolean;
/**
* Type of the listener (e.g. a native DOM event or a custom @Output).
*/
type: 'dom'|'output';
}
/**
* Retrieves a list of event listeners associated with a DOM element. The list does include host
* listeners, but it does not include event listeners defined outside of the Angular context
* (e.g. through `addEventListener`).
*
* @usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <div (click)="doSomething()"></div>
* </my-app>
*
* ```
* Calling `getListeners` on `<div>` will return an object that looks as follows:
* ```
* {
* name: 'click',
* element: <div>,
* callback: () => doSomething(),
* useCapture: false
* }
* ```
*
* @param element Element for which the DOM listeners should be retrieved.
* @returns Array of event listeners on the DOM element.
*
* @publicApi
* @globalApi ng
*/
export function getListeners(element: Element): Listener[] {
assertDomElement(element);
const lContext = loadLContext(element, false);
if (lContext === null) return [];
const lView = lContext.lView;
const tView = lView[TVIEW];
const lCleanup = lView[CLEANUP];
const tCleanup = tView.cleanup;
const listeners: Listener[] = [];
if (tCleanup && lCleanup) {
for (let i = 0; i < tCleanup.length;) {
const firstParam = tCleanup[i++];
const secondParam = tCleanup[i++];
if (typeof firstParam === 'string') {
const name: string = firstParam;
const listenerElement = unwrapRNode(lView[secondParam]) as any as Element;
const callback: (value: any) => any = lCleanup[tCleanup[i++]];
const useCaptureOrIndx = tCleanup[i++];
// if useCaptureOrIndx is boolean then report it as is.
// if useCaptureOrIndx is positive number then it in unsubscribe method
// if useCaptureOrIndx is negative number then it is a Subscription
const type =
(typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0) ? 'dom' : 'output';
const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
if (element == listenerElement) {
listeners.push({element, name, callback, useCapture, type});
}
}
}
}
listeners.sort(sortListeners);
return listeners;
}
function sortListeners(a: Listener, b: Listener) {
if (a.name == b.name) return 0;
return a.name < b.name ? -1 : 1;
}
/**
* This function should not exist because it is megamorphic and only mostly correct.
*
* See call site for more info.
*/
function isDirectiveDefHack(obj: any): obj is DirectiveDef<any> |
/**
* Returns the attached `DebugNode` instance for an element in the DOM.
*
* @param element DOM element which is owned by an existing component's view.
*/
export function getDebugNode(element: Element): DebugNode|null {
let debugNode: DebugNode|null = null;
const lContext = loadLContextFromNode(element);
const lView = lContext.lView;
const nodeIndex = lContext.nodeIndex;
if (nodeIndex !== -1) {
const valueInLView = lView[nodeIndex];
// this means that value in the lView is a component with its own
// data. In this situation the TNode is not accessed at the same spot.
const tNode = isLView(valueInLView) ? (valueInLView[T_HOST] as TNode) :
getTNode(lView[TVIEW], nodeIndex - HEADER_OFFSET);
debugNode = buildDebugNode(tNode, lView, nodeIndex);
}
return debugNode;
}
/**
* Retrieve the component `LView` from component/element.
*
* NOTE: `LView` is a private and should not be leaked outside.
* Don't export this method to `ng.*` on window.
*
* @param target DOM element or component instance for which to retrieve the LView.
*/
export function getComponentLView(target: any): LView {
const lContext = loadLContext(target);
const nodeIndx = lContext.nodeIndex;
const lView = lContext.lView;
const componentLView = lView[nodeIndx];
ngDevMode && assertLView(componentLView);
return componentLView;
}
/** Asserts that a value is a DOM Element. */
function assertDomElement(value: any) {
if (typeof Element !== 'undefined' && !(value instanceof Element)) {
throw new Error('Expecting instance of DOM Element');
}
}
| {
return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined;
} | identifier_body |
discovery_utils.ts | /**
* @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 {Injector} from '../../di/injector';
import {assertLView} from '../assert';
import {discoverLocalRefs, getComponentAtNodeIndex, getDirectivesAtNodeIndex, getLContext} from '../context_discovery';
import {NodeInjector} from '../di';
import {DebugNode, buildDebugNode} from '../instructions/lview_debug';
import {LContext} from '../interfaces/context';
import {DirectiveDef} from '../interfaces/definition';
import {TElementNode, TNode, TNodeProviderIndexes} from '../interfaces/node';
import {isLView} from '../interfaces/type_checks';
import {CLEANUP, CONTEXT, FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, TVIEW, T_HOST} from '../interfaces/view';
import {stringifyForError} from './misc_utils';
import {getLViewParent, getRootContext} from './view_traversal_utils';
import {getTNode, unwrapRNode} from './view_utils';
/**
* Retrieves the component instance associated with a given DOM element.
*
* @usageNotes
* Given the following DOM structure:
* ```html
* <my-app>
* <div>
* <child-comp></child-comp>
* </div>
* </my-app>
* ```
* Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
* associated with this DOM element.
*
* Calling the function on `<my-app>` will return the `MyApp` instance.
*
*
* @param element DOM element from which the component should be retrieved.
* @returns Component instance associated with the element or `null` if there
* is no component associated with it.
*
* @publicApi
* @globalApi ng
*/
export function getComponent<T>(element: Element): T|null {
assertDomElement(element);
const context = loadLContext(element, false);
if (context === null) return null;
if (context.component === undefined) {
context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView);
}
return context.component as T;
}
/**
* If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
* view that the element is part of. Otherwise retrieves the instance of the component whose view
* owns the element (in this case, the result is the same as calling `getOwningComponent`).
*
* @param element Element for which to get the surrounding component instance.
* @returns Instance of the component that is around the element or null if the element isn't
* inside any component.
*
* @publicApi
* @globalApi ng
*/
export function getContext<T>(element: Element): T|null {
assertDomElement(element);
const context = loadLContext(element, false);
return context === null ? null : context.lView[CONTEXT] as T;
}
/**
* Retrieves the component instance whose view contains the DOM element.
*
* For example, if `<child-comp>` is used in the template of `<app-comp>`
* (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
* would return `<app-comp>`.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Component instance whose view owns the DOM element or null if the element is not
* part of a component view.
*
* @publicApi
* @globalApi ng
*/
export function getOwningComponent<T>(elementOrDir: Element | {}): T|null {
const context = loadLContext(elementOrDir, false);
if (context === null) return null;
let lView = context.lView;
let parent: LView|null;
ngDevMode && assertLView(lView);
while (lView[HOST] === null && (parent = getLViewParent(lView) !)) {
// As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf`
lView = parent;
}
return lView[FLAGS] & LViewFlags.IsRoot ? null : lView[CONTEXT] as T;
}
/**
* Retrieves all root components associated with a DOM element, directive or component instance.
* Root components are those which have been bootstrapped by Angular.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Root components associated with the target object.
*
* @publicApi
* @globalApi ng
*/
export function getRootComponents(elementOrDir: Element | {}): {}[] {
return [...getRootContext(elementOrDir).components];
}
/**
* Retrieves an `Injector` associated with an element, component or directive instance.
*
* @param elementOrDir DOM element, component or directive instance for which to
* retrieve the injector.
* @returns Injector associated with the element, component or directive instance.
*
* @publicApi
* @globalApi ng
*/
export function getInjector(elementOrDir: Element | {}): Injector {
const context = loadLContext(elementOrDir, false);
if (context === null) return Injector.NULL;
const tNode = context.lView[TVIEW].data[context.nodeIndex] as TElementNode;
return new NodeInjector(tNode, context.lView);
}
/**
* Retrieve a set of injection tokens at a given DOM node.
*
* @param element Element for which the injection tokens should be retrieved.
*/
export function getInjectionTokens(element: Element): any[] {
const context = loadLContext(element, false);
if (context === null) return [];
const lView = context.lView;
const tView = lView[TVIEW];
const tNode = tView.data[context.nodeIndex] as TNode;
const providerTokens: any[] = [];
const startIndex = tNode.providerIndexes & TNodeProviderIndexes.ProvidersStartIndexMask;
const endIndex = tNode.directiveEnd;
for (let i = startIndex; i < endIndex; i++) {
let value = tView.data[i];
if (isDirectiveDefHack(value)) {
// The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
// design flaw. We should always store same type so that we can be monomorphic. The issue
// is that for Components/Directives we store the def instead the type. The correct behavior
// is that we should always be storing injectable type in this location.
value = value.type;
}
providerTokens.push(value);
}
return providerTokens;
}
/**
* Retrieves directive instances associated with a given DOM element. Does not include
* component instances.
*
* @usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <button my-button></button>
* <my-comp></my-comp>
* </my-app>
* ```
* Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
* directive that is associated with the DOM element.
*
* Calling `getDirectives` on `<my-comp>` will return an empty array.
*
* @param element DOM element for which to get the directives.
* @returns Array of directives associated with the element.
*
* @publicApi
* @globalApi ng
*/
export function getDirectives(element: Element): {}[] {
const context = loadLContext(element) !;
if (context.directives === undefined) {
context.directives = getDirectivesAtNodeIndex(context.nodeIndex, context.lView, false);
}
// The `directives` in this case are a named array called `LComponentView`. Clone the
// result so we don't expose an internal data structure in the user's console.
return context.directives === null ? [] : [...context.directives];
}
/**
* Returns LContext associated with a target passed as an argument.
* Throws if a given target doesn't have associated LContext.
*/
export function loadLContext(target: {}): LContext;
export function loadLContext(target: {}, throwOnNotFound: false): LContext|null;
export function loadLContext(target: {}, throwOnNotFound: boolean = true): LContext|null {
const context = getLContext(target);
if (!context && throwOnNotFound) {
throw new Error(
ngDevMode ? `Unable to find context associated with ${stringifyForError(target)}` :
'Invalid ng target');
}
return context;
}
/**
* Retrieve map of local references.
*
* The references are retrieved as a map of local reference name to element or directive instance.
*
* @param target DOM element, component or directive instance for which to retrieve
* the local references.
*/
export function getLocalRefs(target: {}): {[key: string]: any} {
const context = loadLContext(target, false);
if (context === null) return {};
if (context.localRefs === undefined) {
context.localRefs = discoverLocalRefs(context.lView, context.nodeIndex);
}
return context.localRefs || {};
}
/**
* Retrieves the host element of a component or directive instance.
* The host element is the DOM element that matched the selector of the directive.
*
* @param componentOrDirective Component or directive instance for which the host
* element should be retrieved.
* @returns Host element of the target.
*
* @publicApi
* @globalApi ng
*/
export function getHostElement(componentOrDirective: {}): Element {
return getLContext(componentOrDirective) !.native as never as Element;
}
/**
* Retrieves the rendered text for a given component.
*
* This function retrieves the host element of a component and
* and then returns the `textContent` for that element. This implies
* that the text returned will include re-projected content of
* the component as well.
*
* @param component The component to return the content text for.
*/
export function | (component: any): string {
const hostElement = getHostElement(component);
return hostElement.textContent || '';
}
export function loadLContextFromNode(node: Node): LContext {
if (!(node instanceof Node)) throw new Error('Expecting instance of DOM Element');
return loadLContext(node) !;
}
/**
* Event listener configuration returned from `getListeners`.
* @publicApi
*/
export interface Listener {
/** Name of the event listener. */
name: string;
/** Element that the listener is bound to. */
element: Element;
/** Callback that is invoked when the event is triggered. */
callback: (value: any) => any;
/** Whether the listener is using event capturing. */
useCapture: boolean;
/**
* Type of the listener (e.g. a native DOM event or a custom @Output).
*/
type: 'dom'|'output';
}
/**
* Retrieves a list of event listeners associated with a DOM element. The list does include host
* listeners, but it does not include event listeners defined outside of the Angular context
* (e.g. through `addEventListener`).
*
* @usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <div (click)="doSomething()"></div>
* </my-app>
*
* ```
* Calling `getListeners` on `<div>` will return an object that looks as follows:
* ```
* {
* name: 'click',
* element: <div>,
* callback: () => doSomething(),
* useCapture: false
* }
* ```
*
* @param element Element for which the DOM listeners should be retrieved.
* @returns Array of event listeners on the DOM element.
*
* @publicApi
* @globalApi ng
*/
export function getListeners(element: Element): Listener[] {
assertDomElement(element);
const lContext = loadLContext(element, false);
if (lContext === null) return [];
const lView = lContext.lView;
const tView = lView[TVIEW];
const lCleanup = lView[CLEANUP];
const tCleanup = tView.cleanup;
const listeners: Listener[] = [];
if (tCleanup && lCleanup) {
for (let i = 0; i < tCleanup.length;) {
const firstParam = tCleanup[i++];
const secondParam = tCleanup[i++];
if (typeof firstParam === 'string') {
const name: string = firstParam;
const listenerElement = unwrapRNode(lView[secondParam]) as any as Element;
const callback: (value: any) => any = lCleanup[tCleanup[i++]];
const useCaptureOrIndx = tCleanup[i++];
// if useCaptureOrIndx is boolean then report it as is.
// if useCaptureOrIndx is positive number then it in unsubscribe method
// if useCaptureOrIndx is negative number then it is a Subscription
const type =
(typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0) ? 'dom' : 'output';
const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
if (element == listenerElement) {
listeners.push({element, name, callback, useCapture, type});
}
}
}
}
listeners.sort(sortListeners);
return listeners;
}
function sortListeners(a: Listener, b: Listener) {
if (a.name == b.name) return 0;
return a.name < b.name ? -1 : 1;
}
/**
* This function should not exist because it is megamorphic and only mostly correct.
*
* See call site for more info.
*/
function isDirectiveDefHack(obj: any): obj is DirectiveDef<any> {
return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined;
}
/**
* Returns the attached `DebugNode` instance for an element in the DOM.
*
* @param element DOM element which is owned by an existing component's view.
*/
export function getDebugNode(element: Element): DebugNode|null {
let debugNode: DebugNode|null = null;
const lContext = loadLContextFromNode(element);
const lView = lContext.lView;
const nodeIndex = lContext.nodeIndex;
if (nodeIndex !== -1) {
const valueInLView = lView[nodeIndex];
// this means that value in the lView is a component with its own
// data. In this situation the TNode is not accessed at the same spot.
const tNode = isLView(valueInLView) ? (valueInLView[T_HOST] as TNode) :
getTNode(lView[TVIEW], nodeIndex - HEADER_OFFSET);
debugNode = buildDebugNode(tNode, lView, nodeIndex);
}
return debugNode;
}
/**
* Retrieve the component `LView` from component/element.
*
* NOTE: `LView` is a private and should not be leaked outside.
* Don't export this method to `ng.*` on window.
*
* @param target DOM element or component instance for which to retrieve the LView.
*/
export function getComponentLView(target: any): LView {
const lContext = loadLContext(target);
const nodeIndx = lContext.nodeIndex;
const lView = lContext.lView;
const componentLView = lView[nodeIndx];
ngDevMode && assertLView(componentLView);
return componentLView;
}
/** Asserts that a value is a DOM Element. */
function assertDomElement(value: any) {
if (typeof Element !== 'undefined' && !(value instanceof Element)) {
throw new Error('Expecting instance of DOM Element');
}
}
| getRenderedText | identifier_name |
discovery_utils.ts | /**
* @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 {Injector} from '../../di/injector';
import {assertLView} from '../assert';
import {discoverLocalRefs, getComponentAtNodeIndex, getDirectivesAtNodeIndex, getLContext} from '../context_discovery';
import {NodeInjector} from '../di';
import {DebugNode, buildDebugNode} from '../instructions/lview_debug';
import {LContext} from '../interfaces/context';
import {DirectiveDef} from '../interfaces/definition';
import {TElementNode, TNode, TNodeProviderIndexes} from '../interfaces/node';
import {isLView} from '../interfaces/type_checks';
import {CLEANUP, CONTEXT, FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, TVIEW, T_HOST} from '../interfaces/view';
import {stringifyForError} from './misc_utils';
import {getLViewParent, getRootContext} from './view_traversal_utils';
import {getTNode, unwrapRNode} from './view_utils';
/**
* Retrieves the component instance associated with a given DOM element.
*
* @usageNotes
* Given the following DOM structure:
* ```html
* <my-app>
* <div>
* <child-comp></child-comp>
* </div>
* </my-app>
* ```
* Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
* associated with this DOM element.
*
* Calling the function on `<my-app>` will return the `MyApp` instance.
*
*
* @param element DOM element from which the component should be retrieved.
* @returns Component instance associated with the element or `null` if there
* is no component associated with it.
*
* @publicApi
* @globalApi ng
*/
export function getComponent<T>(element: Element): T|null {
assertDomElement(element);
const context = loadLContext(element, false);
if (context === null) return null;
if (context.component === undefined) {
context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView);
}
return context.component as T;
}
/**
* If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
* view that the element is part of. Otherwise retrieves the instance of the component whose view
* owns the element (in this case, the result is the same as calling `getOwningComponent`).
*
* @param element Element for which to get the surrounding component instance.
* @returns Instance of the component that is around the element or null if the element isn't
* inside any component.
*
* @publicApi
* @globalApi ng
*/
export function getContext<T>(element: Element): T|null {
assertDomElement(element);
const context = loadLContext(element, false);
return context === null ? null : context.lView[CONTEXT] as T;
}
/**
* Retrieves the component instance whose view contains the DOM element.
*
* For example, if `<child-comp>` is used in the template of `<app-comp>`
* (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
* would return `<app-comp>`.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Component instance whose view owns the DOM element or null if the element is not
* part of a component view.
*
* @publicApi
* @globalApi ng
*/
export function getOwningComponent<T>(elementOrDir: Element | {}): T|null {
const context = loadLContext(elementOrDir, false);
if (context === null) return null;
let lView = context.lView;
let parent: LView|null;
ngDevMode && assertLView(lView);
while (lView[HOST] === null && (parent = getLViewParent(lView) !)) {
// As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf`
lView = parent;
}
return lView[FLAGS] & LViewFlags.IsRoot ? null : lView[CONTEXT] as T;
}
/**
* Retrieves all root components associated with a DOM element, directive or component instance.
* Root components are those which have been bootstrapped by Angular.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Root components associated with the target object.
*
* @publicApi
* @globalApi ng
*/
export function getRootComponents(elementOrDir: Element | {}): {}[] {
return [...getRootContext(elementOrDir).components];
}
/**
* Retrieves an `Injector` associated with an element, component or directive instance.
*
* @param elementOrDir DOM element, component or directive instance for which to
* retrieve the injector.
* @returns Injector associated with the element, component or directive instance.
*
* @publicApi
* @globalApi ng
*/
export function getInjector(elementOrDir: Element | {}): Injector {
const context = loadLContext(elementOrDir, false);
if (context === null) return Injector.NULL;
const tNode = context.lView[TVIEW].data[context.nodeIndex] as TElementNode;
return new NodeInjector(tNode, context.lView);
}
/**
* Retrieve a set of injection tokens at a given DOM node.
*
* @param element Element for which the injection tokens should be retrieved.
*/
export function getInjectionTokens(element: Element): any[] {
const context = loadLContext(element, false);
if (context === null) return [];
const lView = context.lView;
const tView = lView[TVIEW];
const tNode = tView.data[context.nodeIndex] as TNode;
const providerTokens: any[] = [];
const startIndex = tNode.providerIndexes & TNodeProviderIndexes.ProvidersStartIndexMask;
const endIndex = tNode.directiveEnd;
for (let i = startIndex; i < endIndex; i++) |
return providerTokens;
}
/**
* Retrieves directive instances associated with a given DOM element. Does not include
* component instances.
*
* @usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <button my-button></button>
* <my-comp></my-comp>
* </my-app>
* ```
* Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
* directive that is associated with the DOM element.
*
* Calling `getDirectives` on `<my-comp>` will return an empty array.
*
* @param element DOM element for which to get the directives.
* @returns Array of directives associated with the element.
*
* @publicApi
* @globalApi ng
*/
export function getDirectives(element: Element): {}[] {
const context = loadLContext(element) !;
if (context.directives === undefined) {
context.directives = getDirectivesAtNodeIndex(context.nodeIndex, context.lView, false);
}
// The `directives` in this case are a named array called `LComponentView`. Clone the
// result so we don't expose an internal data structure in the user's console.
return context.directives === null ? [] : [...context.directives];
}
/**
* Returns LContext associated with a target passed as an argument.
* Throws if a given target doesn't have associated LContext.
*/
export function loadLContext(target: {}): LContext;
export function loadLContext(target: {}, throwOnNotFound: false): LContext|null;
export function loadLContext(target: {}, throwOnNotFound: boolean = true): LContext|null {
const context = getLContext(target);
if (!context && throwOnNotFound) {
throw new Error(
ngDevMode ? `Unable to find context associated with ${stringifyForError(target)}` :
'Invalid ng target');
}
return context;
}
/**
* Retrieve map of local references.
*
* The references are retrieved as a map of local reference name to element or directive instance.
*
* @param target DOM element, component or directive instance for which to retrieve
* the local references.
*/
export function getLocalRefs(target: {}): {[key: string]: any} {
const context = loadLContext(target, false);
if (context === null) return {};
if (context.localRefs === undefined) {
context.localRefs = discoverLocalRefs(context.lView, context.nodeIndex);
}
return context.localRefs || {};
}
/**
* Retrieves the host element of a component or directive instance.
* The host element is the DOM element that matched the selector of the directive.
*
* @param componentOrDirective Component or directive instance for which the host
* element should be retrieved.
* @returns Host element of the target.
*
* @publicApi
* @globalApi ng
*/
export function getHostElement(componentOrDirective: {}): Element {
return getLContext(componentOrDirective) !.native as never as Element;
}
/**
* Retrieves the rendered text for a given component.
*
* This function retrieves the host element of a component and
* and then returns the `textContent` for that element. This implies
* that the text returned will include re-projected content of
* the component as well.
*
* @param component The component to return the content text for.
*/
export function getRenderedText(component: any): string {
const hostElement = getHostElement(component);
return hostElement.textContent || '';
}
export function loadLContextFromNode(node: Node): LContext {
if (!(node instanceof Node)) throw new Error('Expecting instance of DOM Element');
return loadLContext(node) !;
}
/**
* Event listener configuration returned from `getListeners`.
* @publicApi
*/
export interface Listener {
/** Name of the event listener. */
name: string;
/** Element that the listener is bound to. */
element: Element;
/** Callback that is invoked when the event is triggered. */
callback: (value: any) => any;
/** Whether the listener is using event capturing. */
useCapture: boolean;
/**
* Type of the listener (e.g. a native DOM event or a custom @Output).
*/
type: 'dom'|'output';
}
/**
* Retrieves a list of event listeners associated with a DOM element. The list does include host
* listeners, but it does not include event listeners defined outside of the Angular context
* (e.g. through `addEventListener`).
*
* @usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <div (click)="doSomething()"></div>
* </my-app>
*
* ```
* Calling `getListeners` on `<div>` will return an object that looks as follows:
* ```
* {
* name: 'click',
* element: <div>,
* callback: () => doSomething(),
* useCapture: false
* }
* ```
*
* @param element Element for which the DOM listeners should be retrieved.
* @returns Array of event listeners on the DOM element.
*
* @publicApi
* @globalApi ng
*/
export function getListeners(element: Element): Listener[] {
assertDomElement(element);
const lContext = loadLContext(element, false);
if (lContext === null) return [];
const lView = lContext.lView;
const tView = lView[TVIEW];
const lCleanup = lView[CLEANUP];
const tCleanup = tView.cleanup;
const listeners: Listener[] = [];
if (tCleanup && lCleanup) {
for (let i = 0; i < tCleanup.length;) {
const firstParam = tCleanup[i++];
const secondParam = tCleanup[i++];
if (typeof firstParam === 'string') {
const name: string = firstParam;
const listenerElement = unwrapRNode(lView[secondParam]) as any as Element;
const callback: (value: any) => any = lCleanup[tCleanup[i++]];
const useCaptureOrIndx = tCleanup[i++];
// if useCaptureOrIndx is boolean then report it as is.
// if useCaptureOrIndx is positive number then it in unsubscribe method
// if useCaptureOrIndx is negative number then it is a Subscription
const type =
(typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0) ? 'dom' : 'output';
const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
if (element == listenerElement) {
listeners.push({element, name, callback, useCapture, type});
}
}
}
}
listeners.sort(sortListeners);
return listeners;
}
function sortListeners(a: Listener, b: Listener) {
if (a.name == b.name) return 0;
return a.name < b.name ? -1 : 1;
}
/**
* This function should not exist because it is megamorphic and only mostly correct.
*
* See call site for more info.
*/
function isDirectiveDefHack(obj: any): obj is DirectiveDef<any> {
return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined;
}
/**
* Returns the attached `DebugNode` instance for an element in the DOM.
*
* @param element DOM element which is owned by an existing component's view.
*/
export function getDebugNode(element: Element): DebugNode|null {
let debugNode: DebugNode|null = null;
const lContext = loadLContextFromNode(element);
const lView = lContext.lView;
const nodeIndex = lContext.nodeIndex;
if (nodeIndex !== -1) {
const valueInLView = lView[nodeIndex];
// this means that value in the lView is a component with its own
// data. In this situation the TNode is not accessed at the same spot.
const tNode = isLView(valueInLView) ? (valueInLView[T_HOST] as TNode) :
getTNode(lView[TVIEW], nodeIndex - HEADER_OFFSET);
debugNode = buildDebugNode(tNode, lView, nodeIndex);
}
return debugNode;
}
/**
* Retrieve the component `LView` from component/element.
*
* NOTE: `LView` is a private and should not be leaked outside.
* Don't export this method to `ng.*` on window.
*
* @param target DOM element or component instance for which to retrieve the LView.
*/
export function getComponentLView(target: any): LView {
const lContext = loadLContext(target);
const nodeIndx = lContext.nodeIndex;
const lView = lContext.lView;
const componentLView = lView[nodeIndx];
ngDevMode && assertLView(componentLView);
return componentLView;
}
/** Asserts that a value is a DOM Element. */
function assertDomElement(value: any) {
if (typeof Element !== 'undefined' && !(value instanceof Element)) {
throw new Error('Expecting instance of DOM Element');
}
}
| {
let value = tView.data[i];
if (isDirectiveDefHack(value)) {
// The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
// design flaw. We should always store same type so that we can be monomorphic. The issue
// is that for Components/Directives we store the def instead the type. The correct behavior
// is that we should always be storing injectable type in this location.
value = value.type;
}
providerTokens.push(value);
} | conditional_block |
discovery_utils.ts | /**
* @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 {Injector} from '../../di/injector';
import {assertLView} from '../assert';
import {discoverLocalRefs, getComponentAtNodeIndex, getDirectivesAtNodeIndex, getLContext} from '../context_discovery';
import {NodeInjector} from '../di';
import {DebugNode, buildDebugNode} from '../instructions/lview_debug';
import {LContext} from '../interfaces/context';
import {DirectiveDef} from '../interfaces/definition';
import {TElementNode, TNode, TNodeProviderIndexes} from '../interfaces/node';
import {isLView} from '../interfaces/type_checks';
import {CLEANUP, CONTEXT, FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, TVIEW, T_HOST} from '../interfaces/view';
import {stringifyForError} from './misc_utils';
import {getLViewParent, getRootContext} from './view_traversal_utils';
import {getTNode, unwrapRNode} from './view_utils';
/**
* Retrieves the component instance associated with a given DOM element.
*
* @usageNotes
* Given the following DOM structure:
* ```html
* <my-app>
* <div>
* <child-comp></child-comp>
* </div>
* </my-app>
* ```
* Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
* associated with this DOM element.
*
* Calling the function on `<my-app>` will return the `MyApp` instance.
*
*
* @param element DOM element from which the component should be retrieved.
* @returns Component instance associated with the element or `null` if there
* is no component associated with it.
*
* @publicApi
* @globalApi ng
*/
export function getComponent<T>(element: Element): T|null {
assertDomElement(element);
const context = loadLContext(element, false);
if (context === null) return null;
if (context.component === undefined) {
context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView);
}
return context.component as T;
}
/**
* If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
* view that the element is part of. Otherwise retrieves the instance of the component whose view
* owns the element (in this case, the result is the same as calling `getOwningComponent`).
*
* @param element Element for which to get the surrounding component instance.
* @returns Instance of the component that is around the element or null if the element isn't
* inside any component.
*
* @publicApi
* @globalApi ng
*/
export function getContext<T>(element: Element): T|null {
assertDomElement(element);
const context = loadLContext(element, false);
return context === null ? null : context.lView[CONTEXT] as T;
}
/**
* Retrieves the component instance whose view contains the DOM element.
*
* For example, if `<child-comp>` is used in the template of `<app-comp>`
* (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
* would return `<app-comp>`.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Component instance whose view owns the DOM element or null if the element is not
* part of a component view.
*
* @publicApi
* @globalApi ng
*/
export function getOwningComponent<T>(elementOrDir: Element | {}): T|null {
const context = loadLContext(elementOrDir, false);
if (context === null) return null;
let lView = context.lView;
let parent: LView|null;
ngDevMode && assertLView(lView);
while (lView[HOST] === null && (parent = getLViewParent(lView) !)) {
// As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf`
lView = parent;
}
return lView[FLAGS] & LViewFlags.IsRoot ? null : lView[CONTEXT] as T;
}
/**
* Retrieves all root components associated with a DOM element, directive or component instance.
* Root components are those which have been bootstrapped by Angular.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Root components associated with the target object.
*
* @publicApi
* @globalApi ng
*/
export function getRootComponents(elementOrDir: Element | {}): {}[] {
return [...getRootContext(elementOrDir).components];
}
/**
* Retrieves an `Injector` associated with an element, component or directive instance. | * @publicApi
* @globalApi ng
*/
export function getInjector(elementOrDir: Element | {}): Injector {
const context = loadLContext(elementOrDir, false);
if (context === null) return Injector.NULL;
const tNode = context.lView[TVIEW].data[context.nodeIndex] as TElementNode;
return new NodeInjector(tNode, context.lView);
}
/**
* Retrieve a set of injection tokens at a given DOM node.
*
* @param element Element for which the injection tokens should be retrieved.
*/
export function getInjectionTokens(element: Element): any[] {
const context = loadLContext(element, false);
if (context === null) return [];
const lView = context.lView;
const tView = lView[TVIEW];
const tNode = tView.data[context.nodeIndex] as TNode;
const providerTokens: any[] = [];
const startIndex = tNode.providerIndexes & TNodeProviderIndexes.ProvidersStartIndexMask;
const endIndex = tNode.directiveEnd;
for (let i = startIndex; i < endIndex; i++) {
let value = tView.data[i];
if (isDirectiveDefHack(value)) {
// The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
// design flaw. We should always store same type so that we can be monomorphic. The issue
// is that for Components/Directives we store the def instead the type. The correct behavior
// is that we should always be storing injectable type in this location.
value = value.type;
}
providerTokens.push(value);
}
return providerTokens;
}
/**
* Retrieves directive instances associated with a given DOM element. Does not include
* component instances.
*
* @usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <button my-button></button>
* <my-comp></my-comp>
* </my-app>
* ```
* Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
* directive that is associated with the DOM element.
*
* Calling `getDirectives` on `<my-comp>` will return an empty array.
*
* @param element DOM element for which to get the directives.
* @returns Array of directives associated with the element.
*
* @publicApi
* @globalApi ng
*/
export function getDirectives(element: Element): {}[] {
const context = loadLContext(element) !;
if (context.directives === undefined) {
context.directives = getDirectivesAtNodeIndex(context.nodeIndex, context.lView, false);
}
// The `directives` in this case are a named array called `LComponentView`. Clone the
// result so we don't expose an internal data structure in the user's console.
return context.directives === null ? [] : [...context.directives];
}
/**
* Returns LContext associated with a target passed as an argument.
* Throws if a given target doesn't have associated LContext.
*/
export function loadLContext(target: {}): LContext;
export function loadLContext(target: {}, throwOnNotFound: false): LContext|null;
export function loadLContext(target: {}, throwOnNotFound: boolean = true): LContext|null {
const context = getLContext(target);
if (!context && throwOnNotFound) {
throw new Error(
ngDevMode ? `Unable to find context associated with ${stringifyForError(target)}` :
'Invalid ng target');
}
return context;
}
/**
* Retrieve map of local references.
*
* The references are retrieved as a map of local reference name to element or directive instance.
*
* @param target DOM element, component or directive instance for which to retrieve
* the local references.
*/
export function getLocalRefs(target: {}): {[key: string]: any} {
const context = loadLContext(target, false);
if (context === null) return {};
if (context.localRefs === undefined) {
context.localRefs = discoverLocalRefs(context.lView, context.nodeIndex);
}
return context.localRefs || {};
}
/**
* Retrieves the host element of a component or directive instance.
* The host element is the DOM element that matched the selector of the directive.
*
* @param componentOrDirective Component or directive instance for which the host
* element should be retrieved.
* @returns Host element of the target.
*
* @publicApi
* @globalApi ng
*/
export function getHostElement(componentOrDirective: {}): Element {
return getLContext(componentOrDirective) !.native as never as Element;
}
/**
* Retrieves the rendered text for a given component.
*
* This function retrieves the host element of a component and
* and then returns the `textContent` for that element. This implies
* that the text returned will include re-projected content of
* the component as well.
*
* @param component The component to return the content text for.
*/
export function getRenderedText(component: any): string {
const hostElement = getHostElement(component);
return hostElement.textContent || '';
}
export function loadLContextFromNode(node: Node): LContext {
if (!(node instanceof Node)) throw new Error('Expecting instance of DOM Element');
return loadLContext(node) !;
}
/**
* Event listener configuration returned from `getListeners`.
* @publicApi
*/
export interface Listener {
/** Name of the event listener. */
name: string;
/** Element that the listener is bound to. */
element: Element;
/** Callback that is invoked when the event is triggered. */
callback: (value: any) => any;
/** Whether the listener is using event capturing. */
useCapture: boolean;
/**
* Type of the listener (e.g. a native DOM event or a custom @Output).
*/
type: 'dom'|'output';
}
/**
* Retrieves a list of event listeners associated with a DOM element. The list does include host
* listeners, but it does not include event listeners defined outside of the Angular context
* (e.g. through `addEventListener`).
*
* @usageNotes
* Given the following DOM structure:
* ```
* <my-app>
* <div (click)="doSomething()"></div>
* </my-app>
*
* ```
* Calling `getListeners` on `<div>` will return an object that looks as follows:
* ```
* {
* name: 'click',
* element: <div>,
* callback: () => doSomething(),
* useCapture: false
* }
* ```
*
* @param element Element for which the DOM listeners should be retrieved.
* @returns Array of event listeners on the DOM element.
*
* @publicApi
* @globalApi ng
*/
export function getListeners(element: Element): Listener[] {
assertDomElement(element);
const lContext = loadLContext(element, false);
if (lContext === null) return [];
const lView = lContext.lView;
const tView = lView[TVIEW];
const lCleanup = lView[CLEANUP];
const tCleanup = tView.cleanup;
const listeners: Listener[] = [];
if (tCleanup && lCleanup) {
for (let i = 0; i < tCleanup.length;) {
const firstParam = tCleanup[i++];
const secondParam = tCleanup[i++];
if (typeof firstParam === 'string') {
const name: string = firstParam;
const listenerElement = unwrapRNode(lView[secondParam]) as any as Element;
const callback: (value: any) => any = lCleanup[tCleanup[i++]];
const useCaptureOrIndx = tCleanup[i++];
// if useCaptureOrIndx is boolean then report it as is.
// if useCaptureOrIndx is positive number then it in unsubscribe method
// if useCaptureOrIndx is negative number then it is a Subscription
const type =
(typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0) ? 'dom' : 'output';
const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
if (element == listenerElement) {
listeners.push({element, name, callback, useCapture, type});
}
}
}
}
listeners.sort(sortListeners);
return listeners;
}
function sortListeners(a: Listener, b: Listener) {
if (a.name == b.name) return 0;
return a.name < b.name ? -1 : 1;
}
/**
* This function should not exist because it is megamorphic and only mostly correct.
*
* See call site for more info.
*/
function isDirectiveDefHack(obj: any): obj is DirectiveDef<any> {
return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined;
}
/**
* Returns the attached `DebugNode` instance for an element in the DOM.
*
* @param element DOM element which is owned by an existing component's view.
*/
export function getDebugNode(element: Element): DebugNode|null {
let debugNode: DebugNode|null = null;
const lContext = loadLContextFromNode(element);
const lView = lContext.lView;
const nodeIndex = lContext.nodeIndex;
if (nodeIndex !== -1) {
const valueInLView = lView[nodeIndex];
// this means that value in the lView is a component with its own
// data. In this situation the TNode is not accessed at the same spot.
const tNode = isLView(valueInLView) ? (valueInLView[T_HOST] as TNode) :
getTNode(lView[TVIEW], nodeIndex - HEADER_OFFSET);
debugNode = buildDebugNode(tNode, lView, nodeIndex);
}
return debugNode;
}
/**
* Retrieve the component `LView` from component/element.
*
* NOTE: `LView` is a private and should not be leaked outside.
* Don't export this method to `ng.*` on window.
*
* @param target DOM element or component instance for which to retrieve the LView.
*/
export function getComponentLView(target: any): LView {
const lContext = loadLContext(target);
const nodeIndx = lContext.nodeIndex;
const lView = lContext.lView;
const componentLView = lView[nodeIndx];
ngDevMode && assertLView(componentLView);
return componentLView;
}
/** Asserts that a value is a DOM Element. */
function assertDomElement(value: any) {
if (typeof Element !== 'undefined' && !(value instanceof Element)) {
throw new Error('Expecting instance of DOM Element');
}
} | *
* @param elementOrDir DOM element, component or directive instance for which to
* retrieve the injector.
* @returns Injector associated with the element, component or directive instance.
* | random_line_split |
workbench.service.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Injectable, Injector} from '@angular/core';
import {CommonUtil} from '@common/util/common.util';
import {AbstractService} from '@common/service/abstract.service';
import {QueryEditor, Workbench} from '@domain/workbench/workbench';
import {Page} from '@domain/common/page';
@Injectable()
export class WorkbenchService extends AbstractService {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 워크벤치
public static workbench: Workbench;
// 워크벤치 아이디
public static workbenchId: string;
// 웹소켓 아이디
public static websocketId: string;
// 웹소켓 로그인 아이디
public static webSocketLoginId: string;
// 웹소켓 로그인 패스워드
public static webSocketLoginPw: string;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
constructor(protected injector: Injector) {
super(injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*****************************************
* 워크 벤치 관련
*****************************************/
// 워크벤치 생성
public createWorkbench(params: { name: string, dataConnection: string, workspace: string, type: 'workbench', folderId?: string, description?: string }): Promise<any> {
return this.post(this.API_URL + 'workbenchs', params);
}
/**
* 워크벤치 수정
* @param params
* id / name / description
* @returns {Promise<any>}
*/
public updateWorkbench(params: any): Promise<any> {
return this.patch(this.API_URL + 'workbenchs/' + params.id, params);
}
// 워크벤치 삭제
public deleteWorkbench(workbenchId: string): Promise<any> {
return this.delete(this.API_URL + 'workbenchs/' + workbenchId);
}
// 워크벤치 조회
public getWorkbench(id: string, projection: string = 'workbenchDetail'): Promise<Workbench> {
const url = this.API_URL + `workbenchs/${id}?projection=${projection}`;
return this.get(url);
}
// 생성자 기준으로 workbench 조회
public getCreateByWorkbench(createdBy: string) {
return this.get(this.API_URL + `workbenchs/search/findByCreatedBy?createdBy=${createdBy}`);
}
/*****************************************
* 쿼리 관련 - 생성 / 수정 / 삭제
*****************************************/
// 쿼리 생성.
public createQueryEditor(params: QueryEditor) {
return this.post(this.API_URL + 'queryeditors', params);
}
// 쿼리 수정
public updateQueryEditor(params: QueryEditor) {
return this.patch(this.API_URL + `queryeditors/${params.editorId}`, params);
}
// 쿼리 삭제
public deleteQueryEditor(deleteId: string) {
return this.delete(this.API_URL + `queryeditors/${deleteId}`);
}
// 쿼리 가져오기
public getQueryEditor(editorId: string) {
return this.get(this.API_URL + `queryeditors/${editorId}?projection=default`);
}
// 쿼리 히스토리 가져오기
public getQueryHistories(queryEditorId: string, queryPattern: string, projection: string = 'forListView', page: Page) {
// &sort=queryHistoryId,desc
let url = this.API_URL + `queryhistories/list?queryEditorId=${queryEditorId}&queryPattern=${queryPattern}&projection=${projection}`;
url += '&' + CommonUtil.objectToUrlString(page);
return this.get(url);
}
// 쿼리 삭제.
public deleteQueryHistory(queryId: string) {
// &sort=queryHistoryId,desc
return this.delete(this.API_URL + `queryhistories/${queryId}`);
}
// 에디터 쿼리 히스토리 삭제.
public deleteQueryHistoryAll(editorId: string) {
return this.delete(this.API_URL + `queryhistories/deleteAll?queryEditorId=${editorId}`);
}
// 쿼리 navigateion
public getQueryNavigation(workbenchId: string, page: Page) {
let url = this.API_URL + `workbenchs/${workbenchId}/navigation?projection=workbenchNavigation`;
url += '&' + CommonUtil.objectToUrlString(page);
return this.get(url);
}
/*****************************************
* 쿼리 관련 - 실행
*****************************************/
// 쿼리 실행
public runSingleQueryWithInvalidQuery(params: QueryEditor, additional: any) {
const id = params.editorId;
const param = {
query: params.query,
webSocketId: params.webSocketId,
runIndex: additional.runIndex
};
if (additional.retryQueryResultOrder) {
param['retryQueryResultOrder'] = additional.retryQueryResultOrder;
}
return this.post(this.API_URL + `queryeditors/${id}/query/run`, param); // params => query 값만 사용.
}
// 쿼리 실행 => websocket
public runSingleQueryWithInvalidQueryEditorId(params: QueryEditor) {
const id = params.editorId;
return this.post(this.API_URL + `queryeditors/${id}/query/run`, params); // params => query / webSocketId
}
public getCSVDownLoad(queryEditorId: string, params: any) {
return this.postBinary(this.API_URL + `queryeditors/${queryEditorId}/query/download`, params);
}
// 쿼리 취소
public setQueryRunCancel(queryEditorId: string, params: any) {
return this.post(this.API_URL + `queryeditors/${queryEditor | el`, params); // params => query / webSocketId
}
public checkConnectionStatus(queryEditorId: string, socketId: string) {
const param = {
webSocketId: socketId
};
return this.post(this.API_URL + `queryeditors/${queryEditorId}/status`, param);
}
// 쿼리 결과 조회 (페이징 사용)
public runQueryResult(editorId: string, csvFilePath: string, pageSize: number, pageNumber: number, fieldList: any) {
const id = editorId;
const param = {
csvFilePath: csvFilePath,
pageSize: pageSize,
pageNumber: pageNumber,
fieldList: fieldList
};
return this.post(this.API_URL + `queryeditors/${id}/query/result`, param);
}
// 스키마 정보 데이터 조회
public getSchemaInfoTableData(table: string, connection: any) {
const params: any = {};
const connInfo: any = {};
connInfo.implementor = connection.implementor;
connInfo.hostname = connection.hostname;
connInfo.port = connection.port;
// connection 정보가 USERINFO 일 경우 제외
if (connInfo.authenticationType !== 'USERINFO') {
connInfo.username = connection.username;
connInfo.password = connection.password;
}
// TODO #1573 추후 extensions 스펙에 맞게 변경 필요
connInfo.authenticationType = connection.authenticationType;
connInfo.database = connection.connectionDatabase;
connInfo.implementor = connection.implementor;
connInfo.name = connection.name;
connInfo.type = connection.type;
connInfo.catalog = connection.catalog;
connInfo.sid = connection.sid;
connInfo.table = table;
connInfo.url = connection.url;
// properties 속성이 존재 할경우
if (!CommonUtil.isNullOrUndefined(connection.properties)) {
connInfo.properties = connection.properties;
}
params.connection = connInfo;
params.database = connection.database;
params.type = 'TABLE';
params.query = table;
return this.post(this.API_URL + 'connections/query/data', params);
}
public importFile(workbenchId: string, params: any) {
return this.post(this.API_URL + `workbenchs/${workbenchId}/import`, params);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
}
| Id}/query/canc | identifier_name |
workbench.service.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Injectable, Injector} from '@angular/core';
import {CommonUtil} from '@common/util/common.util';
import {AbstractService} from '@common/service/abstract.service';
import {QueryEditor, Workbench} from '@domain/workbench/workbench';
import {Page} from '@domain/common/page';
@Injectable()
export class WorkbenchService extends AbstractService {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 워크벤치
public static workbench: Workbench;
// 워크벤치 아이디
public static workbenchId: string;
// 웹소켓 아이디
public static websocketId: string;
// 웹소켓 로그인 아이디
public static webSocketLoginId: string;
// 웹소켓 로그인 패스워드
public static webSocketLoginPw: string;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
constructor(protected injector: Injector) {
super(injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*****************************************
* 워크 벤치 관련
*****************************************/
// 워크벤치 생성
public createWorkbench(params: { name: string, dataConnection: string, workspace: string, type: 'workbench', folderId?: string, description?: string }): Promise<any> {
return this.post(this.API_URL + 'workbenchs', params);
}
/**
* 워크벤치 수정
* @param params
* id / name / description
* @returns {Promise<any>}
*/
public updateWorkbench(params: any): Promise<any> {
return this.patch(this.API_URL + 'workbenchs/' + params.id, params);
}
// 워크벤치 삭제
public deleteWorkbench(workbenchId: string): Promise<any> {
return this.delete(this.API_URL + 'workbenchs/' + workbenchId);
}
// 워크벤치 조회
public getWorkbench(id: string, projection: string = 'workbenchDetail'): Promise<Workbench> {
const url = this.API_URL + `workbenchs/${id}?projection=${projection}`;
return this.get(url);
}
// 생성자 기준으로 workbench 조회
public getCreateByWorkbench(createdBy: string) {
return this.get(this.API_URL + `workbenchs/search/findByCreatedBy?createdBy=${createdBy}`);
}
/*****************************************
* 쿼리 관련 - 생성 / 수정 / 삭제
*****************************************/
// 쿼리 생성.
public createQueryEditor(params: QueryEditor) {
return this.post(this.API_URL + 'queryeditors', params);
}
// 쿼리 수정
public updateQueryEditor(params: QueryEditor) {
return this.patch(this.API_URL + `queryeditors/${params.editorId}`, params);
}
// 쿼리 삭제
public deleteQueryEditor(deleteId: string) {
return this.delete(this.API_URL + `queryeditors/${deleteId}`);
}
// 쿼리 가져오기
public getQueryEditor(editorId: string) {
return this.get(this.API_URL + `queryeditors/${editorId}?projection=default`);
}
// 쿼리 히스토리 가져오기
public getQueryHistories(queryEditorId: string, queryPattern: string, projection: string = 'forListView', page: Page) {
// &sort=queryHistoryId,desc
let url = this.API_URL + `queryhistories/list?queryEditorId=${queryEditorId}&queryPattern=${queryPattern}&projection=${projection}`;
url += '&' + CommonUtil.objectToUrlString(page);
return this.get(url);
}
// 쿼리 삭제.
public deleteQueryHistory(queryId: string) {
// &sort=queryHistoryId,desc
return this.delete(this.API_URL + `queryhistories/${queryId}`);
}
// 에디터 쿼리 히스토리 삭제.
public deleteQueryHistoryAll(editorId: string) {
return this.delete(this.API_URL + `queryhistories/deleteAll?queryEditorId=${editorId}`);
}
// 쿼리 navigateion
public getQueryNavigation(workbenchId: string, page: Page) {
let url = this.API_URL + `workbenchs/${workbenchId}/navigation?projection=workbenchNavigation`;
url += '&' + CommonUtil.objectToUrlString(page);
return this.get(url);
}
/*****************************************
* 쿼리 관련 - 실행
*****************************************/
// 쿼리 실행
public runSingleQueryWithInvalidQuery(params: QueryEditor, additional: any) {
const id = params.editorId;
const param = {
query: params.query,
webSocketId: params.webSocketId,
runIndex: additional.runIndex
};
if (additional.retryQueryResultOrder) {
param['retryQueryResultOrder'] = additional.retryQueryResultOrder;
}
return this.post(this.API_URL + `queryeditors/${id}/query/run`, param); // params => query 값만 사용.
}
// 쿼리 실행 => websocket
public runSingleQueryWithInvalidQueryEditorId(params: QueryEditor) {
const id = params.editorId;
return this.post(this.API_URL + `queryeditors/${id}/query/run`, params); // params => query / webSocketId
}
public getCSVDownLoad(queryEditorId: string, params: any) {
return this.postBinary(this.API_URL + `queryeditors/${queryEditorId}/query/download`, params);
}
// 쿼리 취소
public setQueryRunCancel(queryEditorId: string, params: any) {
return this.post(this.API_URL + `queryeditors/${queryEditorId}/query/cancel`, params); // params => query / webSocketId
}
public checkConnectionStatus(queryEditorId: string, socketId: string) {
const param = {
webSocketId: socketId
};
return this.post(this.API_URL + `queryeditors/${queryEditorId}/status`, param);
}
// 쿼리 결과 조회 (페이징 사용)
public runQueryResult(editorId: string, csvFilePath: string, pageSize: number, pageNumber: number, fieldList: any) {
const id = editorId;
const param = {
csvFilePath: csvFilePath,
pageSize: pageSize,
pageNumber: pageNumber,
fieldList: fieldList
};
return this.post(this.API_URL + `queryeditors/${id}/query/result`, param);
}
// 스키마 정보 데이터 조회
public getSchemaInfoTableData(table: string, connection: any) {
const params: any = {};
const connInfo: any = {};
connInfo.implementor = connection.implementor;
connInfo.hostname = connection.hostname;
connInfo.port = connection.port;
// connection 정보가 USERINFO 일 경우 제외
if (connInfo.authenticationType !== 'USERINFO') {
connInfo.username = connection.username;
connInfo.password = connection.password;
}
// TODO #1573 추후 extensions 스펙에 맞게 변경 필요
connInfo.authenticationType = connection.authenticationType;
connInfo.database = connection.connectionDatabase;
connInfo.implementor = connection.implementor;
connInfo.name = connection.name;
con | n.sid;
connInfo.table = table;
connInfo.url = connection.url;
// properties 속성이 존재 할경우
if (!CommonUtil.isNullOrUndefined(connection.properties)) {
connInfo.properties = connection.properties;
}
params.connection = connInfo;
params.database = connection.database;
params.type = 'TABLE';
params.query = table;
return this.post(this.API_URL + 'connections/query/data', params);
}
public importFile(workbenchId: string, params: any) {
return this.post(this.API_URL + `workbenchs/${workbenchId}/import`, params);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
}
| nInfo.type = connection.type;
connInfo.catalog = connection.catalog;
connInfo.sid = connectio | conditional_block |
workbench.service.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Injectable, Injector} from '@angular/core';
import {CommonUtil} from '@common/util/common.util';
import {AbstractService} from '@common/service/abstract.service';
import {QueryEditor, Workbench} from '@domain/workbench/workbench';
import {Page} from '@domain/common/page';
@Injectable()
export class WorkbenchService extends AbstractService {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 워크벤치
public static workbench: Workbench;
// 워크벤치 아이디
public static workbenchId: string;
// 웹소켓 아이디
public static websocketId: string;
// 웹소켓 로그인 아이디
public static webSocketLoginId: string;
// 웹소켓 로그인 패스워드
public static webSocketLoginPw: string;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
constructor(protected injector: Injector) {
super(injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*****************************************
* 워크 벤치 관련
*****************************************/
// 워크벤치 생성
public createWorkbench(params: { name: string, dataConnection: string, workspace: string, type: 'workbench', folderId?: string, description?: string }): Promise<any> {
return this.post(this.API_URL + 'workbenchs', params);
}
/**
* 워크벤치 수정
* @param params
* id / name / description
* @returns {Promise<any>}
*/
public updateWorkbench(params: any): Promise<any> {
return this.patch(this.API_URL + 'workbenchs/' + params.id, params);
}
// 워크벤치 삭제
public deleteWorkbench(workbenchId: string): Promise<any> {
return this.delete(this.API_URL + 'workbenchs/' + workbenchId);
}
// 워크벤치 조회
public getWorkbench(id: string, projection: string = 'workbenchDetail'): Promise<Workbench> {
const url = this.API_URL + `workbenchs/${id}?projection=${projection}`;
return this.get(url);
}
// 생성자 기준으로 workbench 조회
public getCreateByWorkbench(createdBy: string) {
return this.get(this.API_URL + `workbenchs/search/findByCreatedBy?createdBy=${createdBy}`);
}
/*****************************************
* 쿼리 관련 - 생성 / 수정 / 삭제
*****************************************/
// 쿼리 생성.
public createQueryEditor(params: QueryEditor) {
return this.post(this.API_URL + 'queryeditors', params);
}
// 쿼리 수정
public updateQueryEditor(params: QueryEditor) {
return this.patch(this.API_URL + `queryeditors/${params.editorId}`, params);
}
// 쿼리 삭제
public deleteQueryEditor(deleteId: string) {
return this.delete(this.API_URL + `queryeditors/${deleteId}`);
}
// 쿼리 가져오기
public getQueryEditor(editorId: string) {
return this.get(this.API_URL + `queryeditors/${editorId}?projection=default`);
}
// 쿼리 히스토리 가져오기
public getQueryHistories(queryEditorId: string, queryPattern: string, projection: string = 'forListView', page: Page) {
// &sort=queryHistoryId,desc
let url = this.API_URL + `queryhistories/list?queryEditorId=${queryEditorId}&queryPattern=${queryPattern}&projection=${projection}`;
url += '&' + CommonUtil.objectToUrlString(page);
return this.get(url);
}
// 쿼리 삭제.
public deleteQueryHistory(queryId: string) {
// &sort=queryHistoryId,desc
return this.delete(this.API_URL + `queryhistories/${queryId}`);
}
// 에디터 쿼리 히스토리 삭제.
public deleteQueryHistoryAll(editorId: string) {
return this.delete(this.API_URL + `queryhistories/deleteAll?queryEditorId=${editorId}`);
}
// 쿼리 navigateion
public getQueryNavigation(workbenchId: string, page: Page) {
let url = this.API_URL + `workbenchs/${workbenchId}/navigation?projection=workbenchNavigation`;
url += '&' + CommonUtil.objectToUrlString(page);
return this.get(url);
}
/*****************************************
* 쿼리 관련 - 실행
*****************************************/
// 쿼리 실행
public runSingleQueryWithInvalidQuery(params: QueryEditor, additional: any) {
const id = params.editorId;
const param = {
query: params.query,
webSocketId: params.webSocketId,
runIndex: additional.runIndex
};
if (additional.retryQueryResultOrder) {
param['retryQueryResultOrder'] = additional.retryQueryResultOrder; | g, params: any) {
return this.postBinary(this.API_URL + `queryeditors/${queryEditorId}/query/download`, params);
}
// 쿼리 취소
public setQueryRunCancel(queryEditorId: string, params: any) {
return this.post(this.API_URL + `queryeditors/${queryEditorId}/query/cancel`, params); // params => query / webSocketId
}
public checkConnectionStatus(queryEditorId: string, socketId: string) {
const param = {
webSocketId: socketId
};
return this.post(this.API_URL + `queryeditors/${queryEditorId}/status`, param);
}
// 쿼리 결과 조회 (페이징 사용)
public runQueryResult(editorId: string, csvFilePath: string, pageSize: number, pageNumber: number, fieldList: any) {
const id = editorId;
const param = {
csvFilePath: csvFilePath,
pageSize: pageSize,
pageNumber: pageNumber,
fieldList: fieldList
};
return this.post(this.API_URL + `queryeditors/${id}/query/result`, param);
}
// 스키마 정보 데이터 조회
public getSchemaInfoTableData(table: string, connection: any) {
const params: any = {};
const connInfo: any = {};
connInfo.implementor = connection.implementor;
connInfo.hostname = connection.hostname;
connInfo.port = connection.port;
// connection 정보가 USERINFO 일 경우 제외
if (connInfo.authenticationType !== 'USERINFO') {
connInfo.username = connection.username;
connInfo.password = connection.password;
}
// TODO #1573 추후 extensions 스펙에 맞게 변경 필요
connInfo.authenticationType = connection.authenticationType;
connInfo.database = connection.connectionDatabase;
connInfo.implementor = connection.implementor;
connInfo.name = connection.name;
connInfo.type = connection.type;
connInfo.catalog = connection.catalog;
connInfo.sid = connection.sid;
connInfo.table = table;
connInfo.url = connection.url;
// properties 속성이 존재 할경우
if (!CommonUtil.isNullOrUndefined(connection.properties)) {
connInfo.properties = connection.properties;
}
params.connection = connInfo;
params.database = connection.database;
params.type = 'TABLE';
params.query = table;
return this.post(this.API_URL + 'connections/query/data', params);
}
public importFile(workbenchId: string, params: any) {
return this.post(this.API_URL + `workbenchs/${workbenchId}/import`, params);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
}
|
}
return this.post(this.API_URL + `queryeditors/${id}/query/run`, param); // params => query 값만 사용.
}
// 쿼리 실행 => websocket
public runSingleQueryWithInvalidQueryEditorId(params: QueryEditor) {
const id = params.editorId;
return this.post(this.API_URL + `queryeditors/${id}/query/run`, params); // params => query / webSocketId
}
public getCSVDownLoad(queryEditorId: strin | identifier_body |
workbench.service.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and | import {CommonUtil} from '@common/util/common.util';
import {AbstractService} from '@common/service/abstract.service';
import {QueryEditor, Workbench} from '@domain/workbench/workbench';
import {Page} from '@domain/common/page';
@Injectable()
export class WorkbenchService extends AbstractService {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 워크벤치
public static workbench: Workbench;
// 워크벤치 아이디
public static workbenchId: string;
// 웹소켓 아이디
public static websocketId: string;
// 웹소켓 로그인 아이디
public static webSocketLoginId: string;
// 웹소켓 로그인 패스워드
public static webSocketLoginPw: string;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
constructor(protected injector: Injector) {
super(injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*****************************************
* 워크 벤치 관련
*****************************************/
// 워크벤치 생성
public createWorkbench(params: { name: string, dataConnection: string, workspace: string, type: 'workbench', folderId?: string, description?: string }): Promise<any> {
return this.post(this.API_URL + 'workbenchs', params);
}
/**
* 워크벤치 수정
* @param params
* id / name / description
* @returns {Promise<any>}
*/
public updateWorkbench(params: any): Promise<any> {
return this.patch(this.API_URL + 'workbenchs/' + params.id, params);
}
// 워크벤치 삭제
public deleteWorkbench(workbenchId: string): Promise<any> {
return this.delete(this.API_URL + 'workbenchs/' + workbenchId);
}
// 워크벤치 조회
public getWorkbench(id: string, projection: string = 'workbenchDetail'): Promise<Workbench> {
const url = this.API_URL + `workbenchs/${id}?projection=${projection}`;
return this.get(url);
}
// 생성자 기준으로 workbench 조회
public getCreateByWorkbench(createdBy: string) {
return this.get(this.API_URL + `workbenchs/search/findByCreatedBy?createdBy=${createdBy}`);
}
/*****************************************
* 쿼리 관련 - 생성 / 수정 / 삭제
*****************************************/
// 쿼리 생성.
public createQueryEditor(params: QueryEditor) {
return this.post(this.API_URL + 'queryeditors', params);
}
// 쿼리 수정
public updateQueryEditor(params: QueryEditor) {
return this.patch(this.API_URL + `queryeditors/${params.editorId}`, params);
}
// 쿼리 삭제
public deleteQueryEditor(deleteId: string) {
return this.delete(this.API_URL + `queryeditors/${deleteId}`);
}
// 쿼리 가져오기
public getQueryEditor(editorId: string) {
return this.get(this.API_URL + `queryeditors/${editorId}?projection=default`);
}
// 쿼리 히스토리 가져오기
public getQueryHistories(queryEditorId: string, queryPattern: string, projection: string = 'forListView', page: Page) {
// &sort=queryHistoryId,desc
let url = this.API_URL + `queryhistories/list?queryEditorId=${queryEditorId}&queryPattern=${queryPattern}&projection=${projection}`;
url += '&' + CommonUtil.objectToUrlString(page);
return this.get(url);
}
// 쿼리 삭제.
public deleteQueryHistory(queryId: string) {
// &sort=queryHistoryId,desc
return this.delete(this.API_URL + `queryhistories/${queryId}`);
}
// 에디터 쿼리 히스토리 삭제.
public deleteQueryHistoryAll(editorId: string) {
return this.delete(this.API_URL + `queryhistories/deleteAll?queryEditorId=${editorId}`);
}
// 쿼리 navigateion
public getQueryNavigation(workbenchId: string, page: Page) {
let url = this.API_URL + `workbenchs/${workbenchId}/navigation?projection=workbenchNavigation`;
url += '&' + CommonUtil.objectToUrlString(page);
return this.get(url);
}
/*****************************************
* 쿼리 관련 - 실행
*****************************************/
// 쿼리 실행
public runSingleQueryWithInvalidQuery(params: QueryEditor, additional: any) {
const id = params.editorId;
const param = {
query: params.query,
webSocketId: params.webSocketId,
runIndex: additional.runIndex
};
if (additional.retryQueryResultOrder) {
param['retryQueryResultOrder'] = additional.retryQueryResultOrder;
}
return this.post(this.API_URL + `queryeditors/${id}/query/run`, param); // params => query 값만 사용.
}
// 쿼리 실행 => websocket
public runSingleQueryWithInvalidQueryEditorId(params: QueryEditor) {
const id = params.editorId;
return this.post(this.API_URL + `queryeditors/${id}/query/run`, params); // params => query / webSocketId
}
public getCSVDownLoad(queryEditorId: string, params: any) {
return this.postBinary(this.API_URL + `queryeditors/${queryEditorId}/query/download`, params);
}
// 쿼리 취소
public setQueryRunCancel(queryEditorId: string, params: any) {
return this.post(this.API_URL + `queryeditors/${queryEditorId}/query/cancel`, params); // params => query / webSocketId
}
public checkConnectionStatus(queryEditorId: string, socketId: string) {
const param = {
webSocketId: socketId
};
return this.post(this.API_URL + `queryeditors/${queryEditorId}/status`, param);
}
// 쿼리 결과 조회 (페이징 사용)
public runQueryResult(editorId: string, csvFilePath: string, pageSize: number, pageNumber: number, fieldList: any) {
const id = editorId;
const param = {
csvFilePath: csvFilePath,
pageSize: pageSize,
pageNumber: pageNumber,
fieldList: fieldList
};
return this.post(this.API_URL + `queryeditors/${id}/query/result`, param);
}
// 스키마 정보 데이터 조회
public getSchemaInfoTableData(table: string, connection: any) {
const params: any = {};
const connInfo: any = {};
connInfo.implementor = connection.implementor;
connInfo.hostname = connection.hostname;
connInfo.port = connection.port;
// connection 정보가 USERINFO 일 경우 제외
if (connInfo.authenticationType !== 'USERINFO') {
connInfo.username = connection.username;
connInfo.password = connection.password;
}
// TODO #1573 추후 extensions 스펙에 맞게 변경 필요
connInfo.authenticationType = connection.authenticationType;
connInfo.database = connection.connectionDatabase;
connInfo.implementor = connection.implementor;
connInfo.name = connection.name;
connInfo.type = connection.type;
connInfo.catalog = connection.catalog;
connInfo.sid = connection.sid;
connInfo.table = table;
connInfo.url = connection.url;
// properties 속성이 존재 할경우
if (!CommonUtil.isNullOrUndefined(connection.properties)) {
connInfo.properties = connection.properties;
}
params.connection = connInfo;
params.database = connection.database;
params.type = 'TABLE';
params.query = table;
return this.post(this.API_URL + 'connections/query/data', params);
}
public importFile(workbenchId: string, params: any) {
return this.post(this.API_URL + `workbenchs/${workbenchId}/import`, params);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
} | * limitations under the License.
*/
import {Injectable, Injector} from '@angular/core'; | random_line_split |
cpqScsiPhyDrv.py | ################################################################################
#
# This program is part of the HPMon Zenpack for Zenoss.
# Copyright (C) 2008, 2009, 2010, 2011 Egor Puzanov.
#
# This program can be used under the GNU General Public License version 2
# You can find full information here: http://www.zenoss.com/oss
#
################################################################################
__doc__="""cpqScsiPhyDrv
cpqScsiPhyDrv is an abstraction of a HP SCSI Hard Disk.
| $Id: cpqScsiPhyDrv.py,v 1.2 2011/01/04 23:27:26 egor Exp $"""
__version__ = "$Revision: 1.2 $"[11:-2]
from HPHardDisk import HPHardDisk
from HPComponent import *
class cpqScsiPhyDrv(HPHardDisk):
"""cpqScsiPhyDrv object
"""
statusmap ={1: (DOT_GREY, SEV_WARNING, 'other'),
2: (DOT_GREEN, SEV_CLEAN, 'Ok'),
3: (DOT_RED, SEV_CRITICAL, 'Failed'),
4: (DOT_YELLOW, SEV_WARNING, 'Not Configured'),
5: (DOT_ORANGE, SEV_ERROR, 'Bad Cable'),
6: (DOT_RED, SEV_CRITICAL, 'Missing was Ok'),
7: (DOT_RED, SEV_CRITICAL, 'Missing was Failed'),
8: (DOT_ORANGE, SEV_ERROR, 'Predictive Failure'),
9: (DOT_RED, SEV_CRITICAL, 'Missing was Predictive Failure'),
10:(DOT_RED, SEV_CRITICAL, 'Offline'),
11:(DOT_RED, SEV_CRITICAL, 'Missing was Offline'),
12:(DOT_RED, SEV_CRITICAL, 'Hard Error'),
}
InitializeClass(cpqScsiPhyDrv) | random_line_split | |
cpqScsiPhyDrv.py | ################################################################################
#
# This program is part of the HPMon Zenpack for Zenoss.
# Copyright (C) 2008, 2009, 2010, 2011 Egor Puzanov.
#
# This program can be used under the GNU General Public License version 2
# You can find full information here: http://www.zenoss.com/oss
#
################################################################################
__doc__="""cpqScsiPhyDrv
cpqScsiPhyDrv is an abstraction of a HP SCSI Hard Disk.
$Id: cpqScsiPhyDrv.py,v 1.2 2011/01/04 23:27:26 egor Exp $"""
__version__ = "$Revision: 1.2 $"[11:-2]
from HPHardDisk import HPHardDisk
from HPComponent import *
class cpqScsiPhyDrv(HPHardDisk):
|
InitializeClass(cpqScsiPhyDrv)
| """cpqScsiPhyDrv object
"""
statusmap ={1: (DOT_GREY, SEV_WARNING, 'other'),
2: (DOT_GREEN, SEV_CLEAN, 'Ok'),
3: (DOT_RED, SEV_CRITICAL, 'Failed'),
4: (DOT_YELLOW, SEV_WARNING, 'Not Configured'),
5: (DOT_ORANGE, SEV_ERROR, 'Bad Cable'),
6: (DOT_RED, SEV_CRITICAL, 'Missing was Ok'),
7: (DOT_RED, SEV_CRITICAL, 'Missing was Failed'),
8: (DOT_ORANGE, SEV_ERROR, 'Predictive Failure'),
9: (DOT_RED, SEV_CRITICAL, 'Missing was Predictive Failure'),
10:(DOT_RED, SEV_CRITICAL, 'Offline'),
11:(DOT_RED, SEV_CRITICAL, 'Missing was Offline'),
12:(DOT_RED, SEV_CRITICAL, 'Hard Error'),
} | identifier_body |
cpqScsiPhyDrv.py | ################################################################################
#
# This program is part of the HPMon Zenpack for Zenoss.
# Copyright (C) 2008, 2009, 2010, 2011 Egor Puzanov.
#
# This program can be used under the GNU General Public License version 2
# You can find full information here: http://www.zenoss.com/oss
#
################################################################################
__doc__="""cpqScsiPhyDrv
cpqScsiPhyDrv is an abstraction of a HP SCSI Hard Disk.
$Id: cpqScsiPhyDrv.py,v 1.2 2011/01/04 23:27:26 egor Exp $"""
__version__ = "$Revision: 1.2 $"[11:-2]
from HPHardDisk import HPHardDisk
from HPComponent import *
class | (HPHardDisk):
"""cpqScsiPhyDrv object
"""
statusmap ={1: (DOT_GREY, SEV_WARNING, 'other'),
2: (DOT_GREEN, SEV_CLEAN, 'Ok'),
3: (DOT_RED, SEV_CRITICAL, 'Failed'),
4: (DOT_YELLOW, SEV_WARNING, 'Not Configured'),
5: (DOT_ORANGE, SEV_ERROR, 'Bad Cable'),
6: (DOT_RED, SEV_CRITICAL, 'Missing was Ok'),
7: (DOT_RED, SEV_CRITICAL, 'Missing was Failed'),
8: (DOT_ORANGE, SEV_ERROR, 'Predictive Failure'),
9: (DOT_RED, SEV_CRITICAL, 'Missing was Predictive Failure'),
10:(DOT_RED, SEV_CRITICAL, 'Offline'),
11:(DOT_RED, SEV_CRITICAL, 'Missing was Offline'),
12:(DOT_RED, SEV_CRITICAL, 'Hard Error'),
}
InitializeClass(cpqScsiPhyDrv)
| cpqScsiPhyDrv | identifier_name |
build.py | import os
from os.path import join, getctime, dirname
import glob
import subprocess
import argparse
def newest_file(root):
path = join(root, "*tar.bz2")
newest = max(glob.iglob(path), key=getctime)
return newest
def upload(pkg, user):
cmd = ["binstar", "upload", "--force","-u", user, pkg]
subprocess.check_call(cmd)
def build(recipe, build_path, pythons=[], platforms=[], binstar_user=None):
|
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("build_dir")
p.add_argument("--py", action="append", default=[])
p.add_argument("--plat", action="append", default=[])
p.add_argument("-u", "--binstar-user", help="binstar user")
args = p.parse_args()
build_dir = p.add_argument("build_dir")
build("conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
#build("../into/conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
"""
python build.py /opt/anaconda/conda-bld/linux-64 --py 27 --py 34 --plat osx-64 --plat win-64 -u hugo
"""
| print (recipe, pythons, platforms)
for p in pythons:
cmd = ["conda", "build", recipe, "--python", p]
subprocess.check_call(cmd)
pkg = newest_file(build_path)
if binstar_user:
upload(pkg, binstar_user)
for plat in platforms:
cmd = ["conda", "convert", "-p", plat, pkg]
subprocess.check_call(cmd)
if binstar_user:
to_upload = newest_file(plat)
upload(to_upload, binstar_user) | identifier_body |
build.py | import os
from os.path import join, getctime, dirname
import glob
import subprocess
import argparse
def newest_file(root):
path = join(root, "*tar.bz2")
newest = max(glob.iglob(path), key=getctime)
return newest
def upload(pkg, user):
cmd = ["binstar", "upload", "--force","-u", user, pkg]
subprocess.check_call(cmd)
def | (recipe, build_path, pythons=[], platforms=[], binstar_user=None):
print (recipe, pythons, platforms)
for p in pythons:
cmd = ["conda", "build", recipe, "--python", p]
subprocess.check_call(cmd)
pkg = newest_file(build_path)
if binstar_user:
upload(pkg, binstar_user)
for plat in platforms:
cmd = ["conda", "convert", "-p", plat, pkg]
subprocess.check_call(cmd)
if binstar_user:
to_upload = newest_file(plat)
upload(to_upload, binstar_user)
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("build_dir")
p.add_argument("--py", action="append", default=[])
p.add_argument("--plat", action="append", default=[])
p.add_argument("-u", "--binstar-user", help="binstar user")
args = p.parse_args()
build_dir = p.add_argument("build_dir")
build("conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
#build("../into/conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
"""
python build.py /opt/anaconda/conda-bld/linux-64 --py 27 --py 34 --plat osx-64 --plat win-64 -u hugo
"""
| build | identifier_name |
build.py | import os
from os.path import join, getctime, dirname
import glob
import subprocess
import argparse
def newest_file(root):
path = join(root, "*tar.bz2")
newest = max(glob.iglob(path), key=getctime)
return newest
def upload(pkg, user):
cmd = ["binstar", "upload", "--force","-u", user, pkg]
subprocess.check_call(cmd)
def build(recipe, build_path, pythons=[], platforms=[], binstar_user=None):
print (recipe, pythons, platforms)
for p in pythons:
cmd = ["conda", "build", recipe, "--python", p]
subprocess.check_call(cmd)
pkg = newest_file(build_path)
if binstar_user:
upload(pkg, binstar_user)
for plat in platforms:
|
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("build_dir")
p.add_argument("--py", action="append", default=[])
p.add_argument("--plat", action="append", default=[])
p.add_argument("-u", "--binstar-user", help="binstar user")
args = p.parse_args()
build_dir = p.add_argument("build_dir")
build("conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
#build("../into/conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
"""
python build.py /opt/anaconda/conda-bld/linux-64 --py 27 --py 34 --plat osx-64 --plat win-64 -u hugo
"""
| cmd = ["conda", "convert", "-p", plat, pkg]
subprocess.check_call(cmd)
if binstar_user:
to_upload = newest_file(plat)
upload(to_upload, binstar_user) | conditional_block |
build.py | import os
from os.path import join, getctime, dirname
import glob
import subprocess
import argparse
def newest_file(root):
path = join(root, "*tar.bz2")
newest = max(glob.iglob(path), key=getctime)
return newest
def upload(pkg, user):
cmd = ["binstar", "upload", "--force","-u", user, pkg]
subprocess.check_call(cmd)
def build(recipe, build_path, pythons=[], platforms=[], binstar_user=None):
print (recipe, pythons, platforms)
for p in pythons:
cmd = ["conda", "build", recipe, "--python", p]
subprocess.check_call(cmd)
pkg = newest_file(build_path)
if binstar_user:
upload(pkg, binstar_user)
for plat in platforms:
cmd = ["conda", "convert", "-p", plat, pkg]
subprocess.check_call(cmd)
if binstar_user:
to_upload = newest_file(plat)
upload(to_upload, binstar_user)
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("build_dir")
p.add_argument("--py", action="append", default=[])
p.add_argument("--plat", action="append", default=[])
p.add_argument("-u", "--binstar-user", help="binstar user")
args = p.parse_args()
build_dir = p.add_argument("build_dir")
build("conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user)
#build("../into/conda.recipe", args.build_dir, args.py, args.plat, args.binstar_user) | """
python build.py /opt/anaconda/conda-bld/linux-64 --py 27 --py 34 --plat osx-64 --plat win-64 -u hugo
""" | random_line_split | |
gen_lines.rs | // Copyright (c) Carl-Erwin Griffith
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
use std::env;
use std::io::BufWriter;
use std::io::{self, Write};
fn main() {
let os_args = env::args();
let args: Vec<_> = os_args.collect();
if args.len() != 4 {
println!("usage : {} start numline width", args[0]);
return;
}
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0);
let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0);
let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0);
gen_lines(start_num, stop_num, width_num);
}
fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () {
let string = gen_line(linewidth);
let stdout = io::stdout();
let mut buff = BufWriter::new(stdout);
for x in start..start + stop + 1 { | let mut string = String::new();
let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'];
for x in 0..linewidth {
string.push(table[x as usize % table.len()]);
}
string.push('\n');
string
} | buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap();
}
}
fn gen_line(linewidth: u64) -> String { | random_line_split |
gen_lines.rs | // Copyright (c) Carl-Erwin Griffith
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
use std::env;
use std::io::BufWriter;
use std::io::{self, Write};
fn main() {
let os_args = env::args();
let args: Vec<_> = os_args.collect();
if args.len() != 4 |
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0);
let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0);
let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0);
gen_lines(start_num, stop_num, width_num);
}
fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () {
let string = gen_line(linewidth);
let stdout = io::stdout();
let mut buff = BufWriter::new(stdout);
for x in start..start + stop + 1 {
buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap();
}
}
fn gen_line(linewidth: u64) -> String {
let mut string = String::new();
let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'];
for x in 0..linewidth {
string.push(table[x as usize % table.len()]);
}
string.push('\n');
string
}
| {
println!("usage : {} start numline width", args[0]);
return;
} | conditional_block |
gen_lines.rs | // Copyright (c) Carl-Erwin Griffith
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
use std::env;
use std::io::BufWriter;
use std::io::{self, Write};
fn main() {
let os_args = env::args();
let args: Vec<_> = os_args.collect();
if args.len() != 4 {
println!("usage : {} start numline width", args[0]);
return;
}
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0);
let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0);
let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0);
gen_lines(start_num, stop_num, width_num);
}
fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () |
fn gen_line(linewidth: u64) -> String {
let mut string = String::new();
let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'];
for x in 0..linewidth {
string.push(table[x as usize % table.len()]);
}
string.push('\n');
string
}
| {
let string = gen_line(linewidth);
let stdout = io::stdout();
let mut buff = BufWriter::new(stdout);
for x in start..start + stop + 1 {
buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap();
}
} | identifier_body |
gen_lines.rs | // Copyright (c) Carl-Erwin Griffith
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
use std::env;
use std::io::BufWriter;
use std::io::{self, Write};
fn main() {
let os_args = env::args();
let args: Vec<_> = os_args.collect();
if args.len() != 4 {
println!("usage : {} start numline width", args[0]);
return;
}
let start_num = args[1].trim_end().parse::<u64>().unwrap_or(0);
let stop_num = args[2].trim_end().parse::<u64>().unwrap_or(0);
let width_num = args[3].trim_end().parse::<u64>().unwrap_or(0);
gen_lines(start_num, stop_num, width_num);
}
fn gen_lines(start: u64, stop: u64, linewidth: u64) -> () {
let string = gen_line(linewidth);
let stdout = io::stdout();
let mut buff = BufWriter::new(stdout);
for x in start..start + stop + 1 {
buff.write_fmt(format_args!("{:012} {}", x, string)).unwrap();
}
}
fn | (linewidth: u64) -> String {
let mut string = String::new();
let table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'];
for x in 0..linewidth {
string.push(table[x as usize % table.len()]);
}
string.push('\n');
string
}
| gen_line | identifier_name |
message.rs | use std::net::SocketAddr;
use std::sync::mpsc::Sender;
#[derive(Debug, Clone)]
pub struct Member {
pub name: String,
pub addr: SocketAddr
}
pub struct Request {
pub addr: SocketAddr,
pub body: RequestBody
}
pub enum RequestBody {
Join { tx: Sender<Notify> },
Leave,
List,
Rename { name: String },
Submit { message: String },
UnicastMessage { message: String }
}
#[derive(Debug, Clone)]
pub enum Notify {
Unicast(UnicastNotify),
Broadcast(BroadcastNotify)
}
#[derive(Debug, Clone)]
pub enum | {
Join { name: String },
Leave,
List(Vec<(Member)>),
Rename(bool),
Submit(bool),
Message(String)
}
#[derive(Debug, Clone)]
pub enum BroadcastNotify {
Join { name: String, addr: SocketAddr },
Leave { name: String, addr: SocketAddr },
Rename { old_name: String, new_name: String, addr: SocketAddr },
Submit { name: String, addr: SocketAddr, message: String },
}
| UnicastNotify | identifier_name |
message.rs | use std::net::SocketAddr;
use std::sync::mpsc::Sender;
#[derive(Debug, Clone)]
pub struct Member {
pub name: String,
pub addr: SocketAddr
}
pub struct Request {
pub addr: SocketAddr,
pub body: RequestBody
}
pub enum RequestBody {
Join { tx: Sender<Notify> },
Leave,
List,
Rename { name: String },
Submit { message: String },
UnicastMessage { message: String }
}
#[derive(Debug, Clone)]
pub enum Notify {
Unicast(UnicastNotify),
Broadcast(BroadcastNotify)
}
#[derive(Debug, Clone)]
pub enum UnicastNotify {
Join { name: String },
Leave,
List(Vec<(Member)>),
Rename(bool),
Submit(bool),
Message(String)
}
| pub enum BroadcastNotify {
Join { name: String, addr: SocketAddr },
Leave { name: String, addr: SocketAddr },
Rename { old_name: String, new_name: String, addr: SocketAddr },
Submit { name: String, addr: SocketAddr, message: String },
} | #[derive(Debug, Clone)] | random_line_split |
views.py | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Profile
from .forms import ProfileForm
@login_required
def | (request):
next = request.GET.get("next")
profile, created = Profile.objects.get_or_create(
user=request.user,
defaults={
"first_name": request.user.first_name,
"last_name": request.user.last_name,
}
)
if request.method == "POST":
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
profile = form.save()
request.user.first_name = form.cleaned_data["first_name"]
request.user.last_name = form.cleaned_data["last_name"]
messages.add_message(request, messages.SUCCESS,
"Successfully updated profile."
)
if next:
return redirect(next)
else:
form = ProfileForm(instance=profile)
return render(request, "profiles/edit.html", {
"form": form,
"next": next,
})
| profile_edit | identifier_name |
views.py | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Profile
from .forms import ProfileForm
@login_required
def profile_edit(request):
| next = request.GET.get("next")
profile, created = Profile.objects.get_or_create(
user=request.user,
defaults={
"first_name": request.user.first_name,
"last_name": request.user.last_name,
}
)
if request.method == "POST":
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
profile = form.save()
request.user.first_name = form.cleaned_data["first_name"]
request.user.last_name = form.cleaned_data["last_name"]
messages.add_message(request, messages.SUCCESS,
"Successfully updated profile."
)
if next:
return redirect(next)
else:
form = ProfileForm(instance=profile)
return render(request, "profiles/edit.html", {
"form": form,
"next": next,
}) | identifier_body | |
views.py | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Profile
from .forms import ProfileForm
@login_required
def profile_edit(request):
next = request.GET.get("next")
profile, created = Profile.objects.get_or_create(
user=request.user,
defaults={
"first_name": request.user.first_name,
"last_name": request.user.last_name,
}
)
if request.method == "POST":
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
|
else:
form = ProfileForm(instance=profile)
return render(request, "profiles/edit.html", {
"form": form,
"next": next,
})
| profile = form.save()
request.user.first_name = form.cleaned_data["first_name"]
request.user.last_name = form.cleaned_data["last_name"]
messages.add_message(request, messages.SUCCESS,
"Successfully updated profile."
)
if next:
return redirect(next) | conditional_block |
views.py | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Profile
from .forms import ProfileForm
@login_required
def profile_edit(request):
next = request.GET.get("next")
profile, created = Profile.objects.get_or_create(
user=request.user,
defaults={
"first_name": request.user.first_name,
"last_name": request.user.last_name,
}
)
if request.method == "POST": | profile = form.save()
request.user.first_name = form.cleaned_data["first_name"]
request.user.last_name = form.cleaned_data["last_name"]
messages.add_message(request, messages.SUCCESS,
"Successfully updated profile."
)
if next:
return redirect(next)
else:
form = ProfileForm(instance=profile)
return render(request, "profiles/edit.html", {
"form": form,
"next": next,
}) | form = ProfileForm(request.POST, instance=profile)
if form.is_valid(): | random_line_split |
__init__.py | # Copyright 2013-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable=W0613,no-member,attribute-defined-outside-init
"""
Some "standard" instruments to collect additional info about workload execution.
.. note:: The run() method of a Workload may perform some "boilerplate" as well as
the actual execution of the workload (e.g. it may contain UI automation
needed to start the workload). This "boilerplate" execution will also
be measured by these instruments. As such, they are not suitable for collected
precise data about specific operations.
"""
import os
import re
import logging
import time
import tarfile
from itertools import izip, izip_longest
from subprocess import CalledProcessError
from wlauto import Instrument, Parameter
from wlauto.core import signal
from wlauto.exceptions import DeviceError, ConfigError
from wlauto.utils.misc import diff_tokens, write_table, check_output, as_relative
from wlauto.utils.misc import ensure_file_directory_exists as _f
from wlauto.utils.misc import ensure_directory_exists as _d
from wlauto.utils.android import ApkInfo
from wlauto.utils.types import list_of_strings
logger = logging.getLogger(__name__)
class SysfsExtractor(Instrument):
name = 'sysfs_extractor'
description = """
Collects the contest of a set of directories, before and after workload execution
and diffs the result.
"""
mount_command = 'mount -t tmpfs -o size={} tmpfs {}'
extract_timeout = 30
tarname = 'sysfs.tar'
DEVICE_PATH = 0
BEFORE_PATH = 1
AFTER_PATH = 2
DIFF_PATH = 3
parameters = [
Parameter('paths', kind=list_of_strings, mandatory=True,
description="""A list of paths to be pulled from the device. These could be directories
as well as files.""",
global_alias='sysfs_extract_dirs'),
Parameter('use_tmpfs', kind=bool, default=None,
description="""
Specifies whether tmpfs should be used to cache sysfile trees and then pull them down
as a tarball. This is significantly faster then just copying the directory trees from
the device directly, bur requres root and may not work on all devices. Defaults to
``True`` if the device is rooted and ``False`` if it is not.
"""),
Parameter('tmpfs_mount_point', default=None,
description="""Mount point for tmpfs partition used to store snapshots of paths."""),
Parameter('tmpfs_size', default='32m',
description="""Size of the tempfs partition."""),
]
def initialize(self, context):
if not self.device.is_rooted and self.use_tmpfs: # pylint: disable=access-member-before-definition
raise ConfigError('use_tempfs must be False for an unrooted device.')
elif self.use_tmpfs is None: # pylint: disable=access-member-before-definition
self.use_tmpfs = self.device.is_rooted
if self.use_tmpfs:
self.on_device_before = self.device.path.join(self.tmpfs_mount_point, 'before')
self.on_device_after = self.device.path.join(self.tmpfs_mount_point, 'after')
if not self.device.file_exists(self.tmpfs_mount_point):
self.device.execute('mkdir -p {}'.format(self.tmpfs_mount_point), as_root=True)
self.device.execute(self.mount_command.format(self.tmpfs_size, self.tmpfs_mount_point),
as_root=True)
def setup(self, context):
before_dirs = [
_d(os.path.join(context.output_directory, 'before', self._local_dir(d)))
for d in self.paths
]
after_dirs = [
_d(os.path.join(context.output_directory, 'after', self._local_dir(d)))
for d in self.paths
]
diff_dirs = [
_d(os.path.join(context.output_directory, 'diff', self._local_dir(d)))
for d in self.paths
]
self.device_and_host_paths = zip(self.paths, before_dirs, after_dirs, diff_dirs)
if self.use_tmpfs:
for d in self.paths:
before_dir = self.device.path.join(self.on_device_before,
self.device.path.dirname(as_relative(d)))
after_dir = self.device.path.join(self.on_device_after,
self.device.path.dirname(as_relative(d)))
if self.device.file_exists(before_dir):
self.device.execute('rm -rf {}'.format(before_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(before_dir), as_root=True)
if self.device.file_exists(after_dir):
self.device.execute('rm -rf {}'.format(after_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(after_dir), as_root=True)
def slow_start(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_before, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not rooted
for dev_dir, before_dir, _, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, before_dir)
def slow_stop(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_after, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not using tmpfs
for dev_dir, _, after_dir, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, after_dir)
def update_result(self, context):
if self.use_tmpfs:
on_device_tarball = self.device.path.join(self.device.working_directory, self.tarname)
on_host_tarball = self.device.path.join(context.output_directory, self.tarname + ".gz")
self.device.execute('{} tar cf {} -C {} .'.format(self.device.busybox,
on_device_tarball,
self.tmpfs_mount_point),
as_root=True)
self.device.execute('chmod 0777 {}'.format(on_device_tarball), as_root=True)
self.device.execute('{} gzip {}'.format(self.device.busybox,
on_device_tarball))
self.device.pull_file(on_device_tarball + ".gz", on_host_tarball)
with tarfile.open(on_host_tarball, 'r:gz') as tf:
tf.extractall(context.output_directory)
self.device.delete_file(on_device_tarball + ".gz")
os.remove(on_host_tarball)
for paths in self.device_and_host_paths:
after_dir = paths[self.AFTER_PATH]
dev_dir = paths[self.DEVICE_PATH].strip('*') # remove potential trailing '*'
if (not os.listdir(after_dir) and
self.device.file_exists(dev_dir) and
self.device.listdir(dev_dir)):
self.logger.error('sysfs files were not pulled from the device.')
self.device_and_host_paths.remove(paths) # Path is removed to skip diffing it
for _, before_dir, after_dir, diff_dir in self.device_and_host_paths:
_diff_sysfs_dirs(before_dir, after_dir, diff_dir)
def teardown(self, context):
self._one_time_setup_done = []
def finalize(self, context):
if self.use_tmpfs:
try:
self.device.execute('umount {}'.format(self.tmpfs_mount_point), as_root=True)
except (DeviceError, CalledProcessError):
# assume a directory but not mount point
pass
self.device.execute('rm -rf {}'.format(self.tmpfs_mount_point),
as_root=True, check_exit_code=False)
def validate(self):
if not self.tmpfs_mount_point: # pylint: disable=access-member-before-definition
self.tmpfs_mount_point = self.device.path.join(self.device.working_directory, 'temp-fs')
def _local_dir(self, directory):
return os.path.dirname(as_relative(directory).replace(self.device.path.sep, os.sep))
class ExecutionTimeInstrument(Instrument):
name = 'execution_time'
description = """
Measure how long it took to execute the run() methods of a Workload.
"""
priority = 15
def __init__(self, device, **kwargs):
super(ExecutionTimeInstrument, self).__init__(device, **kwargs)
self.start_time = None
self.end_time = None
def on_run_start(self, context):
signal.connect(self.get_start_time, signal.BEFORE_WORKLOAD_EXECUTION, priority=self.priority)
signal.connect(self.get_stop_time, signal.AFTER_WORKLOAD_EXECUTION, priority=self.priority)
def get_start_time(self, context):
self.start_time = time.time()
def get_stop_time(self, context):
self.end_time = time.time()
def update_result(self, context):
execution_time = self.end_time - self.start_time
context.result.add_metric('execution_time', execution_time, 'seconds')
class ApkVersion(Instrument):
name = 'apk_version'
description = """
(DEPRECATED) Extracts APK versions for workloads that have them.
This instrument is deprecated and should not be used. It will be removed in
future versions of Workload Automation.
Versions of Android packages are now automatically attached to the results as
"apk_version" classfiers.
"""
def __init__(self, device, **kwargs):
super(ApkVersion, self).__init__(device, **kwargs)
self.apk_info = None
def setup(self, context):
if hasattr(context.workload, 'apk_file'):
self.apk_info = ApkInfo(context.workload.apk_file)
else:
self.apk_info = None
def update_result(self, context):
if self.apk_info:
context.result.add_metric(self.name, self.apk_info.version_name)
class InterruptStatsInstrument(Instrument):
name = 'interrupts'
description = """
Pulls the ``/proc/interrupts`` file before and after workload execution and diffs them
to show what interrupts occurred during that time.
"""
def __init__(self, device, **kwargs):
super(InterruptStatsInstrument, self).__init__(device, **kwargs)
self.before_file = None
self.after_file = None
self.diff_file = None
def setup(self, context):
self.before_file = os.path.join(context.output_directory, 'before', 'proc', 'interrupts')
self.after_file = os.path.join(context.output_directory, 'after', 'proc', 'interrupts')
self.diff_file = os.path.join(context.output_directory, 'diff', 'proc', 'interrupts')
def start(self, context):
with open(_f(self.before_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def stop(self, context):
with open(_f(self.after_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def update_result(self, context):
# If workload execution failed, the after_file may not have been created.
if os.path.isfile(self.after_file):
_diff_interrupt_files(self.before_file, self.after_file, _f(self.diff_file))
class DynamicFrequencyInstrument(SysfsExtractor):
name = 'cpufreq'
description = """
Collects dynamic frequency (DVFS) settings before and after workload execution.
"""
tarname = 'cpufreq.tar'
parameters = [
Parameter('paths', mandatory=False, override=True),
]
def setup(self, context):
self.paths = ['/sys/devices/system/cpu']
if self.use_tmpfs:
self.paths.append('/sys/class/devfreq/*') # the '*' would cause problems for adb pull.
super(DynamicFrequencyInstrument, self).setup(context)
def validate(self):
# temp-fs would have been set in super's validate, if not explicitly specified.
if not self.tmpfs_mount_point.endswith('-cpufreq'): # pylint: disable=access-member-before-definition
self.tmpfs_mount_point += '-cpufreq'
def _diff_interrupt_files(before, after, result): # pylint: disable=R0914
output_lines = []
with open(before) as bfh:
with open(after) as ofh:
for bline, aline in izip(bfh, ofh): | if achunks[0] == bchunks[0]:
diffchunks = ['']
diffchunks.append(achunks[0])
diffchunks.extend([diff_tokens(b, a) for b, a
in zip(bchunks[1:], achunks[1:])])
output_lines.append(diffchunks)
break
else: # new category appeared in the after file
diffchunks = ['>'] + achunks
output_lines.append(diffchunks)
try:
aline = ofh.next()
except StopIteration:
break
# Offset heading columns by one to allow for row labels on subsequent
# lines.
output_lines[0].insert(0, '')
# Any "columns" that do not have headings in the first row are not actually
# columns -- they are a single column where space-spearated words got
# split. Merge them back together to prevent them from being
# column-aligned by write_table.
table_rows = [output_lines[0]]
num_cols = len(output_lines[0])
for row in output_lines[1:]:
table_row = row[:num_cols]
table_row.append(' '.join(row[num_cols:]))
table_rows.append(table_row)
with open(result, 'w') as wfh:
write_table(table_rows, wfh)
def _diff_sysfs_dirs(before, after, result): # pylint: disable=R0914
before_files = []
os.path.walk(before,
lambda arg, dirname, names: arg.extend([os.path.join(dirname, f) for f in names]),
before_files
)
before_files = filter(os.path.isfile, before_files)
files = [os.path.relpath(f, before) for f in before_files]
after_files = [os.path.join(after, f) for f in files]
diff_files = [os.path.join(result, f) for f in files]
for bfile, afile, dfile in zip(before_files, after_files, diff_files):
if not os.path.isfile(afile):
logger.debug('sysfs_diff: {} does not exist or is not a file'.format(afile))
continue
with open(bfile) as bfh, open(afile) as afh: # pylint: disable=C0321
with open(_f(dfile), 'w') as dfh:
for i, (bline, aline) in enumerate(izip_longest(bfh, afh), 1):
if aline is None:
logger.debug('Lines missing from {}'.format(afile))
break
bchunks = re.split(r'(\W+)', bline)
achunks = re.split(r'(\W+)', aline)
if len(bchunks) != len(achunks):
logger.debug('Token length mismatch in {} on line {}'.format(bfile, i))
dfh.write('xxx ' + bline)
continue
if ((len([c for c in bchunks if c.strip()]) == len([c for c in achunks if c.strip()]) == 2) and
(bchunks[0] == achunks[0])):
# if there are only two columns and the first column is the
# same, assume it's a "header" column and do not diff it.
dchunks = [bchunks[0]] + [diff_tokens(b, a) for b, a in zip(bchunks[1:], achunks[1:])]
else:
dchunks = [diff_tokens(b, a) for b, a in zip(bchunks, achunks)]
dfh.write(''.join(dchunks)) | bchunks = bline.strip().split()
while True:
achunks = aline.strip().split() | random_line_split |
__init__.py | # Copyright 2013-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable=W0613,no-member,attribute-defined-outside-init
"""
Some "standard" instruments to collect additional info about workload execution.
.. note:: The run() method of a Workload may perform some "boilerplate" as well as
the actual execution of the workload (e.g. it may contain UI automation
needed to start the workload). This "boilerplate" execution will also
be measured by these instruments. As such, they are not suitable for collected
precise data about specific operations.
"""
import os
import re
import logging
import time
import tarfile
from itertools import izip, izip_longest
from subprocess import CalledProcessError
from wlauto import Instrument, Parameter
from wlauto.core import signal
from wlauto.exceptions import DeviceError, ConfigError
from wlauto.utils.misc import diff_tokens, write_table, check_output, as_relative
from wlauto.utils.misc import ensure_file_directory_exists as _f
from wlauto.utils.misc import ensure_directory_exists as _d
from wlauto.utils.android import ApkInfo
from wlauto.utils.types import list_of_strings
logger = logging.getLogger(__name__)
class SysfsExtractor(Instrument):
name = 'sysfs_extractor'
description = """
Collects the contest of a set of directories, before and after workload execution
and diffs the result.
"""
mount_command = 'mount -t tmpfs -o size={} tmpfs {}'
extract_timeout = 30
tarname = 'sysfs.tar'
DEVICE_PATH = 0
BEFORE_PATH = 1
AFTER_PATH = 2
DIFF_PATH = 3
parameters = [
Parameter('paths', kind=list_of_strings, mandatory=True,
description="""A list of paths to be pulled from the device. These could be directories
as well as files.""",
global_alias='sysfs_extract_dirs'),
Parameter('use_tmpfs', kind=bool, default=None,
description="""
Specifies whether tmpfs should be used to cache sysfile trees and then pull them down
as a tarball. This is significantly faster then just copying the directory trees from
the device directly, bur requres root and may not work on all devices. Defaults to
``True`` if the device is rooted and ``False`` if it is not.
"""),
Parameter('tmpfs_mount_point', default=None,
description="""Mount point for tmpfs partition used to store snapshots of paths."""),
Parameter('tmpfs_size', default='32m',
description="""Size of the tempfs partition."""),
]
def initialize(self, context):
if not self.device.is_rooted and self.use_tmpfs: # pylint: disable=access-member-before-definition
raise ConfigError('use_tempfs must be False for an unrooted device.')
elif self.use_tmpfs is None: # pylint: disable=access-member-before-definition
self.use_tmpfs = self.device.is_rooted
if self.use_tmpfs:
self.on_device_before = self.device.path.join(self.tmpfs_mount_point, 'before')
self.on_device_after = self.device.path.join(self.tmpfs_mount_point, 'after')
if not self.device.file_exists(self.tmpfs_mount_point):
self.device.execute('mkdir -p {}'.format(self.tmpfs_mount_point), as_root=True)
self.device.execute(self.mount_command.format(self.tmpfs_size, self.tmpfs_mount_point),
as_root=True)
def setup(self, context):
before_dirs = [
_d(os.path.join(context.output_directory, 'before', self._local_dir(d)))
for d in self.paths
]
after_dirs = [
_d(os.path.join(context.output_directory, 'after', self._local_dir(d)))
for d in self.paths
]
diff_dirs = [
_d(os.path.join(context.output_directory, 'diff', self._local_dir(d)))
for d in self.paths
]
self.device_and_host_paths = zip(self.paths, before_dirs, after_dirs, diff_dirs)
if self.use_tmpfs:
for d in self.paths:
before_dir = self.device.path.join(self.on_device_before,
self.device.path.dirname(as_relative(d)))
after_dir = self.device.path.join(self.on_device_after,
self.device.path.dirname(as_relative(d)))
if self.device.file_exists(before_dir):
self.device.execute('rm -rf {}'.format(before_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(before_dir), as_root=True)
if self.device.file_exists(after_dir):
self.device.execute('rm -rf {}'.format(after_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(after_dir), as_root=True)
def slow_start(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_before, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not rooted
for dev_dir, before_dir, _, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, before_dir)
def slow_stop(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_after, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not using tmpfs
for dev_dir, _, after_dir, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, after_dir)
def update_result(self, context):
if self.use_tmpfs:
on_device_tarball = self.device.path.join(self.device.working_directory, self.tarname)
on_host_tarball = self.device.path.join(context.output_directory, self.tarname + ".gz")
self.device.execute('{} tar cf {} -C {} .'.format(self.device.busybox,
on_device_tarball,
self.tmpfs_mount_point),
as_root=True)
self.device.execute('chmod 0777 {}'.format(on_device_tarball), as_root=True)
self.device.execute('{} gzip {}'.format(self.device.busybox,
on_device_tarball))
self.device.pull_file(on_device_tarball + ".gz", on_host_tarball)
with tarfile.open(on_host_tarball, 'r:gz') as tf:
tf.extractall(context.output_directory)
self.device.delete_file(on_device_tarball + ".gz")
os.remove(on_host_tarball)
for paths in self.device_and_host_paths:
after_dir = paths[self.AFTER_PATH]
dev_dir = paths[self.DEVICE_PATH].strip('*') # remove potential trailing '*'
if (not os.listdir(after_dir) and
self.device.file_exists(dev_dir) and
self.device.listdir(dev_dir)):
self.logger.error('sysfs files were not pulled from the device.')
self.device_and_host_paths.remove(paths) # Path is removed to skip diffing it
for _, before_dir, after_dir, diff_dir in self.device_and_host_paths:
_diff_sysfs_dirs(before_dir, after_dir, diff_dir)
def teardown(self, context):
self._one_time_setup_done = []
def finalize(self, context):
if self.use_tmpfs:
try:
self.device.execute('umount {}'.format(self.tmpfs_mount_point), as_root=True)
except (DeviceError, CalledProcessError):
# assume a directory but not mount point
pass
self.device.execute('rm -rf {}'.format(self.tmpfs_mount_point),
as_root=True, check_exit_code=False)
def validate(self):
if not self.tmpfs_mount_point: # pylint: disable=access-member-before-definition
self.tmpfs_mount_point = self.device.path.join(self.device.working_directory, 'temp-fs')
def _local_dir(self, directory):
return os.path.dirname(as_relative(directory).replace(self.device.path.sep, os.sep))
class ExecutionTimeInstrument(Instrument):
name = 'execution_time'
description = """
Measure how long it took to execute the run() methods of a Workload.
"""
priority = 15
def __init__(self, device, **kwargs):
super(ExecutionTimeInstrument, self).__init__(device, **kwargs)
self.start_time = None
self.end_time = None
def on_run_start(self, context):
signal.connect(self.get_start_time, signal.BEFORE_WORKLOAD_EXECUTION, priority=self.priority)
signal.connect(self.get_stop_time, signal.AFTER_WORKLOAD_EXECUTION, priority=self.priority)
def get_start_time(self, context):
self.start_time = time.time()
def get_stop_time(self, context):
self.end_time = time.time()
def update_result(self, context):
execution_time = self.end_time - self.start_time
context.result.add_metric('execution_time', execution_time, 'seconds')
class ApkVersion(Instrument):
name = 'apk_version'
description = """
(DEPRECATED) Extracts APK versions for workloads that have them.
This instrument is deprecated and should not be used. It will be removed in
future versions of Workload Automation.
Versions of Android packages are now automatically attached to the results as
"apk_version" classfiers.
"""
def __init__(self, device, **kwargs):
super(ApkVersion, self).__init__(device, **kwargs)
self.apk_info = None
def setup(self, context):
if hasattr(context.workload, 'apk_file'):
self.apk_info = ApkInfo(context.workload.apk_file)
else:
self.apk_info = None
def update_result(self, context):
if self.apk_info:
context.result.add_metric(self.name, self.apk_info.version_name)
class InterruptStatsInstrument(Instrument):
name = 'interrupts'
description = """
Pulls the ``/proc/interrupts`` file before and after workload execution and diffs them
to show what interrupts occurred during that time.
"""
def __init__(self, device, **kwargs):
super(InterruptStatsInstrument, self).__init__(device, **kwargs)
self.before_file = None
self.after_file = None
self.diff_file = None
def setup(self, context):
self.before_file = os.path.join(context.output_directory, 'before', 'proc', 'interrupts')
self.after_file = os.path.join(context.output_directory, 'after', 'proc', 'interrupts')
self.diff_file = os.path.join(context.output_directory, 'diff', 'proc', 'interrupts')
def start(self, context):
with open(_f(self.before_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def | (self, context):
with open(_f(self.after_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def update_result(self, context):
# If workload execution failed, the after_file may not have been created.
if os.path.isfile(self.after_file):
_diff_interrupt_files(self.before_file, self.after_file, _f(self.diff_file))
class DynamicFrequencyInstrument(SysfsExtractor):
name = 'cpufreq'
description = """
Collects dynamic frequency (DVFS) settings before and after workload execution.
"""
tarname = 'cpufreq.tar'
parameters = [
Parameter('paths', mandatory=False, override=True),
]
def setup(self, context):
self.paths = ['/sys/devices/system/cpu']
if self.use_tmpfs:
self.paths.append('/sys/class/devfreq/*') # the '*' would cause problems for adb pull.
super(DynamicFrequencyInstrument, self).setup(context)
def validate(self):
# temp-fs would have been set in super's validate, if not explicitly specified.
if not self.tmpfs_mount_point.endswith('-cpufreq'): # pylint: disable=access-member-before-definition
self.tmpfs_mount_point += '-cpufreq'
def _diff_interrupt_files(before, after, result): # pylint: disable=R0914
output_lines = []
with open(before) as bfh:
with open(after) as ofh:
for bline, aline in izip(bfh, ofh):
bchunks = bline.strip().split()
while True:
achunks = aline.strip().split()
if achunks[0] == bchunks[0]:
diffchunks = ['']
diffchunks.append(achunks[0])
diffchunks.extend([diff_tokens(b, a) for b, a
in zip(bchunks[1:], achunks[1:])])
output_lines.append(diffchunks)
break
else: # new category appeared in the after file
diffchunks = ['>'] + achunks
output_lines.append(diffchunks)
try:
aline = ofh.next()
except StopIteration:
break
# Offset heading columns by one to allow for row labels on subsequent
# lines.
output_lines[0].insert(0, '')
# Any "columns" that do not have headings in the first row are not actually
# columns -- they are a single column where space-spearated words got
# split. Merge them back together to prevent them from being
# column-aligned by write_table.
table_rows = [output_lines[0]]
num_cols = len(output_lines[0])
for row in output_lines[1:]:
table_row = row[:num_cols]
table_row.append(' '.join(row[num_cols:]))
table_rows.append(table_row)
with open(result, 'w') as wfh:
write_table(table_rows, wfh)
def _diff_sysfs_dirs(before, after, result): # pylint: disable=R0914
before_files = []
os.path.walk(before,
lambda arg, dirname, names: arg.extend([os.path.join(dirname, f) for f in names]),
before_files
)
before_files = filter(os.path.isfile, before_files)
files = [os.path.relpath(f, before) for f in before_files]
after_files = [os.path.join(after, f) for f in files]
diff_files = [os.path.join(result, f) for f in files]
for bfile, afile, dfile in zip(before_files, after_files, diff_files):
if not os.path.isfile(afile):
logger.debug('sysfs_diff: {} does not exist or is not a file'.format(afile))
continue
with open(bfile) as bfh, open(afile) as afh: # pylint: disable=C0321
with open(_f(dfile), 'w') as dfh:
for i, (bline, aline) in enumerate(izip_longest(bfh, afh), 1):
if aline is None:
logger.debug('Lines missing from {}'.format(afile))
break
bchunks = re.split(r'(\W+)', bline)
achunks = re.split(r'(\W+)', aline)
if len(bchunks) != len(achunks):
logger.debug('Token length mismatch in {} on line {}'.format(bfile, i))
dfh.write('xxx ' + bline)
continue
if ((len([c for c in bchunks if c.strip()]) == len([c for c in achunks if c.strip()]) == 2) and
(bchunks[0] == achunks[0])):
# if there are only two columns and the first column is the
# same, assume it's a "header" column and do not diff it.
dchunks = [bchunks[0]] + [diff_tokens(b, a) for b, a in zip(bchunks[1:], achunks[1:])]
else:
dchunks = [diff_tokens(b, a) for b, a in zip(bchunks, achunks)]
dfh.write(''.join(dchunks))
| stop | identifier_name |
__init__.py | # Copyright 2013-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable=W0613,no-member,attribute-defined-outside-init
"""
Some "standard" instruments to collect additional info about workload execution.
.. note:: The run() method of a Workload may perform some "boilerplate" as well as
the actual execution of the workload (e.g. it may contain UI automation
needed to start the workload). This "boilerplate" execution will also
be measured by these instruments. As such, they are not suitable for collected
precise data about specific operations.
"""
import os
import re
import logging
import time
import tarfile
from itertools import izip, izip_longest
from subprocess import CalledProcessError
from wlauto import Instrument, Parameter
from wlauto.core import signal
from wlauto.exceptions import DeviceError, ConfigError
from wlauto.utils.misc import diff_tokens, write_table, check_output, as_relative
from wlauto.utils.misc import ensure_file_directory_exists as _f
from wlauto.utils.misc import ensure_directory_exists as _d
from wlauto.utils.android import ApkInfo
from wlauto.utils.types import list_of_strings
logger = logging.getLogger(__name__)
class SysfsExtractor(Instrument):
name = 'sysfs_extractor'
description = """
Collects the contest of a set of directories, before and after workload execution
and diffs the result.
"""
mount_command = 'mount -t tmpfs -o size={} tmpfs {}'
extract_timeout = 30
tarname = 'sysfs.tar'
DEVICE_PATH = 0
BEFORE_PATH = 1
AFTER_PATH = 2
DIFF_PATH = 3
parameters = [
Parameter('paths', kind=list_of_strings, mandatory=True,
description="""A list of paths to be pulled from the device. These could be directories
as well as files.""",
global_alias='sysfs_extract_dirs'),
Parameter('use_tmpfs', kind=bool, default=None,
description="""
Specifies whether tmpfs should be used to cache sysfile trees and then pull them down
as a tarball. This is significantly faster then just copying the directory trees from
the device directly, bur requres root and may not work on all devices. Defaults to
``True`` if the device is rooted and ``False`` if it is not.
"""),
Parameter('tmpfs_mount_point', default=None,
description="""Mount point for tmpfs partition used to store snapshots of paths."""),
Parameter('tmpfs_size', default='32m',
description="""Size of the tempfs partition."""),
]
def initialize(self, context):
if not self.device.is_rooted and self.use_tmpfs: # pylint: disable=access-member-before-definition
raise ConfigError('use_tempfs must be False for an unrooted device.')
elif self.use_tmpfs is None: # pylint: disable=access-member-before-definition
self.use_tmpfs = self.device.is_rooted
if self.use_tmpfs:
self.on_device_before = self.device.path.join(self.tmpfs_mount_point, 'before')
self.on_device_after = self.device.path.join(self.tmpfs_mount_point, 'after')
if not self.device.file_exists(self.tmpfs_mount_point):
self.device.execute('mkdir -p {}'.format(self.tmpfs_mount_point), as_root=True)
self.device.execute(self.mount_command.format(self.tmpfs_size, self.tmpfs_mount_point),
as_root=True)
def setup(self, context):
before_dirs = [
_d(os.path.join(context.output_directory, 'before', self._local_dir(d)))
for d in self.paths
]
after_dirs = [
_d(os.path.join(context.output_directory, 'after', self._local_dir(d)))
for d in self.paths
]
diff_dirs = [
_d(os.path.join(context.output_directory, 'diff', self._local_dir(d)))
for d in self.paths
]
self.device_and_host_paths = zip(self.paths, before_dirs, after_dirs, diff_dirs)
if self.use_tmpfs:
|
def slow_start(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_before, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not rooted
for dev_dir, before_dir, _, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, before_dir)
def slow_stop(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_after, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not using tmpfs
for dev_dir, _, after_dir, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, after_dir)
def update_result(self, context):
if self.use_tmpfs:
on_device_tarball = self.device.path.join(self.device.working_directory, self.tarname)
on_host_tarball = self.device.path.join(context.output_directory, self.tarname + ".gz")
self.device.execute('{} tar cf {} -C {} .'.format(self.device.busybox,
on_device_tarball,
self.tmpfs_mount_point),
as_root=True)
self.device.execute('chmod 0777 {}'.format(on_device_tarball), as_root=True)
self.device.execute('{} gzip {}'.format(self.device.busybox,
on_device_tarball))
self.device.pull_file(on_device_tarball + ".gz", on_host_tarball)
with tarfile.open(on_host_tarball, 'r:gz') as tf:
tf.extractall(context.output_directory)
self.device.delete_file(on_device_tarball + ".gz")
os.remove(on_host_tarball)
for paths in self.device_and_host_paths:
after_dir = paths[self.AFTER_PATH]
dev_dir = paths[self.DEVICE_PATH].strip('*') # remove potential trailing '*'
if (not os.listdir(after_dir) and
self.device.file_exists(dev_dir) and
self.device.listdir(dev_dir)):
self.logger.error('sysfs files were not pulled from the device.')
self.device_and_host_paths.remove(paths) # Path is removed to skip diffing it
for _, before_dir, after_dir, diff_dir in self.device_and_host_paths:
_diff_sysfs_dirs(before_dir, after_dir, diff_dir)
def teardown(self, context):
self._one_time_setup_done = []
def finalize(self, context):
if self.use_tmpfs:
try:
self.device.execute('umount {}'.format(self.tmpfs_mount_point), as_root=True)
except (DeviceError, CalledProcessError):
# assume a directory but not mount point
pass
self.device.execute('rm -rf {}'.format(self.tmpfs_mount_point),
as_root=True, check_exit_code=False)
def validate(self):
if not self.tmpfs_mount_point: # pylint: disable=access-member-before-definition
self.tmpfs_mount_point = self.device.path.join(self.device.working_directory, 'temp-fs')
def _local_dir(self, directory):
return os.path.dirname(as_relative(directory).replace(self.device.path.sep, os.sep))
class ExecutionTimeInstrument(Instrument):
name = 'execution_time'
description = """
Measure how long it took to execute the run() methods of a Workload.
"""
priority = 15
def __init__(self, device, **kwargs):
super(ExecutionTimeInstrument, self).__init__(device, **kwargs)
self.start_time = None
self.end_time = None
def on_run_start(self, context):
signal.connect(self.get_start_time, signal.BEFORE_WORKLOAD_EXECUTION, priority=self.priority)
signal.connect(self.get_stop_time, signal.AFTER_WORKLOAD_EXECUTION, priority=self.priority)
def get_start_time(self, context):
self.start_time = time.time()
def get_stop_time(self, context):
self.end_time = time.time()
def update_result(self, context):
execution_time = self.end_time - self.start_time
context.result.add_metric('execution_time', execution_time, 'seconds')
class ApkVersion(Instrument):
name = 'apk_version'
description = """
(DEPRECATED) Extracts APK versions for workloads that have them.
This instrument is deprecated and should not be used. It will be removed in
future versions of Workload Automation.
Versions of Android packages are now automatically attached to the results as
"apk_version" classfiers.
"""
def __init__(self, device, **kwargs):
super(ApkVersion, self).__init__(device, **kwargs)
self.apk_info = None
def setup(self, context):
if hasattr(context.workload, 'apk_file'):
self.apk_info = ApkInfo(context.workload.apk_file)
else:
self.apk_info = None
def update_result(self, context):
if self.apk_info:
context.result.add_metric(self.name, self.apk_info.version_name)
class InterruptStatsInstrument(Instrument):
name = 'interrupts'
description = """
Pulls the ``/proc/interrupts`` file before and after workload execution and diffs them
to show what interrupts occurred during that time.
"""
def __init__(self, device, **kwargs):
super(InterruptStatsInstrument, self).__init__(device, **kwargs)
self.before_file = None
self.after_file = None
self.diff_file = None
def setup(self, context):
self.before_file = os.path.join(context.output_directory, 'before', 'proc', 'interrupts')
self.after_file = os.path.join(context.output_directory, 'after', 'proc', 'interrupts')
self.diff_file = os.path.join(context.output_directory, 'diff', 'proc', 'interrupts')
def start(self, context):
with open(_f(self.before_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def stop(self, context):
with open(_f(self.after_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def update_result(self, context):
# If workload execution failed, the after_file may not have been created.
if os.path.isfile(self.after_file):
_diff_interrupt_files(self.before_file, self.after_file, _f(self.diff_file))
class DynamicFrequencyInstrument(SysfsExtractor):
name = 'cpufreq'
description = """
Collects dynamic frequency (DVFS) settings before and after workload execution.
"""
tarname = 'cpufreq.tar'
parameters = [
Parameter('paths', mandatory=False, override=True),
]
def setup(self, context):
self.paths = ['/sys/devices/system/cpu']
if self.use_tmpfs:
self.paths.append('/sys/class/devfreq/*') # the '*' would cause problems for adb pull.
super(DynamicFrequencyInstrument, self).setup(context)
def validate(self):
# temp-fs would have been set in super's validate, if not explicitly specified.
if not self.tmpfs_mount_point.endswith('-cpufreq'): # pylint: disable=access-member-before-definition
self.tmpfs_mount_point += '-cpufreq'
def _diff_interrupt_files(before, after, result): # pylint: disable=R0914
output_lines = []
with open(before) as bfh:
with open(after) as ofh:
for bline, aline in izip(bfh, ofh):
bchunks = bline.strip().split()
while True:
achunks = aline.strip().split()
if achunks[0] == bchunks[0]:
diffchunks = ['']
diffchunks.append(achunks[0])
diffchunks.extend([diff_tokens(b, a) for b, a
in zip(bchunks[1:], achunks[1:])])
output_lines.append(diffchunks)
break
else: # new category appeared in the after file
diffchunks = ['>'] + achunks
output_lines.append(diffchunks)
try:
aline = ofh.next()
except StopIteration:
break
# Offset heading columns by one to allow for row labels on subsequent
# lines.
output_lines[0].insert(0, '')
# Any "columns" that do not have headings in the first row are not actually
# columns -- they are a single column where space-spearated words got
# split. Merge them back together to prevent them from being
# column-aligned by write_table.
table_rows = [output_lines[0]]
num_cols = len(output_lines[0])
for row in output_lines[1:]:
table_row = row[:num_cols]
table_row.append(' '.join(row[num_cols:]))
table_rows.append(table_row)
with open(result, 'w') as wfh:
write_table(table_rows, wfh)
def _diff_sysfs_dirs(before, after, result): # pylint: disable=R0914
before_files = []
os.path.walk(before,
lambda arg, dirname, names: arg.extend([os.path.join(dirname, f) for f in names]),
before_files
)
before_files = filter(os.path.isfile, before_files)
files = [os.path.relpath(f, before) for f in before_files]
after_files = [os.path.join(after, f) for f in files]
diff_files = [os.path.join(result, f) for f in files]
for bfile, afile, dfile in zip(before_files, after_files, diff_files):
if not os.path.isfile(afile):
logger.debug('sysfs_diff: {} does not exist or is not a file'.format(afile))
continue
with open(bfile) as bfh, open(afile) as afh: # pylint: disable=C0321
with open(_f(dfile), 'w') as dfh:
for i, (bline, aline) in enumerate(izip_longest(bfh, afh), 1):
if aline is None:
logger.debug('Lines missing from {}'.format(afile))
break
bchunks = re.split(r'(\W+)', bline)
achunks = re.split(r'(\W+)', aline)
if len(bchunks) != len(achunks):
logger.debug('Token length mismatch in {} on line {}'.format(bfile, i))
dfh.write('xxx ' + bline)
continue
if ((len([c for c in bchunks if c.strip()]) == len([c for c in achunks if c.strip()]) == 2) and
(bchunks[0] == achunks[0])):
# if there are only two columns and the first column is the
# same, assume it's a "header" column and do not diff it.
dchunks = [bchunks[0]] + [diff_tokens(b, a) for b, a in zip(bchunks[1:], achunks[1:])]
else:
dchunks = [diff_tokens(b, a) for b, a in zip(bchunks, achunks)]
dfh.write(''.join(dchunks))
| for d in self.paths:
before_dir = self.device.path.join(self.on_device_before,
self.device.path.dirname(as_relative(d)))
after_dir = self.device.path.join(self.on_device_after,
self.device.path.dirname(as_relative(d)))
if self.device.file_exists(before_dir):
self.device.execute('rm -rf {}'.format(before_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(before_dir), as_root=True)
if self.device.file_exists(after_dir):
self.device.execute('rm -rf {}'.format(after_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(after_dir), as_root=True) | conditional_block |
__init__.py | # Copyright 2013-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable=W0613,no-member,attribute-defined-outside-init
"""
Some "standard" instruments to collect additional info about workload execution.
.. note:: The run() method of a Workload may perform some "boilerplate" as well as
the actual execution of the workload (e.g. it may contain UI automation
needed to start the workload). This "boilerplate" execution will also
be measured by these instruments. As such, they are not suitable for collected
precise data about specific operations.
"""
import os
import re
import logging
import time
import tarfile
from itertools import izip, izip_longest
from subprocess import CalledProcessError
from wlauto import Instrument, Parameter
from wlauto.core import signal
from wlauto.exceptions import DeviceError, ConfigError
from wlauto.utils.misc import diff_tokens, write_table, check_output, as_relative
from wlauto.utils.misc import ensure_file_directory_exists as _f
from wlauto.utils.misc import ensure_directory_exists as _d
from wlauto.utils.android import ApkInfo
from wlauto.utils.types import list_of_strings
logger = logging.getLogger(__name__)
class SysfsExtractor(Instrument):
name = 'sysfs_extractor'
description = """
Collects the contest of a set of directories, before and after workload execution
and diffs the result.
"""
mount_command = 'mount -t tmpfs -o size={} tmpfs {}'
extract_timeout = 30
tarname = 'sysfs.tar'
DEVICE_PATH = 0
BEFORE_PATH = 1
AFTER_PATH = 2
DIFF_PATH = 3
parameters = [
Parameter('paths', kind=list_of_strings, mandatory=True,
description="""A list of paths to be pulled from the device. These could be directories
as well as files.""",
global_alias='sysfs_extract_dirs'),
Parameter('use_tmpfs', kind=bool, default=None,
description="""
Specifies whether tmpfs should be used to cache sysfile trees and then pull them down
as a tarball. This is significantly faster then just copying the directory trees from
the device directly, bur requres root and may not work on all devices. Defaults to
``True`` if the device is rooted and ``False`` if it is not.
"""),
Parameter('tmpfs_mount_point', default=None,
description="""Mount point for tmpfs partition used to store snapshots of paths."""),
Parameter('tmpfs_size', default='32m',
description="""Size of the tempfs partition."""),
]
def initialize(self, context):
if not self.device.is_rooted and self.use_tmpfs: # pylint: disable=access-member-before-definition
raise ConfigError('use_tempfs must be False for an unrooted device.')
elif self.use_tmpfs is None: # pylint: disable=access-member-before-definition
self.use_tmpfs = self.device.is_rooted
if self.use_tmpfs:
self.on_device_before = self.device.path.join(self.tmpfs_mount_point, 'before')
self.on_device_after = self.device.path.join(self.tmpfs_mount_point, 'after')
if not self.device.file_exists(self.tmpfs_mount_point):
self.device.execute('mkdir -p {}'.format(self.tmpfs_mount_point), as_root=True)
self.device.execute(self.mount_command.format(self.tmpfs_size, self.tmpfs_mount_point),
as_root=True)
def setup(self, context):
before_dirs = [
_d(os.path.join(context.output_directory, 'before', self._local_dir(d)))
for d in self.paths
]
after_dirs = [
_d(os.path.join(context.output_directory, 'after', self._local_dir(d)))
for d in self.paths
]
diff_dirs = [
_d(os.path.join(context.output_directory, 'diff', self._local_dir(d)))
for d in self.paths
]
self.device_and_host_paths = zip(self.paths, before_dirs, after_dirs, diff_dirs)
if self.use_tmpfs:
for d in self.paths:
before_dir = self.device.path.join(self.on_device_before,
self.device.path.dirname(as_relative(d)))
after_dir = self.device.path.join(self.on_device_after,
self.device.path.dirname(as_relative(d)))
if self.device.file_exists(before_dir):
self.device.execute('rm -rf {}'.format(before_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(before_dir), as_root=True)
if self.device.file_exists(after_dir):
self.device.execute('rm -rf {}'.format(after_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(after_dir), as_root=True)
def slow_start(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_before, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not rooted
for dev_dir, before_dir, _, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, before_dir)
def slow_stop(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_after, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not using tmpfs
for dev_dir, _, after_dir, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, after_dir)
def update_result(self, context):
if self.use_tmpfs:
on_device_tarball = self.device.path.join(self.device.working_directory, self.tarname)
on_host_tarball = self.device.path.join(context.output_directory, self.tarname + ".gz")
self.device.execute('{} tar cf {} -C {} .'.format(self.device.busybox,
on_device_tarball,
self.tmpfs_mount_point),
as_root=True)
self.device.execute('chmod 0777 {}'.format(on_device_tarball), as_root=True)
self.device.execute('{} gzip {}'.format(self.device.busybox,
on_device_tarball))
self.device.pull_file(on_device_tarball + ".gz", on_host_tarball)
with tarfile.open(on_host_tarball, 'r:gz') as tf:
tf.extractall(context.output_directory)
self.device.delete_file(on_device_tarball + ".gz")
os.remove(on_host_tarball)
for paths in self.device_and_host_paths:
after_dir = paths[self.AFTER_PATH]
dev_dir = paths[self.DEVICE_PATH].strip('*') # remove potential trailing '*'
if (not os.listdir(after_dir) and
self.device.file_exists(dev_dir) and
self.device.listdir(dev_dir)):
self.logger.error('sysfs files were not pulled from the device.')
self.device_and_host_paths.remove(paths) # Path is removed to skip diffing it
for _, before_dir, after_dir, diff_dir in self.device_and_host_paths:
_diff_sysfs_dirs(before_dir, after_dir, diff_dir)
def teardown(self, context):
self._one_time_setup_done = []
def finalize(self, context):
if self.use_tmpfs:
try:
self.device.execute('umount {}'.format(self.tmpfs_mount_point), as_root=True)
except (DeviceError, CalledProcessError):
# assume a directory but not mount point
pass
self.device.execute('rm -rf {}'.format(self.tmpfs_mount_point),
as_root=True, check_exit_code=False)
def validate(self):
if not self.tmpfs_mount_point: # pylint: disable=access-member-before-definition
self.tmpfs_mount_point = self.device.path.join(self.device.working_directory, 'temp-fs')
def _local_dir(self, directory):
return os.path.dirname(as_relative(directory).replace(self.device.path.sep, os.sep))
class ExecutionTimeInstrument(Instrument):
name = 'execution_time'
description = """
Measure how long it took to execute the run() methods of a Workload.
"""
priority = 15
def __init__(self, device, **kwargs):
super(ExecutionTimeInstrument, self).__init__(device, **kwargs)
self.start_time = None
self.end_time = None
def on_run_start(self, context):
signal.connect(self.get_start_time, signal.BEFORE_WORKLOAD_EXECUTION, priority=self.priority)
signal.connect(self.get_stop_time, signal.AFTER_WORKLOAD_EXECUTION, priority=self.priority)
def get_start_time(self, context):
self.start_time = time.time()
def get_stop_time(self, context):
self.end_time = time.time()
def update_result(self, context):
execution_time = self.end_time - self.start_time
context.result.add_metric('execution_time', execution_time, 'seconds')
class ApkVersion(Instrument):
name = 'apk_version'
description = """
(DEPRECATED) Extracts APK versions for workloads that have them.
This instrument is deprecated and should not be used. It will be removed in
future versions of Workload Automation.
Versions of Android packages are now automatically attached to the results as
"apk_version" classfiers.
"""
def __init__(self, device, **kwargs):
super(ApkVersion, self).__init__(device, **kwargs)
self.apk_info = None
def setup(self, context):
if hasattr(context.workload, 'apk_file'):
self.apk_info = ApkInfo(context.workload.apk_file)
else:
self.apk_info = None
def update_result(self, context):
if self.apk_info:
context.result.add_metric(self.name, self.apk_info.version_name)
class InterruptStatsInstrument(Instrument):
name = 'interrupts'
description = """
Pulls the ``/proc/interrupts`` file before and after workload execution and diffs them
to show what interrupts occurred during that time.
"""
def __init__(self, device, **kwargs):
super(InterruptStatsInstrument, self).__init__(device, **kwargs)
self.before_file = None
self.after_file = None
self.diff_file = None
def setup(self, context):
self.before_file = os.path.join(context.output_directory, 'before', 'proc', 'interrupts')
self.after_file = os.path.join(context.output_directory, 'after', 'proc', 'interrupts')
self.diff_file = os.path.join(context.output_directory, 'diff', 'proc', 'interrupts')
def start(self, context):
with open(_f(self.before_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def stop(self, context):
with open(_f(self.after_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def update_result(self, context):
# If workload execution failed, the after_file may not have been created.
if os.path.isfile(self.after_file):
_diff_interrupt_files(self.before_file, self.after_file, _f(self.diff_file))
class DynamicFrequencyInstrument(SysfsExtractor):
|
def _diff_interrupt_files(before, after, result): # pylint: disable=R0914
output_lines = []
with open(before) as bfh:
with open(after) as ofh:
for bline, aline in izip(bfh, ofh):
bchunks = bline.strip().split()
while True:
achunks = aline.strip().split()
if achunks[0] == bchunks[0]:
diffchunks = ['']
diffchunks.append(achunks[0])
diffchunks.extend([diff_tokens(b, a) for b, a
in zip(bchunks[1:], achunks[1:])])
output_lines.append(diffchunks)
break
else: # new category appeared in the after file
diffchunks = ['>'] + achunks
output_lines.append(diffchunks)
try:
aline = ofh.next()
except StopIteration:
break
# Offset heading columns by one to allow for row labels on subsequent
# lines.
output_lines[0].insert(0, '')
# Any "columns" that do not have headings in the first row are not actually
# columns -- they are a single column where space-spearated words got
# split. Merge them back together to prevent them from being
# column-aligned by write_table.
table_rows = [output_lines[0]]
num_cols = len(output_lines[0])
for row in output_lines[1:]:
table_row = row[:num_cols]
table_row.append(' '.join(row[num_cols:]))
table_rows.append(table_row)
with open(result, 'w') as wfh:
write_table(table_rows, wfh)
def _diff_sysfs_dirs(before, after, result): # pylint: disable=R0914
before_files = []
os.path.walk(before,
lambda arg, dirname, names: arg.extend([os.path.join(dirname, f) for f in names]),
before_files
)
before_files = filter(os.path.isfile, before_files)
files = [os.path.relpath(f, before) for f in before_files]
after_files = [os.path.join(after, f) for f in files]
diff_files = [os.path.join(result, f) for f in files]
for bfile, afile, dfile in zip(before_files, after_files, diff_files):
if not os.path.isfile(afile):
logger.debug('sysfs_diff: {} does not exist or is not a file'.format(afile))
continue
with open(bfile) as bfh, open(afile) as afh: # pylint: disable=C0321
with open(_f(dfile), 'w') as dfh:
for i, (bline, aline) in enumerate(izip_longest(bfh, afh), 1):
if aline is None:
logger.debug('Lines missing from {}'.format(afile))
break
bchunks = re.split(r'(\W+)', bline)
achunks = re.split(r'(\W+)', aline)
if len(bchunks) != len(achunks):
logger.debug('Token length mismatch in {} on line {}'.format(bfile, i))
dfh.write('xxx ' + bline)
continue
if ((len([c for c in bchunks if c.strip()]) == len([c for c in achunks if c.strip()]) == 2) and
(bchunks[0] == achunks[0])):
# if there are only two columns and the first column is the
# same, assume it's a "header" column and do not diff it.
dchunks = [bchunks[0]] + [diff_tokens(b, a) for b, a in zip(bchunks[1:], achunks[1:])]
else:
dchunks = [diff_tokens(b, a) for b, a in zip(bchunks, achunks)]
dfh.write(''.join(dchunks))
| name = 'cpufreq'
description = """
Collects dynamic frequency (DVFS) settings before and after workload execution.
"""
tarname = 'cpufreq.tar'
parameters = [
Parameter('paths', mandatory=False, override=True),
]
def setup(self, context):
self.paths = ['/sys/devices/system/cpu']
if self.use_tmpfs:
self.paths.append('/sys/class/devfreq/*') # the '*' would cause problems for adb pull.
super(DynamicFrequencyInstrument, self).setup(context)
def validate(self):
# temp-fs would have been set in super's validate, if not explicitly specified.
if not self.tmpfs_mount_point.endswith('-cpufreq'): # pylint: disable=access-member-before-definition
self.tmpfs_mount_point += '-cpufreq' | identifier_body |
preferences_default.py | """User preferences for KlustaViewa."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import logging
import numpy as np
# -----------------------------------------------------------------------------
# Logging
# -----------------------------------------------------------------------------
|
# Level of the logging file. DEBUG, INFO or WARNING, or just None to disable.
loglevel_file = logging.INFO
# -----------------------------------------------------------------------------
# Main window
# -----------------------------------------------------------------------------
# Should the software ask the user to save upon closing?
prompt_save_on_exit = True
delay_timer = .05
delay_buffer = .1
# -----------------------------------------------------------------------------
# Similarity matrix
# -----------------------------------------------------------------------------
similarity_measure = 'gaussian' # or 'kl' for KL divergence
# -----------------------------------------------------------------------------
# Waveform view
# -----------------------------------------------------------------------------
# Approximate maximum number of spikes pper cluster to show. Should be
# about 100 for low-end graphics cards, 1000 for high-end ones.
waveforms_nspikes_max_expected = 100
# The minimum number of spikes per cluster to display.
waveforms_nspikes_per_cluster_min = 10
# -----------------------------------------------------------------------------
# Feature view
# -----------------------------------------------------------------------------
# Opacity value of the background spikes.
feature_background_alpha = .25
# Opacity value of the spikes in the selected clusters.
feature_selected_alpha = .75
# Number of spikes to show in the background.
features_nspikes_background_max = 10000
# Maximum number of spikes per cluster to show.
features_nspikes_per_cluster_max = 1000
# Unit of the spike time in the feature view. Can be 'samples' or 'second'.
features_info_time_unit = 'second'
# -----------------------------------------------------------------------------
# Correlograms view
# -----------------------------------------------------------------------------
# Maximum number of clusters to show in the correlograms view.
correlograms_max_nclusters = 20
correlograms_nexcerpts = 100
correlograms_excerpt_size = 20000
# -----------------------------------------------------------------------------
# IPython import path
# -----------------------------------------------------------------------------
# Paths where all .py files are loaded in IPython view.
# "~" corresponds to the user home path, C:\Users\Username\ on Windows,
# /home/username/ on Linux, etc.
ipython_import_paths = ['~/.kwiklib/code']
# -----------------------------------------------------------------------------
# Unit tests
# -----------------------------------------------------------------------------
# Delay between two successive automatic operations in unit tests for views.
test_operator_delay = .1
# Whether to automatically close the views during unit testing.
test_auto_close = True | # Console logging level, can be DEBUG, INFO or WARNING.
loglevel = logging.INFO
| random_line_split |
component_fixture.ts | /**
* @license
* Copyright Google LLC 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 {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, getDebugNode, NgZone, RendererFactory2} from '@angular/core';
/**
* Fixture for debugging and testing a component.
*
* @publicApi
*/
export class ComponentFixture<T> {
/**
* The DebugElement associated with the root element of this component.
*/
debugElement: DebugElement;
/**
* The instance of the root component class.
*/
componentInstance: T;
/**
* The native element at the root of the component.
*/
nativeElement: any;
/**
* The ElementRef for the element at the root of the component.
*/
elementRef: ElementRef;
/**
* The ChangeDetectorRef for the component
*/
changeDetectorRef: ChangeDetectorRef;
private _renderer: RendererFactory2|null|undefined;
private _isStable: boolean = true;
private _isDestroyed: boolean = false;
private _resolve: ((result: any) => void)|null = null;
private _promise: Promise<any>|null = null;
private _onUnstableSubscription: any /** TODO #9100 */ = null;
private _onStableSubscription: any /** TODO #9100 */ = null;
private _onMicrotaskEmptySubscription: any /** TODO #9100 */ = null;
private _onErrorSubscription: any /** TODO #9100 */ = null;
constructor(
public componentRef: ComponentRef<T>, public ngZone: NgZone|null,
private _autoDetect: boolean) {
this.changeDetectorRef = componentRef.changeDetectorRef;
this.elementRef = componentRef.location;
this.debugElement = <DebugElement>getDebugNode(this.elementRef.nativeElement);
this.componentInstance = componentRef.instance;
this.nativeElement = this.elementRef.nativeElement;
this.componentRef = componentRef;
this.ngZone = ngZone;
if (ngZone) {
// Create subscriptions outside the NgZone so that the callbacks run oustide
// of NgZone.
ngZone.runOutsideAngular(() => {
this._onUnstableSubscription = ngZone.onUnstable.subscribe({
next: () => {
this._isStable = false;
}
});
this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
next: () => {
if (this._autoDetect) {
// Do a change detection run with checkNoChanges set to true to check
// there are no changes on the second run.
this.detectChanges(true);
}
}
});
this._onStableSubscription = ngZone.onStable.subscribe({
next: () => {
this._isStable = true;
// Check whether there is a pending whenStable() completer to resolve.
if (this._promise !== null) {
// If so check whether there are no pending macrotasks before resolving.
// Do this check in the next tick so that ngZone gets a chance to update the state of
// pending macrotasks.
scheduleMicroTask(() => {
if (!ngZone.hasPendingMacrotasks) {
if (this._promise !== null) {
this._resolve!(true);
this._resolve = null;
this._promise = null;
}
}
});
}
} | }
});
});
}
}
private _tick(checkNoChanges: boolean) {
this.changeDetectorRef.detectChanges();
if (checkNoChanges) {
this.checkNoChanges();
}
}
/**
* Trigger a change detection cycle for the component.
*/
detectChanges(checkNoChanges: boolean = true): void {
if (this.ngZone != null) {
// Run the change detection inside the NgZone so that any async tasks as part of the change
// detection are captured by the zone and can be waited for in isStable.
this.ngZone.run(() => {
this._tick(checkNoChanges);
});
} else {
// Running without zone. Just do the change detection.
this._tick(checkNoChanges);
}
}
/**
* Do a change detection run to make sure there were no changes.
*/
checkNoChanges(): void {
this.changeDetectorRef.checkNoChanges();
}
/**
* Set whether the fixture should autodetect changes.
*
* Also runs detectChanges once so that any existing change is detected.
*/
autoDetectChanges(autoDetect: boolean = true) {
if (this.ngZone == null) {
throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set');
}
this._autoDetect = autoDetect;
this.detectChanges();
}
/**
* Return whether the fixture is currently stable or has async tasks that have not been completed
* yet.
*/
isStable(): boolean {
return this._isStable && !this.ngZone!.hasPendingMacrotasks;
}
/**
* Get a promise that resolves when the fixture is stable.
*
* This can be used to resume testing after events have triggered asynchronous activity or
* asynchronous change detection.
*/
whenStable(): Promise<any> {
if (this.isStable()) {
return Promise.resolve(false);
} else if (this._promise !== null) {
return this._promise;
} else {
this._promise = new Promise(res => {
this._resolve = res;
});
return this._promise;
}
}
private _getRenderer() {
if (this._renderer === undefined) {
this._renderer = this.componentRef.injector.get(RendererFactory2, null);
}
return this._renderer as RendererFactory2 | null;
}
/**
* Get a promise that resolves when the ui state is stable following animations.
*/
whenRenderingDone(): Promise<any> {
const renderer = this._getRenderer();
if (renderer && renderer.whenRenderingDone) {
return renderer.whenRenderingDone();
}
return this.whenStable();
}
/**
* Trigger component destruction.
*/
destroy(): void {
if (!this._isDestroyed) {
this.componentRef.destroy();
if (this._onUnstableSubscription != null) {
this._onUnstableSubscription.unsubscribe();
this._onUnstableSubscription = null;
}
if (this._onStableSubscription != null) {
this._onStableSubscription.unsubscribe();
this._onStableSubscription = null;
}
if (this._onMicrotaskEmptySubscription != null) {
this._onMicrotaskEmptySubscription.unsubscribe();
this._onMicrotaskEmptySubscription = null;
}
if (this._onErrorSubscription != null) {
this._onErrorSubscription.unsubscribe();
this._onErrorSubscription = null;
}
this._isDestroyed = true;
}
}
}
function scheduleMicroTask(fn: Function) {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
} | });
this._onErrorSubscription = ngZone.onError.subscribe({
next: (error: any) => {
throw error; | random_line_split |
component_fixture.ts | /**
* @license
* Copyright Google LLC 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 {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, getDebugNode, NgZone, RendererFactory2} from '@angular/core';
/**
* Fixture for debugging and testing a component.
*
* @publicApi
*/
export class ComponentFixture<T> {
/**
* The DebugElement associated with the root element of this component.
*/
debugElement: DebugElement;
/**
* The instance of the root component class.
*/
componentInstance: T;
/**
* The native element at the root of the component.
*/
nativeElement: any;
/**
* The ElementRef for the element at the root of the component.
*/
elementRef: ElementRef;
/**
* The ChangeDetectorRef for the component
*/
changeDetectorRef: ChangeDetectorRef;
private _renderer: RendererFactory2|null|undefined;
private _isStable: boolean = true;
private _isDestroyed: boolean = false;
private _resolve: ((result: any) => void)|null = null;
private _promise: Promise<any>|null = null;
private _onUnstableSubscription: any /** TODO #9100 */ = null;
private _onStableSubscription: any /** TODO #9100 */ = null;
private _onMicrotaskEmptySubscription: any /** TODO #9100 */ = null;
private _onErrorSubscription: any /** TODO #9100 */ = null;
constructor(
public componentRef: ComponentRef<T>, public ngZone: NgZone|null,
private _autoDetect: boolean) {
this.changeDetectorRef = componentRef.changeDetectorRef;
this.elementRef = componentRef.location;
this.debugElement = <DebugElement>getDebugNode(this.elementRef.nativeElement);
this.componentInstance = componentRef.instance;
this.nativeElement = this.elementRef.nativeElement;
this.componentRef = componentRef;
this.ngZone = ngZone;
if (ngZone) {
// Create subscriptions outside the NgZone so that the callbacks run oustide
// of NgZone.
ngZone.runOutsideAngular(() => {
this._onUnstableSubscription = ngZone.onUnstable.subscribe({
next: () => {
this._isStable = false;
}
});
this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
next: () => {
if (this._autoDetect) {
// Do a change detection run with checkNoChanges set to true to check
// there are no changes on the second run.
this.detectChanges(true);
}
}
});
this._onStableSubscription = ngZone.onStable.subscribe({
next: () => {
this._isStable = true;
// Check whether there is a pending whenStable() completer to resolve.
if (this._promise !== null) {
// If so check whether there are no pending macrotasks before resolving.
// Do this check in the next tick so that ngZone gets a chance to update the state of
// pending macrotasks.
scheduleMicroTask(() => {
if (!ngZone.hasPendingMacrotasks) {
if (this._promise !== null) {
this._resolve!(true);
this._resolve = null;
this._promise = null;
}
}
});
}
}
});
this._onErrorSubscription = ngZone.onError.subscribe({
next: (error: any) => {
throw error;
}
});
});
}
}
private _tick(checkNoChanges: boolean) {
this.changeDetectorRef.detectChanges();
if (checkNoChanges) {
this.checkNoChanges();
}
}
/**
* Trigger a change detection cycle for the component.
*/
detectChanges(checkNoChanges: boolean = true): void {
if (this.ngZone != null) {
// Run the change detection inside the NgZone so that any async tasks as part of the change
// detection are captured by the zone and can be waited for in isStable.
this.ngZone.run(() => {
this._tick(checkNoChanges);
});
} else {
// Running without zone. Just do the change detection.
this._tick(checkNoChanges);
}
}
/**
* Do a change detection run to make sure there were no changes.
*/
checkNoChanges(): void {
this.changeDetectorRef.checkNoChanges();
}
/**
* Set whether the fixture should autodetect changes.
*
* Also runs detectChanges once so that any existing change is detected.
*/
autoDetectChanges(autoDetect: boolean = true) {
if (this.ngZone == null) {
throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set');
}
this._autoDetect = autoDetect;
this.detectChanges();
}
/**
* Return whether the fixture is currently stable or has async tasks that have not been completed
* yet.
*/
isStable(): boolean {
return this._isStable && !this.ngZone!.hasPendingMacrotasks;
}
/**
* Get a promise that resolves when the fixture is stable.
*
* This can be used to resume testing after events have triggered asynchronous activity or
* asynchronous change detection.
*/
whenStable(): Promise<any> {
if (this.isStable()) {
return Promise.resolve(false);
} else if (this._promise !== null) {
return this._promise;
} else {
this._promise = new Promise(res => {
this._resolve = res;
});
return this._promise;
}
}
private _getRenderer() {
if (this._renderer === undefined) {
this._renderer = this.componentRef.injector.get(RendererFactory2, null);
}
return this._renderer as RendererFactory2 | null;
}
/**
* Get a promise that resolves when the ui state is stable following animations.
*/
whenRenderingDone(): Promise<any> {
const renderer = this._getRenderer();
if (renderer && renderer.whenRenderingDone) {
return renderer.whenRenderingDone();
}
return this.whenStable();
}
/**
* Trigger component destruction.
*/
destroy(): void {
if (!this._isDestroyed) {
this.componentRef.destroy();
if (this._onUnstableSubscription != null) {
this._onUnstableSubscription.unsubscribe();
this._onUnstableSubscription = null;
}
if (this._onStableSubscription != null) {
this._onStableSubscription.unsubscribe();
this._onStableSubscription = null;
}
if (this._onMicrotaskEmptySubscription != null) {
this._onMicrotaskEmptySubscription.unsubscribe();
this._onMicrotaskEmptySubscription = null;
}
if (this._onErrorSubscription != null) |
this._isDestroyed = true;
}
}
}
function scheduleMicroTask(fn: Function) {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
| {
this._onErrorSubscription.unsubscribe();
this._onErrorSubscription = null;
} | conditional_block |
component_fixture.ts | /**
* @license
* Copyright Google LLC 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 {ChangeDetectorRef, ComponentRef, DebugElement, ElementRef, getDebugNode, NgZone, RendererFactory2} from '@angular/core';
/**
* Fixture for debugging and testing a component.
*
* @publicApi
*/
export class | <T> {
/**
* The DebugElement associated with the root element of this component.
*/
debugElement: DebugElement;
/**
* The instance of the root component class.
*/
componentInstance: T;
/**
* The native element at the root of the component.
*/
nativeElement: any;
/**
* The ElementRef for the element at the root of the component.
*/
elementRef: ElementRef;
/**
* The ChangeDetectorRef for the component
*/
changeDetectorRef: ChangeDetectorRef;
private _renderer: RendererFactory2|null|undefined;
private _isStable: boolean = true;
private _isDestroyed: boolean = false;
private _resolve: ((result: any) => void)|null = null;
private _promise: Promise<any>|null = null;
private _onUnstableSubscription: any /** TODO #9100 */ = null;
private _onStableSubscription: any /** TODO #9100 */ = null;
private _onMicrotaskEmptySubscription: any /** TODO #9100 */ = null;
private _onErrorSubscription: any /** TODO #9100 */ = null;
constructor(
public componentRef: ComponentRef<T>, public ngZone: NgZone|null,
private _autoDetect: boolean) {
this.changeDetectorRef = componentRef.changeDetectorRef;
this.elementRef = componentRef.location;
this.debugElement = <DebugElement>getDebugNode(this.elementRef.nativeElement);
this.componentInstance = componentRef.instance;
this.nativeElement = this.elementRef.nativeElement;
this.componentRef = componentRef;
this.ngZone = ngZone;
if (ngZone) {
// Create subscriptions outside the NgZone so that the callbacks run oustide
// of NgZone.
ngZone.runOutsideAngular(() => {
this._onUnstableSubscription = ngZone.onUnstable.subscribe({
next: () => {
this._isStable = false;
}
});
this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
next: () => {
if (this._autoDetect) {
// Do a change detection run with checkNoChanges set to true to check
// there are no changes on the second run.
this.detectChanges(true);
}
}
});
this._onStableSubscription = ngZone.onStable.subscribe({
next: () => {
this._isStable = true;
// Check whether there is a pending whenStable() completer to resolve.
if (this._promise !== null) {
// If so check whether there are no pending macrotasks before resolving.
// Do this check in the next tick so that ngZone gets a chance to update the state of
// pending macrotasks.
scheduleMicroTask(() => {
if (!ngZone.hasPendingMacrotasks) {
if (this._promise !== null) {
this._resolve!(true);
this._resolve = null;
this._promise = null;
}
}
});
}
}
});
this._onErrorSubscription = ngZone.onError.subscribe({
next: (error: any) => {
throw error;
}
});
});
}
}
private _tick(checkNoChanges: boolean) {
this.changeDetectorRef.detectChanges();
if (checkNoChanges) {
this.checkNoChanges();
}
}
/**
* Trigger a change detection cycle for the component.
*/
detectChanges(checkNoChanges: boolean = true): void {
if (this.ngZone != null) {
// Run the change detection inside the NgZone so that any async tasks as part of the change
// detection are captured by the zone and can be waited for in isStable.
this.ngZone.run(() => {
this._tick(checkNoChanges);
});
} else {
// Running without zone. Just do the change detection.
this._tick(checkNoChanges);
}
}
/**
* Do a change detection run to make sure there were no changes.
*/
checkNoChanges(): void {
this.changeDetectorRef.checkNoChanges();
}
/**
* Set whether the fixture should autodetect changes.
*
* Also runs detectChanges once so that any existing change is detected.
*/
autoDetectChanges(autoDetect: boolean = true) {
if (this.ngZone == null) {
throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set');
}
this._autoDetect = autoDetect;
this.detectChanges();
}
/**
* Return whether the fixture is currently stable or has async tasks that have not been completed
* yet.
*/
isStable(): boolean {
return this._isStable && !this.ngZone!.hasPendingMacrotasks;
}
/**
* Get a promise that resolves when the fixture is stable.
*
* This can be used to resume testing after events have triggered asynchronous activity or
* asynchronous change detection.
*/
whenStable(): Promise<any> {
if (this.isStable()) {
return Promise.resolve(false);
} else if (this._promise !== null) {
return this._promise;
} else {
this._promise = new Promise(res => {
this._resolve = res;
});
return this._promise;
}
}
private _getRenderer() {
if (this._renderer === undefined) {
this._renderer = this.componentRef.injector.get(RendererFactory2, null);
}
return this._renderer as RendererFactory2 | null;
}
/**
* Get a promise that resolves when the ui state is stable following animations.
*/
whenRenderingDone(): Promise<any> {
const renderer = this._getRenderer();
if (renderer && renderer.whenRenderingDone) {
return renderer.whenRenderingDone();
}
return this.whenStable();
}
/**
* Trigger component destruction.
*/
destroy(): void {
if (!this._isDestroyed) {
this.componentRef.destroy();
if (this._onUnstableSubscription != null) {
this._onUnstableSubscription.unsubscribe();
this._onUnstableSubscription = null;
}
if (this._onStableSubscription != null) {
this._onStableSubscription.unsubscribe();
this._onStableSubscription = null;
}
if (this._onMicrotaskEmptySubscription != null) {
this._onMicrotaskEmptySubscription.unsubscribe();
this._onMicrotaskEmptySubscription = null;
}
if (this._onErrorSubscription != null) {
this._onErrorSubscription.unsubscribe();
this._onErrorSubscription = null;
}
this._isDestroyed = true;
}
}
}
function scheduleMicroTask(fn: Function) {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
| ComponentFixture | identifier_name |
local_output_manager_test.py | #! /usr/bin/env vpython3
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=protected-access
import tempfile
import shutil
import unittest
from pylib.base import output_manager
from pylib.base import output_manager_test_case
from pylib.output import local_output_manager
class LocalOutputManagerTest(output_manager_test_case.OutputManagerTestCase):
def setUp(self):
self._output_dir = tempfile.mkdtemp()
self._output_manager = local_output_manager.LocalOutputManager(
self._output_dir)
def | (self):
self.assertUsableTempFile(
self._output_manager._CreateArchivedFile(
'test_file', 'test_subdir', output_manager.Datatype.TEXT))
def tearDown(self):
shutil.rmtree(self._output_dir)
if __name__ == '__main__':
unittest.main()
| testUsableTempFile | identifier_name |
local_output_manager_test.py | #! /usr/bin/env vpython3
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=protected-access
import tempfile
import shutil
import unittest
from pylib.base import output_manager
from pylib.base import output_manager_test_case
from pylib.output import local_output_manager |
def setUp(self):
self._output_dir = tempfile.mkdtemp()
self._output_manager = local_output_manager.LocalOutputManager(
self._output_dir)
def testUsableTempFile(self):
self.assertUsableTempFile(
self._output_manager._CreateArchivedFile(
'test_file', 'test_subdir', output_manager.Datatype.TEXT))
def tearDown(self):
shutil.rmtree(self._output_dir)
if __name__ == '__main__':
unittest.main() |
class LocalOutputManagerTest(output_manager_test_case.OutputManagerTestCase): | random_line_split |
local_output_manager_test.py | #! /usr/bin/env vpython3
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=protected-access
import tempfile
import shutil
import unittest
from pylib.base import output_manager
from pylib.base import output_manager_test_case
from pylib.output import local_output_manager
class LocalOutputManagerTest(output_manager_test_case.OutputManagerTestCase):
def setUp(self):
self._output_dir = tempfile.mkdtemp()
self._output_manager = local_output_manager.LocalOutputManager(
self._output_dir)
def testUsableTempFile(self):
self.assertUsableTempFile(
self._output_manager._CreateArchivedFile(
'test_file', 'test_subdir', output_manager.Datatype.TEXT))
def tearDown(self):
shutil.rmtree(self._output_dir)
if __name__ == '__main__':
| unittest.main() | conditional_block | |
local_output_manager_test.py | #! /usr/bin/env vpython3
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=protected-access
import tempfile
import shutil
import unittest
from pylib.base import output_manager
from pylib.base import output_manager_test_case
from pylib.output import local_output_manager
class LocalOutputManagerTest(output_manager_test_case.OutputManagerTestCase):
def setUp(self):
self._output_dir = tempfile.mkdtemp()
self._output_manager = local_output_manager.LocalOutputManager(
self._output_dir)
def testUsableTempFile(self):
|
def tearDown(self):
shutil.rmtree(self._output_dir)
if __name__ == '__main__':
unittest.main()
| self.assertUsableTempFile(
self._output_manager._CreateArchivedFile(
'test_file', 'test_subdir', output_manager.Datatype.TEXT)) | identifier_body |
tastypie.js | /**
* Backbone-tastypie.js 0.1
* (c) 2011 Paul Uithol
*
* Backbone-tastypie may be freely distributed under the MIT license.
* Add or override Backbone.js functionality, for compatibility with django-tastypie.
*/
(function( undefined ) {
"use strict";
// Backbone.noConflict support. Save local copy of Backbone object.
var Backbone = window.Backbone;
Backbone.Tastypie = {
doGetOnEmptyPostResponse: true,
doGetOnEmptyPutResponse: false,
apiKey: {
username: '',
key: ''
}
};
/**
* Override Backbone's sync function, to do a GET upon receiving a HTTP CREATED.
* This requires 2 requests to do a create, so you may want to use some other method in production.
* Modified from http://joshbohde.com/blog/backbonejs-and-django
*/
Backbone.oldSync = Backbone.sync;
Backbone.sync = function( method, model, options ) {
var headers = '';
if ( Backbone.Tastypie.apiKey && Backbone.Tastypie.apiKey.username.length ) {
headers = _.extend( {
'Authorization': 'ApiKey ' + Backbone.Tastypie.apiKey.username + ':' + Backbone.Tastypie.apiKey.key
}, options.headers );
options.headers = headers;
}
if ( ( method === 'create' && Backbone.Tastypie.doGetOnEmptyPostResponse ) ||
( method === 'update' && Backbone.Tastypie.doGetOnEmptyPutResponse ) ) {
var dfd = new $.Deferred();
// Set up 'success' handling
dfd.done( options.success );
options.success = function( resp, status, xhr ) {
// If create is successful but doesn't return a response, fire an extra GET.
// Otherwise, resolve the deferred (which triggers the original 'success' callbacks).
if ( !resp && ( xhr.status === 201 || xhr.status === 202 || xhr.status === 204 ) ) { // 201 CREATED, 202 ACCEPTED or 204 NO CONTENT; response null or empty.
var location = xhr.getResponseHeader( 'Location' ) || model.id;
return $.ajax( {
url: location,
headers: headers,
success: dfd.resolve,
error: dfd.reject
});
}
else {
return dfd.resolveWith( options.context || options, [ resp, status, xhr ] );
}
};
// Set up 'error' handling
dfd.fail( options.error );
options.error = function( xhr, status, resp ) {
dfd.rejectWith( options.context || options, [ xhr, status, resp ] );
};
// Make the request, make it accessibly by assigning it to the 'request' property on the deferred
dfd.request = Backbone.oldSync( method, model, options );
return dfd;
}
return Backbone.oldSync( method, model, options );
};
Backbone.Model.prototype.idAttribute = 'resource_uri';
Backbone.Model.prototype.url = function() {
// Use the id if possible
var url = this.id;
| url = url || this.collection && ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
if ( url && this.has( 'id' ) ) {
url = addSlash( url ) + this.get( 'id' );
}
}
url = url && addSlash( url );
return url || null;
};
/**
* Return the first entry in 'data.objects' if it exists and is an array, or else just plain 'data'.
*/
Backbone.Model.prototype.parse = function( data ) {
return data && data.objects && ( _.isArray( data.objects ) ? data.objects[ 0 ] : data.objects ) || data;
};
/**
* Return 'data.objects' if it exists.
* If present, the 'data.meta' object is assigned to the 'collection.meta' var.
*/
Backbone.Collection.prototype.parse = function( data ) {
if ( data && data.meta ) {
this.meta = data.meta;
}
return data && data.objects;
};
Backbone.Collection.prototype.url = function( models ) {
var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
url = url && addSlash( url );
// Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
// (set to 'resource_uri') contains the model's id.
if ( models && models.length ) {
var ids = _.map( models, function( model ) {
var parts = _.compact( model.id.split( '/' ) );
return parts[ parts.length - 1 ];
});
url += 'set/' + ids.join( ';' ) + '/';
}
return url || null;
};
var addSlash = function( str ) {
return str + ( ( str.length > 0 && str.charAt( str.length - 1 ) === '/' ) ? '' : '/' );
}
})(); | // If there's no idAttribute, use the 'urlRoot'. Fallback to try to have the collection construct a url.
// Explicitly add the 'id' attribute if the model has one.
if ( !url ) {
url = this.urlRoot; | random_line_split |
tastypie.js | /**
* Backbone-tastypie.js 0.1
* (c) 2011 Paul Uithol
*
* Backbone-tastypie may be freely distributed under the MIT license.
* Add or override Backbone.js functionality, for compatibility with django-tastypie.
*/
(function( undefined ) {
"use strict";
// Backbone.noConflict support. Save local copy of Backbone object.
var Backbone = window.Backbone;
Backbone.Tastypie = {
doGetOnEmptyPostResponse: true,
doGetOnEmptyPutResponse: false,
apiKey: {
username: '',
key: ''
}
};
/**
* Override Backbone's sync function, to do a GET upon receiving a HTTP CREATED.
* This requires 2 requests to do a create, so you may want to use some other method in production.
* Modified from http://joshbohde.com/blog/backbonejs-and-django
*/
Backbone.oldSync = Backbone.sync;
Backbone.sync = function( method, model, options ) {
var headers = '';
if ( Backbone.Tastypie.apiKey && Backbone.Tastypie.apiKey.username.length ) {
headers = _.extend( {
'Authorization': 'ApiKey ' + Backbone.Tastypie.apiKey.username + ':' + Backbone.Tastypie.apiKey.key
}, options.headers );
options.headers = headers;
}
if ( ( method === 'create' && Backbone.Tastypie.doGetOnEmptyPostResponse ) ||
( method === 'update' && Backbone.Tastypie.doGetOnEmptyPutResponse ) ) {
var dfd = new $.Deferred();
// Set up 'success' handling
dfd.done( options.success );
options.success = function( resp, status, xhr ) {
// If create is successful but doesn't return a response, fire an extra GET.
// Otherwise, resolve the deferred (which triggers the original 'success' callbacks).
if ( !resp && ( xhr.status === 201 || xhr.status === 202 || xhr.status === 204 ) ) { // 201 CREATED, 202 ACCEPTED or 204 NO CONTENT; response null or empty.
var location = xhr.getResponseHeader( 'Location' ) || model.id;
return $.ajax( {
url: location,
headers: headers,
success: dfd.resolve,
error: dfd.reject
});
}
else |
};
// Set up 'error' handling
dfd.fail( options.error );
options.error = function( xhr, status, resp ) {
dfd.rejectWith( options.context || options, [ xhr, status, resp ] );
};
// Make the request, make it accessibly by assigning it to the 'request' property on the deferred
dfd.request = Backbone.oldSync( method, model, options );
return dfd;
}
return Backbone.oldSync( method, model, options );
};
Backbone.Model.prototype.idAttribute = 'resource_uri';
Backbone.Model.prototype.url = function() {
// Use the id if possible
var url = this.id;
// If there's no idAttribute, use the 'urlRoot'. Fallback to try to have the collection construct a url.
// Explicitly add the 'id' attribute if the model has one.
if ( !url ) {
url = this.urlRoot;
url = url || this.collection && ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
if ( url && this.has( 'id' ) ) {
url = addSlash( url ) + this.get( 'id' );
}
}
url = url && addSlash( url );
return url || null;
};
/**
* Return the first entry in 'data.objects' if it exists and is an array, or else just plain 'data'.
*/
Backbone.Model.prototype.parse = function( data ) {
return data && data.objects && ( _.isArray( data.objects ) ? data.objects[ 0 ] : data.objects ) || data;
};
/**
* Return 'data.objects' if it exists.
* If present, the 'data.meta' object is assigned to the 'collection.meta' var.
*/
Backbone.Collection.prototype.parse = function( data ) {
if ( data && data.meta ) {
this.meta = data.meta;
}
return data && data.objects;
};
Backbone.Collection.prototype.url = function( models ) {
var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
url = url && addSlash( url );
// Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
// (set to 'resource_uri') contains the model's id.
if ( models && models.length ) {
var ids = _.map( models, function( model ) {
var parts = _.compact( model.id.split( '/' ) );
return parts[ parts.length - 1 ];
});
url += 'set/' + ids.join( ';' ) + '/';
}
return url || null;
};
var addSlash = function( str ) {
return str + ( ( str.length > 0 && str.charAt( str.length - 1 ) === '/' ) ? '' : '/' );
}
})(); | {
return dfd.resolveWith( options.context || options, [ resp, status, xhr ] );
} | conditional_block |
Teams.d.ts | declare class | {
create(obj: any): Promise<Team.OnfleetTeam>;
deleteOne(id: string): Promise<void>;
get(): Promise<Team.OnfleetTeam[]>;
get(id: string): Promise<Team.OnfleetTeam>;
insertTask(id: string, obj: { tasks: string[] }): Promise<Team.OnfleetTeam>;
update(id: string, obj: Team.UpdateTeamProps): Promise<Team.OnfleetTeam>;
}
declare namespace Team {
interface OnfleetTeam {
hub: string;
id: string;
managers: string[];
name: string;
timeCreated: number;
timeLastModified: number;
workers: string[];
}
/**
* @prop managers - An array of managing administrator IDs.
* @prop name - A unique name for the team.
* @prop workers - An array of worker IDs.
* @prop hub - Optional. The ID of the team's hub.
*/
interface CreateTeamProps {
managers: string[];
name: string;
workers: string[];
hub?: string;
}
interface UpdateTeamProps {
managers?: string[];
name?: string;
workers?: string[];
hub?: string;
}
}
export = Team;
| Team | identifier_name |
Teams.d.ts | declare class Team {
create(obj: any): Promise<Team.OnfleetTeam>;
deleteOne(id: string): Promise<void>;
get(): Promise<Team.OnfleetTeam[]>;
get(id: string): Promise<Team.OnfleetTeam>;
insertTask(id: string, obj: { tasks: string[] }): Promise<Team.OnfleetTeam>;
update(id: string, obj: Team.UpdateTeamProps): Promise<Team.OnfleetTeam>;
}
declare namespace Team {
interface OnfleetTeam {
hub: string;
id: string;
managers: string[];
name: string;
timeCreated: number;
timeLastModified: number;
workers: string[];
}
/**
* @prop managers - An array of managing administrator IDs.
* @prop name - A unique name for the team.
* @prop workers - An array of worker IDs. | interface CreateTeamProps {
managers: string[];
name: string;
workers: string[];
hub?: string;
}
interface UpdateTeamProps {
managers?: string[];
name?: string;
workers?: string[];
hub?: string;
}
}
export = Team; | * @prop hub - Optional. The ID of the team's hub.
*/ | random_line_split |
commands.py |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import superdesk
import urllib3
import urllib
import xml.etree.ElementTree as etree
from superdesk.io.iptc import subject_codes
from datetime import datetime
from superdesk.metadata.item import ITEM_TYPE, CONTENT_TYPE, ITEM_STATE, CONTENT_STATE
from superdesk.utc import utc
from superdesk.io.commands.update_ingest import process_iptc_codes
from superdesk.etree import get_text_word_count
# The older content does not contain an anpa category, so we derive it from the
# publication name
pubnames = {
'International Sport': 'S',
'Racing': 'R',
'Parliamentary Press Releases': 'P',
'Features': 'C',
'Financial News': 'F',
'General': 'A',
'aap Features': 'C',
'aap International News': 'I',
'aap Australian Sport': 'S',
'Australian General News': 'A',
'Asia Pulse Full': 'I',
'AFR Summary': 'A',
'Australian Sport': 'T',
'PR Releases': 'J',
'Entertainment News': 'E',
'Special Events': 'Y',
'Asia Pulse': 'I',
'aap International Sport': 'S',
'Emergency Services': 'A',
'BRW Summary': 'A',
'FBM Summary': 'A',
'aap Australian General News': 'A',
'International News': 'I',
'aap Financial News': 'F',
'Asia Pulse Basic': 'I',
'Political News': 'P',
'Advisories': 'V'
}
class AppImportTextArchiveCommand(superdesk.Command):
option_list = (
superdesk.Option('--start', '-strt', dest='start_id', required=False),
superdesk.Option('--user', '-usr', dest='user', required=True),
superdesk.Option('--password', '-pwd', dest='password', required=True),
superdesk.Option('--url_root', '-url', dest='url', required=True),
superdesk.Option('--query', '-qry', dest='query', required=True),
superdesk.Option('--count', '-c', dest='limit', required=False)
)
def | (self, start_id, user, password, url, query, limit):
print('Starting text archive import at {}'.format(start_id))
self._user = user
self._password = password
self._id = int(start_id)
self._url_root = url
self._query = urllib.parse.quote(query)
if limit is not None:
self._limit = int(limit)
else:
self._limit = None
self._api_login()
x = self._get_bunch(self._id)
while x:
self._process_bunch(x)
x = self._get_bunch(self._id)
if self._limit is not None and self._limit <= 0:
break
print('finished text archive import')
def _api_login(self):
self._http = urllib3.PoolManager()
credentials = '?login[username]={}&login[password]={}'.format(self._user, self._password)
url = self._url_root + credentials
r = self._http.urlopen('GET', url, headers={'Content-Type': 'application/xml'})
self._headers = {'cookie': r.getheader('set-cookie')}
self._anpa_categories = superdesk.get_resource_service('vocabularies').find_one(req=None, _id='categories')
def _get_bunch(self, id):
url = self._url_root + \
'archives/txtarch?search_docs[struct_query]=(DCDATA_ID<{0})&search_docs[query]='.format(id)
url += self._query
url += '&search_docs[format]=full&search_docs[pagesize]=500&search_docs[page]=1'
url += '&search_docs[sortorder]=DCDATA_ID%20DESC'
print(url)
retries = 3
while retries > 0:
r = self._http.request('GET', url, headers=self._headers)
if r.status == 200:
e = etree.fromstring(r.data)
# print(str(r.data))
count = int(e.find('doc_count').text)
if count > 0:
print('count : {}'.format(count))
return e
else:
self._api_login()
retries -= 1
return None
def _get_head_value(self, doc, field):
el = doc.find('dcdossier/document/head/' + field)
if el is not None:
return el.text
return None
def _addkeywords(self, key, doc, item):
code = self._get_head_value(doc, key)
if code:
if 'keywords' not in item:
item['keywords'] = []
item['keywords'].append(code)
def _process_bunch(self, x):
# x.findall('dc_rest_docs/dc_rest_doc')[0].get('href')
for doc in x.findall('dc_rest_docs/dc_rest_doc'):
print(doc.get('href'))
id = doc.find('dcdossier').get('id')
if int(id) < self._id:
self._id = int(id)
item = {}
item['guid'] = doc.find('dcdossier').get('guid')
# if the item has been modified in the archive then it is due to a kill
# there is an argument that this item should not be imported at all
if doc.find('dcdossier').get('created') != doc.find('dcdossier').get('modified'):
item[ITEM_STATE] = CONTENT_STATE.KILLED
else:
item[ITEM_STATE] = CONTENT_STATE.PUBLISHED
value = datetime.strptime(self._get_head_value(doc, 'PublicationDate'), '%Y%m%d%H%M%S')
item['firstcreated'] = utc.normalize(value) if value.tzinfo else value
item['versioncreated'] = item['firstcreated']
item['unique_id'] = doc.find('dcdossier').get('unique')
item['ingest_id'] = id
item['source'] = self._get_head_value(doc, 'Agency')
self._addkeywords('AsiaPulseCodes', doc, item)
byline = self._get_head_value(doc, 'Byline')
if byline:
item['byline'] = byline
# item['service'] = self._get_head_value(doc,'Service')
category = self._get_head_value(doc, 'Category')
if not category:
publication_name = self._get_head_value(doc, 'PublicationName')
if publication_name in pubnames:
category = pubnames[publication_name]
if category:
anpacategory = {}
anpacategory['qcode'] = category
for anpa_category in self._anpa_categories['items']:
if anpacategory['qcode'].lower() == anpa_category['qcode'].lower():
anpacategory = {'qcode': anpacategory['qcode'], 'name': anpa_category['name']}
break
item['anpa_category'] = [anpacategory]
self._addkeywords('CompanyCodes', doc, item)
type = self._get_head_value(doc, 'Format')
if type == 'x':
item[ITEM_TYPE] = CONTENT_TYPE.TEXT
elif type == 't':
item[ITEM_TYPE] = CONTENT_TYPE.PREFORMATTED
else:
item[ITEM_TYPE] = CONTENT_TYPE.TEXT
item['keyword'] = self._get_head_value(doc, 'Keyword')
item['ingest_provider_sequence'] = self._get_head_value(doc, 'Sequence')
orginal_source = self._get_head_value(doc, 'Author')
if orginal_source:
item['original_source'] = orginal_source
item['headline'] = self._get_head_value(doc, 'Headline')
code = self._get_head_value(doc, 'SubjectRefNum')
if code and len(code) == 7:
code = '0' + code
if code and code in subject_codes:
item['subject'] = []
item['subject'].append({'qcode': code, 'name': subject_codes[code]})
try:
process_iptc_codes(item, None)
except:
pass
slug = self._get_head_value(doc, 'SLUG')
if slug:
item['slugline'] = slug
else:
item['slugline'] = self._get_head_value(doc, 'Keyword')
# self._addkeywords('Takekey', doc, item)
take_key = self._get_head_value(doc, 'Takekey')
if take_key:
item['anpa_take_key'] = take_key
self._addkeywords('Topic', doc, item)
self._addkeywords('Selectors', doc, item)
el = doc.find('dcdossier/document/body/BodyText')
if el is not None:
story = el.text
if item[ITEM_TYPE] == CONTENT_TYPE.TEXT:
story = story.replace('\n ', '<br><br>')
story = story.replace('\n', '<br>')
item['body_html'] = story
else:
item['body_html'] = story
try:
item['word_count'] = get_text_word_count(item['body_html'])
except:
pass
item['pubstatus'] = 'usable'
item['allow_post_publish_actions'] = False
res = superdesk.get_resource_service('published')
original = res.find_one(req=None, guid=item['guid'])
if not original:
res.post([item])
else:
res.patch(original['_id'], item)
if self._limit:
self._limit -= 1
# print(item)
superdesk.command('app:import_text_archive', AppImportTextArchiveCommand())
| run | identifier_name |
commands.py |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import superdesk
import urllib3
import urllib
import xml.etree.ElementTree as etree
from superdesk.io.iptc import subject_codes
from datetime import datetime
from superdesk.metadata.item import ITEM_TYPE, CONTENT_TYPE, ITEM_STATE, CONTENT_STATE
from superdesk.utc import utc
from superdesk.io.commands.update_ingest import process_iptc_codes
from superdesk.etree import get_text_word_count
# The older content does not contain an anpa category, so we derive it from the
# publication name
pubnames = {
'International Sport': 'S',
'Racing': 'R',
'Parliamentary Press Releases': 'P',
'Features': 'C',
'Financial News': 'F',
'General': 'A',
'aap Features': 'C',
'aap International News': 'I',
'aap Australian Sport': 'S',
'Australian General News': 'A',
'Asia Pulse Full': 'I',
'AFR Summary': 'A',
'Australian Sport': 'T',
'PR Releases': 'J',
'Entertainment News': 'E',
'Special Events': 'Y',
'Asia Pulse': 'I',
'aap International Sport': 'S',
'Emergency Services': 'A',
'BRW Summary': 'A',
'FBM Summary': 'A',
'aap Australian General News': 'A',
'International News': 'I',
'aap Financial News': 'F',
'Asia Pulse Basic': 'I',
'Political News': 'P',
'Advisories': 'V'
}
class AppImportTextArchiveCommand(superdesk.Command):
option_list = (
superdesk.Option('--start', '-strt', dest='start_id', required=False),
superdesk.Option('--user', '-usr', dest='user', required=True),
superdesk.Option('--password', '-pwd', dest='password', required=True),
superdesk.Option('--url_root', '-url', dest='url', required=True),
superdesk.Option('--query', '-qry', dest='query', required=True),
superdesk.Option('--count', '-c', dest='limit', required=False)
)
def run(self, start_id, user, password, url, query, limit):
print('Starting text archive import at {}'.format(start_id))
self._user = user
self._password = password
self._id = int(start_id)
self._url_root = url
self._query = urllib.parse.quote(query)
if limit is not None:
self._limit = int(limit)
else:
self._limit = None
self._api_login()
x = self._get_bunch(self._id)
while x:
self._process_bunch(x)
x = self._get_bunch(self._id)
if self._limit is not None and self._limit <= 0:
break
print('finished text archive import')
def _api_login(self):
self._http = urllib3.PoolManager()
credentials = '?login[username]={}&login[password]={}'.format(self._user, self._password)
url = self._url_root + credentials
r = self._http.urlopen('GET', url, headers={'Content-Type': 'application/xml'})
self._headers = {'cookie': r.getheader('set-cookie')}
self._anpa_categories = superdesk.get_resource_service('vocabularies').find_one(req=None, _id='categories')
def _get_bunch(self, id):
url = self._url_root + \
'archives/txtarch?search_docs[struct_query]=(DCDATA_ID<{0})&search_docs[query]='.format(id)
url += self._query
url += '&search_docs[format]=full&search_docs[pagesize]=500&search_docs[page]=1'
url += '&search_docs[sortorder]=DCDATA_ID%20DESC'
print(url)
retries = 3
while retries > 0:
r = self._http.request('GET', url, headers=self._headers)
if r.status == 200:
e = etree.fromstring(r.data)
# print(str(r.data))
count = int(e.find('doc_count').text)
if count > 0:
print('count : {}'.format(count))
return e
else:
self._api_login()
retries -= 1
return None
def _get_head_value(self, doc, field):
|
def _addkeywords(self, key, doc, item):
code = self._get_head_value(doc, key)
if code:
if 'keywords' not in item:
item['keywords'] = []
item['keywords'].append(code)
def _process_bunch(self, x):
# x.findall('dc_rest_docs/dc_rest_doc')[0].get('href')
for doc in x.findall('dc_rest_docs/dc_rest_doc'):
print(doc.get('href'))
id = doc.find('dcdossier').get('id')
if int(id) < self._id:
self._id = int(id)
item = {}
item['guid'] = doc.find('dcdossier').get('guid')
# if the item has been modified in the archive then it is due to a kill
# there is an argument that this item should not be imported at all
if doc.find('dcdossier').get('created') != doc.find('dcdossier').get('modified'):
item[ITEM_STATE] = CONTENT_STATE.KILLED
else:
item[ITEM_STATE] = CONTENT_STATE.PUBLISHED
value = datetime.strptime(self._get_head_value(doc, 'PublicationDate'), '%Y%m%d%H%M%S')
item['firstcreated'] = utc.normalize(value) if value.tzinfo else value
item['versioncreated'] = item['firstcreated']
item['unique_id'] = doc.find('dcdossier').get('unique')
item['ingest_id'] = id
item['source'] = self._get_head_value(doc, 'Agency')
self._addkeywords('AsiaPulseCodes', doc, item)
byline = self._get_head_value(doc, 'Byline')
if byline:
item['byline'] = byline
# item['service'] = self._get_head_value(doc,'Service')
category = self._get_head_value(doc, 'Category')
if not category:
publication_name = self._get_head_value(doc, 'PublicationName')
if publication_name in pubnames:
category = pubnames[publication_name]
if category:
anpacategory = {}
anpacategory['qcode'] = category
for anpa_category in self._anpa_categories['items']:
if anpacategory['qcode'].lower() == anpa_category['qcode'].lower():
anpacategory = {'qcode': anpacategory['qcode'], 'name': anpa_category['name']}
break
item['anpa_category'] = [anpacategory]
self._addkeywords('CompanyCodes', doc, item)
type = self._get_head_value(doc, 'Format')
if type == 'x':
item[ITEM_TYPE] = CONTENT_TYPE.TEXT
elif type == 't':
item[ITEM_TYPE] = CONTENT_TYPE.PREFORMATTED
else:
item[ITEM_TYPE] = CONTENT_TYPE.TEXT
item['keyword'] = self._get_head_value(doc, 'Keyword')
item['ingest_provider_sequence'] = self._get_head_value(doc, 'Sequence')
orginal_source = self._get_head_value(doc, 'Author')
if orginal_source:
item['original_source'] = orginal_source
item['headline'] = self._get_head_value(doc, 'Headline')
code = self._get_head_value(doc, 'SubjectRefNum')
if code and len(code) == 7:
code = '0' + code
if code and code in subject_codes:
item['subject'] = []
item['subject'].append({'qcode': code, 'name': subject_codes[code]})
try:
process_iptc_codes(item, None)
except:
pass
slug = self._get_head_value(doc, 'SLUG')
if slug:
item['slugline'] = slug
else:
item['slugline'] = self._get_head_value(doc, 'Keyword')
# self._addkeywords('Takekey', doc, item)
take_key = self._get_head_value(doc, 'Takekey')
if take_key:
item['anpa_take_key'] = take_key
self._addkeywords('Topic', doc, item)
self._addkeywords('Selectors', doc, item)
el = doc.find('dcdossier/document/body/BodyText')
if el is not None:
story = el.text
if item[ITEM_TYPE] == CONTENT_TYPE.TEXT:
story = story.replace('\n ', '<br><br>')
story = story.replace('\n', '<br>')
item['body_html'] = story
else:
item['body_html'] = story
try:
item['word_count'] = get_text_word_count(item['body_html'])
except:
pass
item['pubstatus'] = 'usable'
item['allow_post_publish_actions'] = False
res = superdesk.get_resource_service('published')
original = res.find_one(req=None, guid=item['guid'])
if not original:
res.post([item])
else:
res.patch(original['_id'], item)
if self._limit:
self._limit -= 1
# print(item)
superdesk.command('app:import_text_archive', AppImportTextArchiveCommand())
| el = doc.find('dcdossier/document/head/' + field)
if el is not None:
return el.text
return None | identifier_body |
commands.py |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import superdesk
import urllib3
import urllib
import xml.etree.ElementTree as etree
from superdesk.io.iptc import subject_codes
from datetime import datetime
from superdesk.metadata.item import ITEM_TYPE, CONTENT_TYPE, ITEM_STATE, CONTENT_STATE
from superdesk.utc import utc
from superdesk.io.commands.update_ingest import process_iptc_codes
from superdesk.etree import get_text_word_count
# The older content does not contain an anpa category, so we derive it from the
# publication name
pubnames = {
'International Sport': 'S',
'Racing': 'R',
'Parliamentary Press Releases': 'P',
'Features': 'C',
'Financial News': 'F',
'General': 'A',
'aap Features': 'C',
'aap International News': 'I',
'aap Australian Sport': 'S',
'Australian General News': 'A',
'Asia Pulse Full': 'I',
'AFR Summary': 'A',
'Australian Sport': 'T',
'PR Releases': 'J',
'Entertainment News': 'E',
'Special Events': 'Y',
'Asia Pulse': 'I',
'aap International Sport': 'S',
'Emergency Services': 'A',
'BRW Summary': 'A',
'FBM Summary': 'A',
'aap Australian General News': 'A',
'International News': 'I',
'aap Financial News': 'F',
'Asia Pulse Basic': 'I',
'Political News': 'P',
'Advisories': 'V'
}
class AppImportTextArchiveCommand(superdesk.Command):
option_list = (
superdesk.Option('--start', '-strt', dest='start_id', required=False),
superdesk.Option('--user', '-usr', dest='user', required=True),
superdesk.Option('--password', '-pwd', dest='password', required=True),
superdesk.Option('--url_root', '-url', dest='url', required=True),
superdesk.Option('--query', '-qry', dest='query', required=True),
superdesk.Option('--count', '-c', dest='limit', required=False)
)
def run(self, start_id, user, password, url, query, limit):
print('Starting text archive import at {}'.format(start_id))
self._user = user
self._password = password
self._id = int(start_id)
self._url_root = url
self._query = urllib.parse.quote(query)
if limit is not None:
self._limit = int(limit)
else:
self._limit = None
self._api_login()
x = self._get_bunch(self._id)
while x:
self._process_bunch(x)
x = self._get_bunch(self._id)
if self._limit is not None and self._limit <= 0:
break
print('finished text archive import')
def _api_login(self):
self._http = urllib3.PoolManager()
credentials = '?login[username]={}&login[password]={}'.format(self._user, self._password)
url = self._url_root + credentials
r = self._http.urlopen('GET', url, headers={'Content-Type': 'application/xml'})
self._headers = {'cookie': r.getheader('set-cookie')}
self._anpa_categories = superdesk.get_resource_service('vocabularies').find_one(req=None, _id='categories')
def _get_bunch(self, id):
url = self._url_root + \
'archives/txtarch?search_docs[struct_query]=(DCDATA_ID<{0})&search_docs[query]='.format(id)
url += self._query
url += '&search_docs[format]=full&search_docs[pagesize]=500&search_docs[page]=1'
url += '&search_docs[sortorder]=DCDATA_ID%20DESC'
print(url)
retries = 3
while retries > 0:
r = self._http.request('GET', url, headers=self._headers)
if r.status == 200:
e = etree.fromstring(r.data)
# print(str(r.data))
count = int(e.find('doc_count').text)
if count > 0:
print('count : {}'.format(count))
return e
else:
self._api_login()
retries -= 1
return None
def _get_head_value(self, doc, field):
el = doc.find('dcdossier/document/head/' + field)
if el is not None:
return el.text
return None
def _addkeywords(self, key, doc, item):
code = self._get_head_value(doc, key)
if code:
if 'keywords' not in item:
item['keywords'] = []
item['keywords'].append(code)
def _process_bunch(self, x):
# x.findall('dc_rest_docs/dc_rest_doc')[0].get('href')
for doc in x.findall('dc_rest_docs/dc_rest_doc'):
print(doc.get('href'))
id = doc.find('dcdossier').get('id')
if int(id) < self._id:
|
item = {}
item['guid'] = doc.find('dcdossier').get('guid')
# if the item has been modified in the archive then it is due to a kill
# there is an argument that this item should not be imported at all
if doc.find('dcdossier').get('created') != doc.find('dcdossier').get('modified'):
item[ITEM_STATE] = CONTENT_STATE.KILLED
else:
item[ITEM_STATE] = CONTENT_STATE.PUBLISHED
value = datetime.strptime(self._get_head_value(doc, 'PublicationDate'), '%Y%m%d%H%M%S')
item['firstcreated'] = utc.normalize(value) if value.tzinfo else value
item['versioncreated'] = item['firstcreated']
item['unique_id'] = doc.find('dcdossier').get('unique')
item['ingest_id'] = id
item['source'] = self._get_head_value(doc, 'Agency')
self._addkeywords('AsiaPulseCodes', doc, item)
byline = self._get_head_value(doc, 'Byline')
if byline:
item['byline'] = byline
# item['service'] = self._get_head_value(doc,'Service')
category = self._get_head_value(doc, 'Category')
if not category:
publication_name = self._get_head_value(doc, 'PublicationName')
if publication_name in pubnames:
category = pubnames[publication_name]
if category:
anpacategory = {}
anpacategory['qcode'] = category
for anpa_category in self._anpa_categories['items']:
if anpacategory['qcode'].lower() == anpa_category['qcode'].lower():
anpacategory = {'qcode': anpacategory['qcode'], 'name': anpa_category['name']}
break
item['anpa_category'] = [anpacategory]
self._addkeywords('CompanyCodes', doc, item)
type = self._get_head_value(doc, 'Format')
if type == 'x':
item[ITEM_TYPE] = CONTENT_TYPE.TEXT
elif type == 't':
item[ITEM_TYPE] = CONTENT_TYPE.PREFORMATTED
else:
item[ITEM_TYPE] = CONTENT_TYPE.TEXT
item['keyword'] = self._get_head_value(doc, 'Keyword')
item['ingest_provider_sequence'] = self._get_head_value(doc, 'Sequence')
orginal_source = self._get_head_value(doc, 'Author')
if orginal_source:
item['original_source'] = orginal_source
item['headline'] = self._get_head_value(doc, 'Headline')
code = self._get_head_value(doc, 'SubjectRefNum')
if code and len(code) == 7:
code = '0' + code
if code and code in subject_codes:
item['subject'] = []
item['subject'].append({'qcode': code, 'name': subject_codes[code]})
try:
process_iptc_codes(item, None)
except:
pass
slug = self._get_head_value(doc, 'SLUG')
if slug:
item['slugline'] = slug
else:
item['slugline'] = self._get_head_value(doc, 'Keyword')
# self._addkeywords('Takekey', doc, item)
take_key = self._get_head_value(doc, 'Takekey')
if take_key:
item['anpa_take_key'] = take_key
self._addkeywords('Topic', doc, item)
self._addkeywords('Selectors', doc, item)
el = doc.find('dcdossier/document/body/BodyText')
if el is not None:
story = el.text
if item[ITEM_TYPE] == CONTENT_TYPE.TEXT:
story = story.replace('\n ', '<br><br>')
story = story.replace('\n', '<br>')
item['body_html'] = story
else:
item['body_html'] = story
try:
item['word_count'] = get_text_word_count(item['body_html'])
except:
pass
item['pubstatus'] = 'usable'
item['allow_post_publish_actions'] = False
res = superdesk.get_resource_service('published')
original = res.find_one(req=None, guid=item['guid'])
if not original:
res.post([item])
else:
res.patch(original['_id'], item)
if self._limit:
self._limit -= 1
# print(item)
superdesk.command('app:import_text_archive', AppImportTextArchiveCommand())
| self._id = int(id) | conditional_block |
commands.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import superdesk
import urllib3
import urllib
import xml.etree.ElementTree as etree
from superdesk.io.iptc import subject_codes
from datetime import datetime
from superdesk.metadata.item import ITEM_TYPE, CONTENT_TYPE, ITEM_STATE, CONTENT_STATE
from superdesk.utc import utc
from superdesk.io.commands.update_ingest import process_iptc_codes
from superdesk.etree import get_text_word_count
# The older content does not contain an anpa category, so we derive it from the
# publication name
pubnames = {
'International Sport': 'S',
'Racing': 'R',
'Parliamentary Press Releases': 'P',
'Features': 'C',
'Financial News': 'F',
'General': 'A',
'aap Features': 'C',
'aap International News': 'I',
'aap Australian Sport': 'S',
'Australian General News': 'A',
'Asia Pulse Full': 'I',
'AFR Summary': 'A',
'Australian Sport': 'T',
'PR Releases': 'J',
'Entertainment News': 'E',
'Special Events': 'Y',
'Asia Pulse': 'I',
'aap International Sport': 'S',
'Emergency Services': 'A',
'BRW Summary': 'A',
'FBM Summary': 'A',
'aap Australian General News': 'A',
'International News': 'I',
'aap Financial News': 'F',
'Asia Pulse Basic': 'I',
'Political News': 'P',
'Advisories': 'V'
}
class AppImportTextArchiveCommand(superdesk.Command):
option_list = (
superdesk.Option('--start', '-strt', dest='start_id', required=False),
superdesk.Option('--user', '-usr', dest='user', required=True),
superdesk.Option('--password', '-pwd', dest='password', required=True),
superdesk.Option('--url_root', '-url', dest='url', required=True),
superdesk.Option('--query', '-qry', dest='query', required=True),
superdesk.Option('--count', '-c', dest='limit', required=False)
)
def run(self, start_id, user, password, url, query, limit):
print('Starting text archive import at {}'.format(start_id))
self._user = user
self._password = password
self._id = int(start_id)
self._url_root = url
self._query = urllib.parse.quote(query)
if limit is not None:
self._limit = int(limit)
else:
self._limit = None
self._api_login()
x = self._get_bunch(self._id)
while x:
self._process_bunch(x)
x = self._get_bunch(self._id)
if self._limit is not None and self._limit <= 0:
break
print('finished text archive import')
def _api_login(self):
self._http = urllib3.PoolManager()
credentials = '?login[username]={}&login[password]={}'.format(self._user, self._password)
url = self._url_root + credentials
r = self._http.urlopen('GET', url, headers={'Content-Type': 'application/xml'})
self._headers = {'cookie': r.getheader('set-cookie')}
self._anpa_categories = superdesk.get_resource_service('vocabularies').find_one(req=None, _id='categories')
def _get_bunch(self, id):
url = self._url_root + \
'archives/txtarch?search_docs[struct_query]=(DCDATA_ID<{0})&search_docs[query]='.format(id)
url += self._query
url += '&search_docs[format]=full&search_docs[pagesize]=500&search_docs[page]=1'
url += '&search_docs[sortorder]=DCDATA_ID%20DESC'
print(url)
retries = 3
while retries > 0:
r = self._http.request('GET', url, headers=self._headers)
if r.status == 200:
e = etree.fromstring(r.data)
# print(str(r.data))
count = int(e.find('doc_count').text) | retries -= 1
return None
def _get_head_value(self, doc, field):
el = doc.find('dcdossier/document/head/' + field)
if el is not None:
return el.text
return None
def _addkeywords(self, key, doc, item):
code = self._get_head_value(doc, key)
if code:
if 'keywords' not in item:
item['keywords'] = []
item['keywords'].append(code)
def _process_bunch(self, x):
# x.findall('dc_rest_docs/dc_rest_doc')[0].get('href')
for doc in x.findall('dc_rest_docs/dc_rest_doc'):
print(doc.get('href'))
id = doc.find('dcdossier').get('id')
if int(id) < self._id:
self._id = int(id)
item = {}
item['guid'] = doc.find('dcdossier').get('guid')
# if the item has been modified in the archive then it is due to a kill
# there is an argument that this item should not be imported at all
if doc.find('dcdossier').get('created') != doc.find('dcdossier').get('modified'):
item[ITEM_STATE] = CONTENT_STATE.KILLED
else:
item[ITEM_STATE] = CONTENT_STATE.PUBLISHED
value = datetime.strptime(self._get_head_value(doc, 'PublicationDate'), '%Y%m%d%H%M%S')
item['firstcreated'] = utc.normalize(value) if value.tzinfo else value
item['versioncreated'] = item['firstcreated']
item['unique_id'] = doc.find('dcdossier').get('unique')
item['ingest_id'] = id
item['source'] = self._get_head_value(doc, 'Agency')
self._addkeywords('AsiaPulseCodes', doc, item)
byline = self._get_head_value(doc, 'Byline')
if byline:
item['byline'] = byline
# item['service'] = self._get_head_value(doc,'Service')
category = self._get_head_value(doc, 'Category')
if not category:
publication_name = self._get_head_value(doc, 'PublicationName')
if publication_name in pubnames:
category = pubnames[publication_name]
if category:
anpacategory = {}
anpacategory['qcode'] = category
for anpa_category in self._anpa_categories['items']:
if anpacategory['qcode'].lower() == anpa_category['qcode'].lower():
anpacategory = {'qcode': anpacategory['qcode'], 'name': anpa_category['name']}
break
item['anpa_category'] = [anpacategory]
self._addkeywords('CompanyCodes', doc, item)
type = self._get_head_value(doc, 'Format')
if type == 'x':
item[ITEM_TYPE] = CONTENT_TYPE.TEXT
elif type == 't':
item[ITEM_TYPE] = CONTENT_TYPE.PREFORMATTED
else:
item[ITEM_TYPE] = CONTENT_TYPE.TEXT
item['keyword'] = self._get_head_value(doc, 'Keyword')
item['ingest_provider_sequence'] = self._get_head_value(doc, 'Sequence')
orginal_source = self._get_head_value(doc, 'Author')
if orginal_source:
item['original_source'] = orginal_source
item['headline'] = self._get_head_value(doc, 'Headline')
code = self._get_head_value(doc, 'SubjectRefNum')
if code and len(code) == 7:
code = '0' + code
if code and code in subject_codes:
item['subject'] = []
item['subject'].append({'qcode': code, 'name': subject_codes[code]})
try:
process_iptc_codes(item, None)
except:
pass
slug = self._get_head_value(doc, 'SLUG')
if slug:
item['slugline'] = slug
else:
item['slugline'] = self._get_head_value(doc, 'Keyword')
# self._addkeywords('Takekey', doc, item)
take_key = self._get_head_value(doc, 'Takekey')
if take_key:
item['anpa_take_key'] = take_key
self._addkeywords('Topic', doc, item)
self._addkeywords('Selectors', doc, item)
el = doc.find('dcdossier/document/body/BodyText')
if el is not None:
story = el.text
if item[ITEM_TYPE] == CONTENT_TYPE.TEXT:
story = story.replace('\n ', '<br><br>')
story = story.replace('\n', '<br>')
item['body_html'] = story
else:
item['body_html'] = story
try:
item['word_count'] = get_text_word_count(item['body_html'])
except:
pass
item['pubstatus'] = 'usable'
item['allow_post_publish_actions'] = False
res = superdesk.get_resource_service('published')
original = res.find_one(req=None, guid=item['guid'])
if not original:
res.post([item])
else:
res.patch(original['_id'], item)
if self._limit:
self._limit -= 1
# print(item)
superdesk.command('app:import_text_archive', AppImportTextArchiveCommand()) | if count > 0:
print('count : {}'.format(count))
return e
else:
self._api_login() | random_line_split |
strainreview-component.ts | import {Component, OnInit, ViewChild} from "@angular/core";
import {StrainReviewService} from "../services/strainreview-service";
import {StrainService} from "../services/strain-service";
import {StrainReview} from "../classes/strainReview";
import {Strain} from "../classes/strain";
import {Router} from "@angular/router";
import {Status} from "../classes/status";
@Component({
templateUrl: "./templates/strain.php"
})
export class StrainReviewComponent implements OnInit {
@ViewChild("strainReviewForm") strainReviewForm : any;
strainReviews: StrainReview[] = [];
strainReview: StrainReview = new StrainReview (null, "","",null,"");
strains: Strain[] = [];
status: Status = null;
constructor(
private strainReviewService: StrainReviewService,
private strainService: StrainService,
private router: Router
) {}
ngOnInit() : void {
this.reloadStrainReviews();
}
| () : void {
this.strainReviewService.getAllStrainReviews()
.subscribe(strainReviews => {
this.strainReviews = strainReviews;
this.strainService.getStrainByStrainId(this.strainReview.strainReviewId)
.subscribe(strains => this.strains=strains);
});
}
}
//Written by Nathan Sanchez @nsanchez121@cnm.edu | reloadStrainReviews | identifier_name |
strainreview-component.ts | import {Component, OnInit, ViewChild} from "@angular/core";
import {StrainReviewService} from "../services/strainreview-service";
import {StrainService} from "../services/strain-service";
import {StrainReview} from "../classes/strainReview";
import {Strain} from "../classes/strain";
import {Router} from "@angular/router";
import {Status} from "../classes/status";
@Component({
templateUrl: "./templates/strain.php"
})
export class StrainReviewComponent implements OnInit {
@ViewChild("strainReviewForm") strainReviewForm : any;
strainReviews: StrainReview[] = [];
strainReview: StrainReview = new StrainReview (null, "","",null,"");
strains: Strain[] = [];
status: Status = null;
constructor(
private strainReviewService: StrainReviewService,
private strainService: StrainService,
private router: Router
) {}
ngOnInit() : void {
this.reloadStrainReviews();
}
reloadStrainReviews() : void |
}
//Written by Nathan Sanchez @nsanchez121@cnm.edu | {
this.strainReviewService.getAllStrainReviews()
.subscribe(strainReviews => {
this.strainReviews = strainReviews;
this.strainService.getStrainByStrainId(this.strainReview.strainReviewId)
.subscribe(strains => this.strains=strains);
});
} | identifier_body |
strainreview-component.ts | import {Component, OnInit, ViewChild} from "@angular/core";
import {StrainReviewService} from "../services/strainreview-service";
import {StrainService} from "../services/strain-service";
import {StrainReview} from "../classes/strainReview";
import {Strain} from "../classes/strain";
import {Router} from "@angular/router";
import {Status} from "../classes/status";
@Component({
templateUrl: "./templates/strain.php"
})
export class StrainReviewComponent implements OnInit {
@ViewChild("strainReviewForm") strainReviewForm : any;
strainReviews: StrainReview[] = [];
strainReview: StrainReview = new StrainReview (null, "","",null,"");
strains: Strain[] = [];
status: Status = null;
constructor(
private strainReviewService: StrainReviewService,
private strainService: StrainService,
private router: Router
) {}
ngOnInit() : void {
this.reloadStrainReviews();
}
reloadStrainReviews() : void { | });
}
}
//Written by Nathan Sanchez @nsanchez121@cnm.edu | this.strainReviewService.getAllStrainReviews()
.subscribe(strainReviews => {
this.strainReviews = strainReviews;
this.strainService.getStrainByStrainId(this.strainReview.strainReviewId)
.subscribe(strains => this.strains=strains); | random_line_split |
mod-ent-install.js | var log = new Log();
var mod = require('store');
var user = mod.user;
var server = require('store').server;
var currentUser = server.current(session);
var SUBSCRIPTIONS_PATH = '/subscriptions/mobileapp/';
var mobileGeneric = new Packages.org.wso2.carbon.appmgt.mobile.store.Generic();
var mdmConfig = parse(String((new Packages.org.wso2.carbon.appmgt.mobile.store.MDMConfig()).getConfigs()));
var isMDMOperationsEnabled = mdmConfig.EnableMDMOperations == "true" ? true : false;
var isDirectDownloadEnabled = mdmConfig.EnableDirectDownload == "true" ? true : false;
var performAction = function performAction (action, tenantId, type, app, params, schedule) {
//check security;
registry = server.systemRegistry(tenantId);
store = require('/modules/store.js').store(tenantId, session);
asset = store.asset('mobileapp', app);
if(asset.attributes.overview_visibility){
var assetRoles = asset.attributes.overview_visibility.split(",");
var um = server.userManager(tenantId);
var userRoles = um.getRoleListOfUser(currentUser.username);
var commonRoles = userRoles.filter(function(n) {
return assetRoles.indexOf(String(n)) != -1
});
if(commonRoles.length <= 0){
response.sendError(401, 'Unauthorized');
return;
}
}
if( typeof params === 'string' ) {
params = [ params ];
}
log.debug(action + " performs on the app " + app + " in tenant " + tenantId + " & " + type + " : " + stringify(params));
if(type === 'device'){
var path = user.userSpace(currentUser) + SUBSCRIPTIONS_PATH + app;
if(action == 'install' || action == 'update') {
subscribe(path, app, currentUser.username);
}else if(action === 'uninstall') {
unsubscribe(path, app, currentUser.username);
}
}else if (type === 'user'){
params.forEach(function(username){
var path = user.userSpace({username: username, tenantId : tenantId }) + SUBSCRIPTIONS_PATH + app;
if(action == 'install') {
subscribe(path, app, username);
}else if(action === 'uninstall') {
unsubscribe(path, app, username);
}
});
}else if (type === 'role'){
var um = new carbon.user.UserManager(server, tenantId);
params.forEach(function(role){
var users = parse(stringify(um.getUserListOfRole(role)));
users.forEach(function(username){
var path = user.userSpace({username: username, tenantId : tenantId }) + SUBSCRIPTIONS_PATH + app;
if(action == 'install') {
subscribe(path, app, username);
}else if(action === 'uninstall') {
unsubscribe(path, app, username);
}
});
});
}
function subscribe(path, appId, username){
if (!registry.exists(path)) {
registry.put(path, {name: appId,content: '' });
setVisibility(appId, username, 'ALLOW');
}
}
function unsubscribe(path, appId, username){
if (registry.exists(path)) {
registry.remove(path);
setVisibility(appId, username, 'DENY');
}
}
function setVisibility(appId, username, opType){
asset = store.asset('mobileapp', appId);
var path = "/_system/governance/mobileapps/" + asset.attributes.overview_provider + "/" + asset.attributes.overview_platform + "/" + asset.attributes.overview_name + "/" + asset.attributes.overview_version;
mobileGeneric.showAppVisibilityToUser(path, username, opType);
}
if(isMDMOperationsEnabled){
var operationsClass = Packages.org.wso2.carbon.appmgt.mobile.store.Operations;
var operations = new operationsClass();
operations.performAction(stringify(currentUser), action, tenantId, type, app, params, schedule);
}
|
useragent = request.getHeader("User-Agent");
if(useragent.match(/iPad/i) || useragent.match(/iPhone/i) || useragent.match(/Android/i)) {
if(mdmConfig.AppDownloadURLHost == "%http%"){
var serverAddress = carbon.server.address('http');
}else if(mdmConfig.AppDownloadURLHost == "%https%"){
var serverAddress = carbon.server.address('https');
}else{
var serverAddress = mdmConfig.AppDownloadURLHost;
}
asset = store.asset('mobileapp', app);
if( asset.attributes.overview_type == "enterprise"){
if(asset.attributes.overview_platform == "android"){
var location = serverAddress + asset.attributes.overview_url;
}else if(asset.attributes.overview_platform == "ios"){
var filename = asset.attributes.overview_url.split("/").pop();
var location = "itms-services://?action=download-manifest&url=" + carbon.server.address('https') + "/" + mdmConfig.IosPlistPath + "/" + tenantId + "/" + filename;
}
}else if(asset.attributes.overview_type == "webapp"){
var location = asset.attributes.overview_url;
}
else{
if(asset.attributes.overview_platform == "android"){
var location = "https://play.google.com/store/apps/details?id=" + asset.attributes.overview_packagename;
}else if(asset.attributes.overview_platform == "ios"){
var location = "https://itunes.apple.com/en/app/id" + asset.attributes.overview_appid;
}
}
print({redirect: true, location : location});
}else{
print({});
}
}
}; | if(isDirectDownloadEnabled){ | random_line_split |
mod-ent-install.js | var log = new Log();
var mod = require('store');
var user = mod.user;
var server = require('store').server;
var currentUser = server.current(session);
var SUBSCRIPTIONS_PATH = '/subscriptions/mobileapp/';
var mobileGeneric = new Packages.org.wso2.carbon.appmgt.mobile.store.Generic();
var mdmConfig = parse(String((new Packages.org.wso2.carbon.appmgt.mobile.store.MDMConfig()).getConfigs()));
var isMDMOperationsEnabled = mdmConfig.EnableMDMOperations == "true" ? true : false;
var isDirectDownloadEnabled = mdmConfig.EnableDirectDownload == "true" ? true : false;
var performAction = function performAction (action, tenantId, type, app, params, schedule) {
//check security;
registry = server.systemRegistry(tenantId);
store = require('/modules/store.js').store(tenantId, session);
asset = store.asset('mobileapp', app);
if(asset.attributes.overview_visibility){
var assetRoles = asset.attributes.overview_visibility.split(",");
var um = server.userManager(tenantId);
var userRoles = um.getRoleListOfUser(currentUser.username);
var commonRoles = userRoles.filter(function(n) {
return assetRoles.indexOf(String(n)) != -1
});
if(commonRoles.length <= 0){
response.sendError(401, 'Unauthorized');
return;
}
}
if( typeof params === 'string' ) {
params = [ params ];
}
log.debug(action + " performs on the app " + app + " in tenant " + tenantId + " & " + type + " : " + stringify(params));
if(type === 'device'){
var path = user.userSpace(currentUser) + SUBSCRIPTIONS_PATH + app;
if(action == 'install' || action == 'update') {
subscribe(path, app, currentUser.username);
}else if(action === 'uninstall') {
unsubscribe(path, app, currentUser.username);
}
}else if (type === 'user'){
params.forEach(function(username){
var path = user.userSpace({username: username, tenantId : tenantId }) + SUBSCRIPTIONS_PATH + app;
if(action == 'install') {
subscribe(path, app, username);
}else if(action === 'uninstall') {
unsubscribe(path, app, username);
}
});
}else if (type === 'role'){
var um = new carbon.user.UserManager(server, tenantId);
params.forEach(function(role){
var users = parse(stringify(um.getUserListOfRole(role)));
users.forEach(function(username){
var path = user.userSpace({username: username, tenantId : tenantId }) + SUBSCRIPTIONS_PATH + app;
if(action == 'install') {
subscribe(path, app, username);
}else if(action === 'uninstall') {
unsubscribe(path, app, username);
}
});
});
}
function subscribe(path, appId, username){
if (!registry.exists(path)) {
registry.put(path, {name: appId,content: '' });
setVisibility(appId, username, 'ALLOW');
}
}
function unsubscribe(path, appId, username) |
function setVisibility(appId, username, opType){
asset = store.asset('mobileapp', appId);
var path = "/_system/governance/mobileapps/" + asset.attributes.overview_provider + "/" + asset.attributes.overview_platform + "/" + asset.attributes.overview_name + "/" + asset.attributes.overview_version;
mobileGeneric.showAppVisibilityToUser(path, username, opType);
}
if(isMDMOperationsEnabled){
var operationsClass = Packages.org.wso2.carbon.appmgt.mobile.store.Operations;
var operations = new operationsClass();
operations.performAction(stringify(currentUser), action, tenantId, type, app, params, schedule);
}
if(isDirectDownloadEnabled){
useragent = request.getHeader("User-Agent");
if(useragent.match(/iPad/i) || useragent.match(/iPhone/i) || useragent.match(/Android/i)) {
if(mdmConfig.AppDownloadURLHost == "%http%"){
var serverAddress = carbon.server.address('http');
}else if(mdmConfig.AppDownloadURLHost == "%https%"){
var serverAddress = carbon.server.address('https');
}else{
var serverAddress = mdmConfig.AppDownloadURLHost;
}
asset = store.asset('mobileapp', app);
if( asset.attributes.overview_type == "enterprise"){
if(asset.attributes.overview_platform == "android"){
var location = serverAddress + asset.attributes.overview_url;
}else if(asset.attributes.overview_platform == "ios"){
var filename = asset.attributes.overview_url.split("/").pop();
var location = "itms-services://?action=download-manifest&url=" + carbon.server.address('https') + "/" + mdmConfig.IosPlistPath + "/" + tenantId + "/" + filename;
}
}else if(asset.attributes.overview_type == "webapp"){
var location = asset.attributes.overview_url;
}
else{
if(asset.attributes.overview_platform == "android"){
var location = "https://play.google.com/store/apps/details?id=" + asset.attributes.overview_packagename;
}else if(asset.attributes.overview_platform == "ios"){
var location = "https://itunes.apple.com/en/app/id" + asset.attributes.overview_appid;
}
}
print({redirect: true, location : location});
}else{
print({});
}
}
};
| {
if (registry.exists(path)) {
registry.remove(path);
setVisibility(appId, username, 'DENY');
}
} | identifier_body |
mod-ent-install.js | var log = new Log();
var mod = require('store');
var user = mod.user;
var server = require('store').server;
var currentUser = server.current(session);
var SUBSCRIPTIONS_PATH = '/subscriptions/mobileapp/';
var mobileGeneric = new Packages.org.wso2.carbon.appmgt.mobile.store.Generic();
var mdmConfig = parse(String((new Packages.org.wso2.carbon.appmgt.mobile.store.MDMConfig()).getConfigs()));
var isMDMOperationsEnabled = mdmConfig.EnableMDMOperations == "true" ? true : false;
var isDirectDownloadEnabled = mdmConfig.EnableDirectDownload == "true" ? true : false;
var performAction = function performAction (action, tenantId, type, app, params, schedule) {
//check security;
registry = server.systemRegistry(tenantId);
store = require('/modules/store.js').store(tenantId, session);
asset = store.asset('mobileapp', app);
if(asset.attributes.overview_visibility){
var assetRoles = asset.attributes.overview_visibility.split(",");
var um = server.userManager(tenantId);
var userRoles = um.getRoleListOfUser(currentUser.username);
var commonRoles = userRoles.filter(function(n) {
return assetRoles.indexOf(String(n)) != -1
});
if(commonRoles.length <= 0){
response.sendError(401, 'Unauthorized');
return;
}
}
if( typeof params === 'string' ) {
params = [ params ];
}
log.debug(action + " performs on the app " + app + " in tenant " + tenantId + " & " + type + " : " + stringify(params));
if(type === 'device'){
var path = user.userSpace(currentUser) + SUBSCRIPTIONS_PATH + app;
if(action == 'install' || action == 'update') {
subscribe(path, app, currentUser.username);
}else if(action === 'uninstall') {
unsubscribe(path, app, currentUser.username);
}
}else if (type === 'user'){
params.forEach(function(username){
var path = user.userSpace({username: username, tenantId : tenantId }) + SUBSCRIPTIONS_PATH + app;
if(action == 'install') {
subscribe(path, app, username);
}else if(action === 'uninstall') {
unsubscribe(path, app, username);
}
});
}else if (type === 'role'){
var um = new carbon.user.UserManager(server, tenantId);
params.forEach(function(role){
var users = parse(stringify(um.getUserListOfRole(role)));
users.forEach(function(username){
var path = user.userSpace({username: username, tenantId : tenantId }) + SUBSCRIPTIONS_PATH + app;
if(action == 'install') {
subscribe(path, app, username);
}else if(action === 'uninstall') {
unsubscribe(path, app, username);
}
});
});
}
function subscribe(path, appId, username){
if (!registry.exists(path)) {
registry.put(path, {name: appId,content: '' });
setVisibility(appId, username, 'ALLOW');
}
}
function unsubscribe(path, appId, username){
if (registry.exists(path)) {
registry.remove(path);
setVisibility(appId, username, 'DENY');
}
}
function | (appId, username, opType){
asset = store.asset('mobileapp', appId);
var path = "/_system/governance/mobileapps/" + asset.attributes.overview_provider + "/" + asset.attributes.overview_platform + "/" + asset.attributes.overview_name + "/" + asset.attributes.overview_version;
mobileGeneric.showAppVisibilityToUser(path, username, opType);
}
if(isMDMOperationsEnabled){
var operationsClass = Packages.org.wso2.carbon.appmgt.mobile.store.Operations;
var operations = new operationsClass();
operations.performAction(stringify(currentUser), action, tenantId, type, app, params, schedule);
}
if(isDirectDownloadEnabled){
useragent = request.getHeader("User-Agent");
if(useragent.match(/iPad/i) || useragent.match(/iPhone/i) || useragent.match(/Android/i)) {
if(mdmConfig.AppDownloadURLHost == "%http%"){
var serverAddress = carbon.server.address('http');
}else if(mdmConfig.AppDownloadURLHost == "%https%"){
var serverAddress = carbon.server.address('https');
}else{
var serverAddress = mdmConfig.AppDownloadURLHost;
}
asset = store.asset('mobileapp', app);
if( asset.attributes.overview_type == "enterprise"){
if(asset.attributes.overview_platform == "android"){
var location = serverAddress + asset.attributes.overview_url;
}else if(asset.attributes.overview_platform == "ios"){
var filename = asset.attributes.overview_url.split("/").pop();
var location = "itms-services://?action=download-manifest&url=" + carbon.server.address('https') + "/" + mdmConfig.IosPlistPath + "/" + tenantId + "/" + filename;
}
}else if(asset.attributes.overview_type == "webapp"){
var location = asset.attributes.overview_url;
}
else{
if(asset.attributes.overview_platform == "android"){
var location = "https://play.google.com/store/apps/details?id=" + asset.attributes.overview_packagename;
}else if(asset.attributes.overview_platform == "ios"){
var location = "https://itunes.apple.com/en/app/id" + asset.attributes.overview_appid;
}
}
print({redirect: true, location : location});
}else{
print({});
}
}
};
| setVisibility | identifier_name |
rcvr-borrowed-to-region.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
use std::gc::GC;
trait get {
fn get(self) -> int;
}
// Note: impl on a slice; we're checking that the pointers below
// correctly get borrowed to `&`. (similar to impling for `int`, with
// `&self` instead of `self`.)
impl<'a> get for &'a int {
fn get(self) -> int {
return *self;
}
}
pub fn main() | {
let x = box(GC) 6;
let y = x.get();
assert_eq!(y, 6);
let x = box(GC) 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = box 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = &6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
} | identifier_body | |
rcvr-borrowed-to-region.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
use std::gc::GC;
trait get {
fn get(self) -> int;
}
// Note: impl on a slice; we're checking that the pointers below
// correctly get borrowed to `&`. (similar to impling for `int`, with
// `&self` instead of `self`.)
impl<'a> get for &'a int {
fn get(self) -> int {
return *self;
}
}
pub fn | () {
let x = box(GC) 6;
let y = x.get();
assert_eq!(y, 6);
let x = box(GC) 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = box 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = &6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
}
| main | identifier_name |
rcvr-borrowed-to-region.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
use std::gc::GC;
trait get {
fn get(self) -> int;
}
// Note: impl on a slice; we're checking that the pointers below
// correctly get borrowed to `&`. (similar to impling for `int`, with
// `&self` instead of `self`.)
impl<'a> get for &'a int {
fn get(self) -> int {
return *self;
}
}
pub fn main() {
let x = box(GC) 6;
let y = x.get();
assert_eq!(y, 6);
let x = box(GC) 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = box 6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
let x = &6;
let y = x.get();
println!("y={}", y);
assert_eq!(y, 6);
} | random_line_split | |
368-disused-railway-stations.py | # -*- encoding: utf-8 -*-
from shapely.wkt import loads as wkt_loads
import dsl
from . import FixtureTest
class DisusedRailwayStations(FixtureTest):
| def test_old_south_ferry(self):
# Old South Ferry (1) (disused=yes)
self.generate_fixtures(dsl.way(2086974744, wkt_loads('POINT (-74.01325716895789 40.701283821753)'), {u'name': u'Old South Ferry (1)', u'wheelchair': u'no', u'source': u'openstreetmap.org', u'railway': u'station', u'disused': u'yes', u'network': u'New York City Subway'})) # noqa
self.assert_no_matching_feature(
16, 19294, 24643, 'pois',
{'kind': 'station', 'id': 2086974744})
def test_valle_az(self):
# Valle, AZ (disused=station)
self.generate_fixtures(dsl.way(366220389, wkt_loads('POINT (-112.200039193448 35.65261688375637)'), {u'name': u'Valle', u'gnis:reviewed': u'no', u'addr:state': u'AZ', u'ele': u'1794', u'source': u'openstreetmap.org', u'gnis:feature_id': u'21103', u'disused': u'station', u'gnis:county_name': u'Coconino'})) # noqa
self.assert_no_matching_feature(
16, 12342, 25813, 'pois',
{'id': 366220389}) | identifier_body | |
368-disused-railway-stations.py | # -*- encoding: utf-8 -*-
from shapely.wkt import loads as wkt_loads
import dsl
from . import FixtureTest
class DisusedRailwayStations(FixtureTest):
def test_old_south_ferry(self):
# Old South Ferry (1) (disused=yes)
self.generate_fixtures(dsl.way(2086974744, wkt_loads('POINT (-74.01325716895789 40.701283821753)'), {u'name': u'Old South Ferry (1)', u'wheelchair': u'no', u'source': u'openstreetmap.org', u'railway': u'station', u'disused': u'yes', u'network': u'New York City Subway'})) # noqa
self.assert_no_matching_feature(
16, 19294, 24643, 'pois',
{'kind': 'station', 'id': 2086974744})
def | (self):
# Valle, AZ (disused=station)
self.generate_fixtures(dsl.way(366220389, wkt_loads('POINT (-112.200039193448 35.65261688375637)'), {u'name': u'Valle', u'gnis:reviewed': u'no', u'addr:state': u'AZ', u'ele': u'1794', u'source': u'openstreetmap.org', u'gnis:feature_id': u'21103', u'disused': u'station', u'gnis:county_name': u'Coconino'})) # noqa
self.assert_no_matching_feature(
16, 12342, 25813, 'pois',
{'id': 366220389})
| test_valle_az | identifier_name |
368-disused-railway-stations.py | # -*- encoding: utf-8 -*-
from shapely.wkt import loads as wkt_loads
import dsl
from . import FixtureTest
class DisusedRailwayStations(FixtureTest):
def test_old_south_ferry(self): | # Old South Ferry (1) (disused=yes)
self.generate_fixtures(dsl.way(2086974744, wkt_loads('POINT (-74.01325716895789 40.701283821753)'), {u'name': u'Old South Ferry (1)', u'wheelchair': u'no', u'source': u'openstreetmap.org', u'railway': u'station', u'disused': u'yes', u'network': u'New York City Subway'})) # noqa
self.assert_no_matching_feature(
16, 19294, 24643, 'pois',
{'kind': 'station', 'id': 2086974744})
def test_valle_az(self):
# Valle, AZ (disused=station)
self.generate_fixtures(dsl.way(366220389, wkt_loads('POINT (-112.200039193448 35.65261688375637)'), {u'name': u'Valle', u'gnis:reviewed': u'no', u'addr:state': u'AZ', u'ele': u'1794', u'source': u'openstreetmap.org', u'gnis:feature_id': u'21103', u'disused': u'station', u'gnis:county_name': u'Coconino'})) # noqa
self.assert_no_matching_feature(
16, 12342, 25813, 'pois',
{'id': 366220389}) | random_line_split | |
MacroScreenView.js | // Copyright 2013-2021, University of Colorado Boulder
/**
* View for the 'Macro' screen.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
import Property from '../../../../axon/js/Property.js';
import ScreenView from '../../../../joist/js/ScreenView.js';
import merge from '../../../../phet-core/js/merge.js';
import ModelViewTransform2 from '../../../../phetcommon/js/view/ModelViewTransform2.js';
import ResetAllButton from '../../../../scenery-phet/js/buttons/ResetAllButton.js';
import EyeDropperNode from '../../../../scenery-phet/js/EyeDropperNode.js';
import { Node } from '../../../../scenery/js/imports.js';
import Tandem from '../../../../tandem/js/Tandem.js';
import Water from '../../common/model/Water.js';
import PHScaleConstants from '../../common/PHScaleConstants.js';
import BeakerNode from '../../common/view/BeakerNode.js';
import DrainFaucetNode from '../../common/view/DrainFaucetNode.js';
import DropperFluidNode from '../../common/view/DropperFluidNode.js';
import FaucetFluidNode from '../../common/view/FaucetFluidNode.js';
import PHDropperNode from '../../common/view/PHDropperNode.js';
import SoluteComboBox from '../../common/view/SoluteComboBox.js';
import SolutionNode from '../../common/view/SolutionNode.js';
import VolumeIndicatorNode from '../../common/view/VolumeIndicatorNode.js';
import WaterFaucetNode from '../../common/view/WaterFaucetNode.js';
import phScale from '../../phScale.js';
import MacroPHMeterNode from './MacroPHMeterNode.js';
import NeutralIndicatorNode from './NeutralIndicatorNode.js';
class | extends ScreenView {
/**
* @param {MacroModel} model
* @param {ModelViewTransform2} modelViewTransform
* @param {Tandem} tandem
*/
constructor( model, modelViewTransform, tandem ) {
assert && assert( tandem instanceof Tandem, 'invalid tandem' );
assert && assert( modelViewTransform instanceof ModelViewTransform2, 'invalid modelViewTransform' );
super( merge( {}, PHScaleConstants.SCREEN_VIEW_OPTIONS, {
tandem: tandem
} ) );
// beaker
const beakerNode = new BeakerNode( model.beaker, modelViewTransform, {
tandem: tandem.createTandem( 'beakerNode' )
} );
// solution in the beaker
const solutionNode = new SolutionNode( model.solution, model.beaker, modelViewTransform );
// volume indicator on the right edge of beaker
const volumeIndicatorNode = new VolumeIndicatorNode( model.solution.totalVolumeProperty, model.beaker, modelViewTransform, {
tandem: tandem.createTandem( 'volumeIndicatorNode' )
} );
// Neutral indicator that appears in the bottom of the beaker.
const neutralIndicatorNode = new NeutralIndicatorNode( model.solution, {
tandem: tandem.createTandem( 'neutralIndicatorNode' )
} );
// dropper
const DROPPER_SCALE = 0.85;
const dropperNode = new PHDropperNode( model.dropper, modelViewTransform, {
visibleProperty: model.dropper.visibleProperty,
tandem: tandem.createTandem( 'dropperNode' )
} );
dropperNode.setScaleMagnitude( DROPPER_SCALE );
const dropperFluidNode = new DropperFluidNode( model.dropper, model.beaker, DROPPER_SCALE * EyeDropperNode.TIP_WIDTH,
modelViewTransform, {
visibleProperty: model.dropper.visibleProperty
} );
// faucets
const waterFaucetNode = new WaterFaucetNode( model.waterFaucet, modelViewTransform, {
tandem: tandem.createTandem( 'waterFaucetNode' )
} );
const drainFaucetNode = new DrainFaucetNode( model.drainFaucet, modelViewTransform, {
tandem: tandem.createTandem( 'drainFaucetNode' )
} );
// fluids coming out of faucets
const WATER_FLUID_HEIGHT = model.beaker.position.y - model.waterFaucet.position.y;
const DRAIN_FLUID_HEIGHT = 1000; // tall enough that resizing the play area is unlikely to show bottom of fluid
const waterFluidNode = new FaucetFluidNode( model.waterFaucet, new Property( Water.color ), WATER_FLUID_HEIGHT, modelViewTransform );
const drainFluidNode = new FaucetFluidNode( model.drainFaucet, model.solution.colorProperty, DRAIN_FLUID_HEIGHT, modelViewTransform );
// Hide fluids when their faucets are hidden. See https://github.com/phetsims/ph-scale/issues/107
waterFaucetNode.visibleProperty.lazyLink( () => {
waterFaucetNode.visibile = waterFaucetNode.visible;
} );
drainFluidNode.visibleProperty.lazyLink( () => {
waterFaucetNode.visibile = drainFluidNode.visible;
} );
// pH meter
const pHMeterNode = new MacroPHMeterNode( model.pHMeter, model.solution, model.dropper,
solutionNode, dropperFluidNode, waterFluidNode, drainFluidNode, modelViewTransform, {
tandem: tandem.createTandem( 'pHMeterNode' )
} );
// solutes combo box
const soluteListParent = new Node();
const soluteComboBox = new SoluteComboBox( model.solutes, model.dropper.soluteProperty, soluteListParent, {
maxWidth: 400,
tandem: tandem.createTandem( 'soluteComboBox' )
} );
const resetAllButton = new ResetAllButton( {
scale: 1.32,
listener: () => {
this.interruptSubtreeInput();
model.reset();
},
tandem: tandem.createTandem( 'resetAllButton' )
} );
// Parent for all nodes added to this screen
const rootNode = new Node( {
children: [
// nodes are rendered in this order
waterFluidNode,
waterFaucetNode,
drainFluidNode,
drainFaucetNode,
dropperFluidNode,
dropperNode,
solutionNode,
beakerNode,
neutralIndicatorNode,
volumeIndicatorNode,
soluteComboBox,
resetAllButton,
pHMeterNode, // next to last so that probe doesn't get lost behind anything
soluteListParent // last, so that combo box list is on top
]
} );
this.addChild( rootNode );
// Layout of nodes that don't have a position specified in the model
soluteComboBox.left = modelViewTransform.modelToViewX( model.beaker.left ) - 20; // anchor on left so it grows to the right during i18n
soluteComboBox.top = this.layoutBounds.top + 15;
neutralIndicatorNode.centerX = beakerNode.centerX;
neutralIndicatorNode.bottom = beakerNode.bottom - 30;
resetAllButton.right = this.layoutBounds.right - 40;
resetAllButton.bottom = this.layoutBounds.bottom - 20;
model.isAutofillingProperty.link( () => dropperNode.interruptSubtreeInput() );
}
}
phScale.register( 'MacroScreenView', MacroScreenView );
export default MacroScreenView; | MacroScreenView | identifier_name |
MacroScreenView.js | // Copyright 2013-2021, University of Colorado Boulder
/**
* View for the 'Macro' screen.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
import Property from '../../../../axon/js/Property.js';
import ScreenView from '../../../../joist/js/ScreenView.js';
import merge from '../../../../phet-core/js/merge.js';
import ModelViewTransform2 from '../../../../phetcommon/js/view/ModelViewTransform2.js';
import ResetAllButton from '../../../../scenery-phet/js/buttons/ResetAllButton.js';
import EyeDropperNode from '../../../../scenery-phet/js/EyeDropperNode.js';
import { Node } from '../../../../scenery/js/imports.js';
import Tandem from '../../../../tandem/js/Tandem.js';
import Water from '../../common/model/Water.js';
import PHScaleConstants from '../../common/PHScaleConstants.js';
import BeakerNode from '../../common/view/BeakerNode.js';
import DrainFaucetNode from '../../common/view/DrainFaucetNode.js';
import DropperFluidNode from '../../common/view/DropperFluidNode.js';
import FaucetFluidNode from '../../common/view/FaucetFluidNode.js';
import PHDropperNode from '../../common/view/PHDropperNode.js';
import SoluteComboBox from '../../common/view/SoluteComboBox.js';
import SolutionNode from '../../common/view/SolutionNode.js';
import VolumeIndicatorNode from '../../common/view/VolumeIndicatorNode.js';
import WaterFaucetNode from '../../common/view/WaterFaucetNode.js';
import phScale from '../../phScale.js';
import MacroPHMeterNode from './MacroPHMeterNode.js';
import NeutralIndicatorNode from './NeutralIndicatorNode.js';
class MacroScreenView extends ScreenView {
/**
* @param {MacroModel} model
* @param {ModelViewTransform2} modelViewTransform
* @param {Tandem} tandem
*/
constructor( model, modelViewTransform, tandem ) |
}
phScale.register( 'MacroScreenView', MacroScreenView );
export default MacroScreenView; | {
assert && assert( tandem instanceof Tandem, 'invalid tandem' );
assert && assert( modelViewTransform instanceof ModelViewTransform2, 'invalid modelViewTransform' );
super( merge( {}, PHScaleConstants.SCREEN_VIEW_OPTIONS, {
tandem: tandem
} ) );
// beaker
const beakerNode = new BeakerNode( model.beaker, modelViewTransform, {
tandem: tandem.createTandem( 'beakerNode' )
} );
// solution in the beaker
const solutionNode = new SolutionNode( model.solution, model.beaker, modelViewTransform );
// volume indicator on the right edge of beaker
const volumeIndicatorNode = new VolumeIndicatorNode( model.solution.totalVolumeProperty, model.beaker, modelViewTransform, {
tandem: tandem.createTandem( 'volumeIndicatorNode' )
} );
// Neutral indicator that appears in the bottom of the beaker.
const neutralIndicatorNode = new NeutralIndicatorNode( model.solution, {
tandem: tandem.createTandem( 'neutralIndicatorNode' )
} );
// dropper
const DROPPER_SCALE = 0.85;
const dropperNode = new PHDropperNode( model.dropper, modelViewTransform, {
visibleProperty: model.dropper.visibleProperty,
tandem: tandem.createTandem( 'dropperNode' )
} );
dropperNode.setScaleMagnitude( DROPPER_SCALE );
const dropperFluidNode = new DropperFluidNode( model.dropper, model.beaker, DROPPER_SCALE * EyeDropperNode.TIP_WIDTH,
modelViewTransform, {
visibleProperty: model.dropper.visibleProperty
} );
// faucets
const waterFaucetNode = new WaterFaucetNode( model.waterFaucet, modelViewTransform, {
tandem: tandem.createTandem( 'waterFaucetNode' )
} );
const drainFaucetNode = new DrainFaucetNode( model.drainFaucet, modelViewTransform, {
tandem: tandem.createTandem( 'drainFaucetNode' )
} );
// fluids coming out of faucets
const WATER_FLUID_HEIGHT = model.beaker.position.y - model.waterFaucet.position.y;
const DRAIN_FLUID_HEIGHT = 1000; // tall enough that resizing the play area is unlikely to show bottom of fluid
const waterFluidNode = new FaucetFluidNode( model.waterFaucet, new Property( Water.color ), WATER_FLUID_HEIGHT, modelViewTransform );
const drainFluidNode = new FaucetFluidNode( model.drainFaucet, model.solution.colorProperty, DRAIN_FLUID_HEIGHT, modelViewTransform );
// Hide fluids when their faucets are hidden. See https://github.com/phetsims/ph-scale/issues/107
waterFaucetNode.visibleProperty.lazyLink( () => {
waterFaucetNode.visibile = waterFaucetNode.visible;
} );
drainFluidNode.visibleProperty.lazyLink( () => {
waterFaucetNode.visibile = drainFluidNode.visible;
} );
// pH meter
const pHMeterNode = new MacroPHMeterNode( model.pHMeter, model.solution, model.dropper,
solutionNode, dropperFluidNode, waterFluidNode, drainFluidNode, modelViewTransform, {
tandem: tandem.createTandem( 'pHMeterNode' )
} );
// solutes combo box
const soluteListParent = new Node();
const soluteComboBox = new SoluteComboBox( model.solutes, model.dropper.soluteProperty, soluteListParent, {
maxWidth: 400,
tandem: tandem.createTandem( 'soluteComboBox' )
} );
const resetAllButton = new ResetAllButton( {
scale: 1.32,
listener: () => {
this.interruptSubtreeInput();
model.reset();
},
tandem: tandem.createTandem( 'resetAllButton' )
} );
// Parent for all nodes added to this screen
const rootNode = new Node( {
children: [
// nodes are rendered in this order
waterFluidNode,
waterFaucetNode,
drainFluidNode,
drainFaucetNode,
dropperFluidNode,
dropperNode,
solutionNode,
beakerNode,
neutralIndicatorNode,
volumeIndicatorNode,
soluteComboBox,
resetAllButton,
pHMeterNode, // next to last so that probe doesn't get lost behind anything
soluteListParent // last, so that combo box list is on top
]
} );
this.addChild( rootNode );
// Layout of nodes that don't have a position specified in the model
soluteComboBox.left = modelViewTransform.modelToViewX( model.beaker.left ) - 20; // anchor on left so it grows to the right during i18n
soluteComboBox.top = this.layoutBounds.top + 15;
neutralIndicatorNode.centerX = beakerNode.centerX;
neutralIndicatorNode.bottom = beakerNode.bottom - 30;
resetAllButton.right = this.layoutBounds.right - 40;
resetAllButton.bottom = this.layoutBounds.bottom - 20;
model.isAutofillingProperty.link( () => dropperNode.interruptSubtreeInput() );
} | identifier_body |
MacroScreenView.js | // Copyright 2013-2021, University of Colorado Boulder
/**
* View for the 'Macro' screen.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
import Property from '../../../../axon/js/Property.js';
import ScreenView from '../../../../joist/js/ScreenView.js';
import merge from '../../../../phet-core/js/merge.js';
import ModelViewTransform2 from '../../../../phetcommon/js/view/ModelViewTransform2.js';
import ResetAllButton from '../../../../scenery-phet/js/buttons/ResetAllButton.js';
import EyeDropperNode from '../../../../scenery-phet/js/EyeDropperNode.js';
import { Node } from '../../../../scenery/js/imports.js';
import Tandem from '../../../../tandem/js/Tandem.js';
import Water from '../../common/model/Water.js';
import PHScaleConstants from '../../common/PHScaleConstants.js';
import BeakerNode from '../../common/view/BeakerNode.js';
import DrainFaucetNode from '../../common/view/DrainFaucetNode.js';
import DropperFluidNode from '../../common/view/DropperFluidNode.js';
import FaucetFluidNode from '../../common/view/FaucetFluidNode.js';
import PHDropperNode from '../../common/view/PHDropperNode.js';
import SoluteComboBox from '../../common/view/SoluteComboBox.js';
import SolutionNode from '../../common/view/SolutionNode.js';
import VolumeIndicatorNode from '../../common/view/VolumeIndicatorNode.js';
import WaterFaucetNode from '../../common/view/WaterFaucetNode.js';
import phScale from '../../phScale.js';
import MacroPHMeterNode from './MacroPHMeterNode.js';
import NeutralIndicatorNode from './NeutralIndicatorNode.js';
class MacroScreenView extends ScreenView {
/**
* @param {MacroModel} model
* @param {ModelViewTransform2} modelViewTransform
* @param {Tandem} tandem
*/
constructor( model, modelViewTransform, tandem ) {
assert && assert( tandem instanceof Tandem, 'invalid tandem' );
assert && assert( modelViewTransform instanceof ModelViewTransform2, 'invalid modelViewTransform' );
super( merge( {}, PHScaleConstants.SCREEN_VIEW_OPTIONS, {
tandem: tandem
} ) );
// beaker
const beakerNode = new BeakerNode( model.beaker, modelViewTransform, {
tandem: tandem.createTandem( 'beakerNode' )
} );
// solution in the beaker
const solutionNode = new SolutionNode( model.solution, model.beaker, modelViewTransform );
// volume indicator on the right edge of beaker
const volumeIndicatorNode = new VolumeIndicatorNode( model.solution.totalVolumeProperty, model.beaker, modelViewTransform, {
tandem: tandem.createTandem( 'volumeIndicatorNode' )
} );
// Neutral indicator that appears in the bottom of the beaker.
const neutralIndicatorNode = new NeutralIndicatorNode( model.solution, { | const dropperNode = new PHDropperNode( model.dropper, modelViewTransform, {
visibleProperty: model.dropper.visibleProperty,
tandem: tandem.createTandem( 'dropperNode' )
} );
dropperNode.setScaleMagnitude( DROPPER_SCALE );
const dropperFluidNode = new DropperFluidNode( model.dropper, model.beaker, DROPPER_SCALE * EyeDropperNode.TIP_WIDTH,
modelViewTransform, {
visibleProperty: model.dropper.visibleProperty
} );
// faucets
const waterFaucetNode = new WaterFaucetNode( model.waterFaucet, modelViewTransform, {
tandem: tandem.createTandem( 'waterFaucetNode' )
} );
const drainFaucetNode = new DrainFaucetNode( model.drainFaucet, modelViewTransform, {
tandem: tandem.createTandem( 'drainFaucetNode' )
} );
// fluids coming out of faucets
const WATER_FLUID_HEIGHT = model.beaker.position.y - model.waterFaucet.position.y;
const DRAIN_FLUID_HEIGHT = 1000; // tall enough that resizing the play area is unlikely to show bottom of fluid
const waterFluidNode = new FaucetFluidNode( model.waterFaucet, new Property( Water.color ), WATER_FLUID_HEIGHT, modelViewTransform );
const drainFluidNode = new FaucetFluidNode( model.drainFaucet, model.solution.colorProperty, DRAIN_FLUID_HEIGHT, modelViewTransform );
// Hide fluids when their faucets are hidden. See https://github.com/phetsims/ph-scale/issues/107
waterFaucetNode.visibleProperty.lazyLink( () => {
waterFaucetNode.visibile = waterFaucetNode.visible;
} );
drainFluidNode.visibleProperty.lazyLink( () => {
waterFaucetNode.visibile = drainFluidNode.visible;
} );
// pH meter
const pHMeterNode = new MacroPHMeterNode( model.pHMeter, model.solution, model.dropper,
solutionNode, dropperFluidNode, waterFluidNode, drainFluidNode, modelViewTransform, {
tandem: tandem.createTandem( 'pHMeterNode' )
} );
// solutes combo box
const soluteListParent = new Node();
const soluteComboBox = new SoluteComboBox( model.solutes, model.dropper.soluteProperty, soluteListParent, {
maxWidth: 400,
tandem: tandem.createTandem( 'soluteComboBox' )
} );
const resetAllButton = new ResetAllButton( {
scale: 1.32,
listener: () => {
this.interruptSubtreeInput();
model.reset();
},
tandem: tandem.createTandem( 'resetAllButton' )
} );
// Parent for all nodes added to this screen
const rootNode = new Node( {
children: [
// nodes are rendered in this order
waterFluidNode,
waterFaucetNode,
drainFluidNode,
drainFaucetNode,
dropperFluidNode,
dropperNode,
solutionNode,
beakerNode,
neutralIndicatorNode,
volumeIndicatorNode,
soluteComboBox,
resetAllButton,
pHMeterNode, // next to last so that probe doesn't get lost behind anything
soluteListParent // last, so that combo box list is on top
]
} );
this.addChild( rootNode );
// Layout of nodes that don't have a position specified in the model
soluteComboBox.left = modelViewTransform.modelToViewX( model.beaker.left ) - 20; // anchor on left so it grows to the right during i18n
soluteComboBox.top = this.layoutBounds.top + 15;
neutralIndicatorNode.centerX = beakerNode.centerX;
neutralIndicatorNode.bottom = beakerNode.bottom - 30;
resetAllButton.right = this.layoutBounds.right - 40;
resetAllButton.bottom = this.layoutBounds.bottom - 20;
model.isAutofillingProperty.link( () => dropperNode.interruptSubtreeInput() );
}
}
phScale.register( 'MacroScreenView', MacroScreenView );
export default MacroScreenView; | tandem: tandem.createTandem( 'neutralIndicatorNode' )
} );
// dropper
const DROPPER_SCALE = 0.85; | random_line_split |
views.py | import asjson
from flask.views import MethodView
from functools import wraps
from flask.ext.mongoengine.wtf import model_form
from flask import request, render_template, Blueprint, redirect, abort, session, make_response
from .models import User, SessionStorage
from mongoengine import DoesNotExist
auth = Blueprint('auth', __name__, template_folder='templates')
class UserAuth(MethodView):
@staticmethod
def get():
form = model_form(User)(request.form)
return render_template('auth/index.html', form=form)
@staticmethod
def post():
if request.form:
try:
username = request.form['name']
password = request.form['password']
user = User.objects.get(name=username)
if user and user.password == password: | response = make_response(redirect('/panel_control'))
if 'session' in request.cookies:
session_id = request.cookies['session']
else:
session_id = session['csrf_token']
# Setting user-cookie
response.set_cookie('session_id', value=session_id)
# After.We update our storage session(remove old + add new record)
record = SessionStorage()
record.remove_old_session(username)
record.user = username
record.session_key = session_id
record.save()
# And redirect to admin-panel
return response
else:
raise DoesNotExist
except DoesNotExist:
return abort(401)
@staticmethod
def is_admin():
# Выуживаем куки из различных мест,т.к. отправлять могут в виде атрибута заголовков
cookies = request.cookies
if not cookies: # Ничего не нашли на первой иттерации.Попробуем вытащить из заголовка
try:
cookies = asjson.loads(request.headers['Set-Cookie'])
except KeyError:
pass
if 'session_id' in cookies:
session_id = cookies['session_id']
return bool(SessionStorage.objects.filter(session_key=session_id))
else:
return False
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if not UserAuth.is_admin():
return redirect('auth')
return f(*args, **kwargs)
return decorated
auth.add_url_rule('/auth/', view_func=UserAuth.as_view('auth')) | # prepare response/redirect | random_line_split |
views.py | import asjson
from flask.views import MethodView
from functools import wraps
from flask.ext.mongoengine.wtf import model_form
from flask import request, render_template, Blueprint, redirect, abort, session, make_response
from .models import User, SessionStorage
from mongoengine import DoesNotExist
auth = Blueprint('auth', __name__, template_folder='templates')
class UserAuth(MethodView):
@staticmethod
def get():
form = model_form(User)(request.form)
return render_template('auth/index.html', form=form)
@staticmethod
def post():
|
@staticmethod
def is_admin():
# Выуживаем куки из различных мест,т.к. отправлять могут в виде атрибута заголовков
cookies = request.cookies
if not cookies: # Ничего не нашли на первой иттерации.Попробуем вытащить из заголовка
try:
cookies = asjson.loads(request.headers['Set-Cookie'])
except KeyError:
pass
if 'session_id' in cookies:
session_id = cookies['session_id']
return bool(SessionStorage.objects.filter(session_key=session_id))
else:
return False
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if not UserAuth.is_admin():
return redirect('auth')
return f(*args, **kwargs)
return decorated
auth.add_url_rule('/auth/', view_func=UserAuth.as_view('auth'))
| if request.form:
try:
username = request.form['name']
password = request.form['password']
user = User.objects.get(name=username)
if user and user.password == password:
# prepare response/redirect
response = make_response(redirect('/panel_control'))
if 'session' in request.cookies:
session_id = request.cookies['session']
else:
session_id = session['csrf_token']
# Setting user-cookie
response.set_cookie('session_id', value=session_id)
# After.We update our storage session(remove old + add new record)
record = SessionStorage()
record.remove_old_session(username)
record.user = username
record.session_key = session_id
record.save()
# And redirect to admin-panel
return response
else:
raise DoesNotExist
except DoesNotExist:
return abort(401) | identifier_body |
views.py | import asjson
from flask.views import MethodView
from functools import wraps
from flask.ext.mongoengine.wtf import model_form
from flask import request, render_template, Blueprint, redirect, abort, session, make_response
from .models import User, SessionStorage
from mongoengine import DoesNotExist
auth = Blueprint('auth', __name__, template_folder='templates')
class UserAuth(MethodView):
@staticmethod
def get():
form = model_form(User)(request.form)
return render_template('auth/index.html', form=form)
@staticmethod
def post():
if request.form:
try:
username = request.form['name']
password = request.form['password']
user = User.objects.get(name=username)
if user and user.password == password:
# prepare response/redirect
response = make_response(redirect('/panel_control'))
if 'session' in request.cookies:
session_id = request.cookies['session']
else:
session_id = session['csrf_token']
# Setting user-cookie
response.set_cookie('session_id', value=session_id)
# After.We update our storage session(remove old + add new record)
record = SessionStorage()
record.remove_old_session(username)
record.user = username
record.session_key = session_id
record.save()
# And redirect to admin-panel
return response
else:
raise DoesNotExist
except DoesNotExist:
return abort(401)
@staticmethod
def is_admin():
# Выуживаем куки из различных мест,т.к. отправлять могут в виде атрибута заголовков
cookies = request.cookies
if not cookies: # Ничего не нашли на первой иттерации.Попробуем вытащить из заголовка
try:
cookies = asjson.loads(request.headers['Set-Cookie'])
except KeyError:
pass
if 'session_id' in cookies:
session_id = cookies['session_id']
return bool(SessionStorage.objects.filter(session_key=session_id))
else | ot UserAuth.is_admin():
return redirect('auth')
return f(*args, **kwargs)
return decorated
auth.add_url_rule('/auth/', view_func=UserAuth.as_view('auth'))
| :
return False
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if n | conditional_block |
views.py | import asjson
from flask.views import MethodView
from functools import wraps
from flask.ext.mongoengine.wtf import model_form
from flask import request, render_template, Blueprint, redirect, abort, session, make_response
from .models import User, SessionStorage
from mongoengine import DoesNotExist
auth = Blueprint('auth', __name__, template_folder='templates')
class UserAuth(MethodView):
@staticmethod
def get():
form = model_form(User)(request.form)
return render_template('auth/index.html', form=form)
@staticmethod
def post():
if request.form:
try:
username = request.form['name']
password = request.form['password']
user = User.objects.get(name=username)
if user and user.password == password:
# prepare response/redirect
response = make_response(redirect('/panel_control'))
if 'session' in request.cookies:
session_id = request.cookies['session']
else:
session_id = session['csrf_token']
# Setting user-cookie
response.set_cookie('session_id', value=session_id)
# After.We update our storage session(remove old + add new record)
record = SessionStorage()
record.remove_old_session(username)
record.user = username
record.session_key = session_id
record.save()
# And redirect to admin-panel
return response
else:
raise DoesNotExist
except DoesNotExist:
return abort(401)
@staticmethod
def | ():
# Выуживаем куки из различных мест,т.к. отправлять могут в виде атрибута заголовков
cookies = request.cookies
if not cookies: # Ничего не нашли на первой иттерации.Попробуем вытащить из заголовка
try:
cookies = asjson.loads(request.headers['Set-Cookie'])
except KeyError:
pass
if 'session_id' in cookies:
session_id = cookies['session_id']
return bool(SessionStorage.objects.filter(session_key=session_id))
else:
return False
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if not UserAuth.is_admin():
return redirect('auth')
return f(*args, **kwargs)
return decorated
auth.add_url_rule('/auth/', view_func=UserAuth.as_view('auth'))
| is_admin | identifier_name |
diepempmsk.rs | #[doc = "Register `DIEPEMPMSK` reader"]
pub struct R(crate::R<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DIEPEMPMSK_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DIEPEMPMSK_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DIEPEMPMSK` writer"]
pub struct W(crate::W<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DIEPEMPMSK_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DIEPEMPMSK_SPEC>) -> Self {
W(writer) | pub struct INEPTXFEMPMSK_R(crate::FieldReader<u16, u16>);
impl INEPTXFEMPMSK_R {
pub(crate) fn new(bits: u16) -> Self {
INEPTXFEMPMSK_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPTXFEMPMSK_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `InEpTxfEmpMsk` writer - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_W<'a> {
w: &'a mut W,
}
impl<'a> INEPTXFEMPMSK_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&self) -> INEPTXFEMPMSK_R {
INEPTXFEMPMSK_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&mut self) -> INEPTXFEMPMSK_W {
INEPTXFEMPMSK_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Device IN Endpoint FIFO Empty Interrupt Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [diepempmsk](index.html) module"]
pub struct DIEPEMPMSK_SPEC;
impl crate::RegisterSpec for DIEPEMPMSK_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [diepempmsk::R](R) reader structure"]
impl crate::Readable for DIEPEMPMSK_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [diepempmsk::W](W) writer structure"]
impl crate::Writable for DIEPEMPMSK_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DIEPEMPMSK to value 0"]
impl crate::Resettable for DIEPEMPMSK_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | }
}
#[doc = "Field `InEpTxfEmpMsk` reader - IN EP Tx FIFO Empty Interrupt Mask Bits"] | random_line_split |
diepempmsk.rs | #[doc = "Register `DIEPEMPMSK` reader"]
pub struct R(crate::R<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DIEPEMPMSK_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DIEPEMPMSK_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DIEPEMPMSK` writer"]
pub struct W(crate::W<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn | (&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DIEPEMPMSK_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DIEPEMPMSK_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `InEpTxfEmpMsk` reader - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_R(crate::FieldReader<u16, u16>);
impl INEPTXFEMPMSK_R {
pub(crate) fn new(bits: u16) -> Self {
INEPTXFEMPMSK_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPTXFEMPMSK_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `InEpTxfEmpMsk` writer - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_W<'a> {
w: &'a mut W,
}
impl<'a> INEPTXFEMPMSK_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&self) -> INEPTXFEMPMSK_R {
INEPTXFEMPMSK_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&mut self) -> INEPTXFEMPMSK_W {
INEPTXFEMPMSK_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Device IN Endpoint FIFO Empty Interrupt Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [diepempmsk](index.html) module"]
pub struct DIEPEMPMSK_SPEC;
impl crate::RegisterSpec for DIEPEMPMSK_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [diepempmsk::R](R) reader structure"]
impl crate::Readable for DIEPEMPMSK_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [diepempmsk::W](W) writer structure"]
impl crate::Writable for DIEPEMPMSK_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DIEPEMPMSK to value 0"]
impl crate::Resettable for DIEPEMPMSK_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| deref_mut | identifier_name |
diepempmsk.rs | #[doc = "Register `DIEPEMPMSK` reader"]
pub struct R(crate::R<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DIEPEMPMSK_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DIEPEMPMSK_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DIEPEMPMSK` writer"]
pub struct W(crate::W<DIEPEMPMSK_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DIEPEMPMSK_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DIEPEMPMSK_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DIEPEMPMSK_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `InEpTxfEmpMsk` reader - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_R(crate::FieldReader<u16, u16>);
impl INEPTXFEMPMSK_R {
pub(crate) fn new(bits: u16) -> Self {
INEPTXFEMPMSK_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INEPTXFEMPMSK_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target |
}
#[doc = "Field `InEpTxfEmpMsk` writer - IN EP Tx FIFO Empty Interrupt Mask Bits"]
pub struct INEPTXFEMPMSK_W<'a> {
w: &'a mut W,
}
impl<'a> INEPTXFEMPMSK_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&self) -> INEPTXFEMPMSK_R {
INEPTXFEMPMSK_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - IN EP Tx FIFO Empty Interrupt Mask Bits"]
#[inline(always)]
pub fn in_ep_txf_emp_msk(&mut self) -> INEPTXFEMPMSK_W {
INEPTXFEMPMSK_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Device IN Endpoint FIFO Empty Interrupt Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [diepempmsk](index.html) module"]
pub struct DIEPEMPMSK_SPEC;
impl crate::RegisterSpec for DIEPEMPMSK_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [diepempmsk::R](R) reader structure"]
impl crate::Readable for DIEPEMPMSK_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [diepempmsk::W](W) writer structure"]
impl crate::Writable for DIEPEMPMSK_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DIEPEMPMSK to value 0"]
impl crate::Resettable for DIEPEMPMSK_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| {
&self.0
} | identifier_body |
test_apis_tags.py | # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
from .api_common import ApiCommon, recorder
class TestApisTags(ApiCommon):
"""Tests the Tags API endpoint."""
def setUp(self):
super(TestApisTags, self).setUp()
self.__endpoint__ = self.api.Tags
@recorder.use_cassette()
def test_apis_tags_get(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.update(None)
@recorder.use_cassette()
def test_apis_tags_delete(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.delete(None)
@recorder.use_cassette()
def test_apis_tags_update(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.update(None)
@recorder.use_cassette()
def test_apis_tags_create(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.create(None)
@recorder.use_cassette()
def test_apis_tags_list(self):
"""It should list the tags in the tag."""
self._test_list()
@recorder.use_cassette()
def test_apis_tags_search(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError): | self.__endpoint__.search([], None) | random_line_split | |
test_apis_tags.py | # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
from .api_common import ApiCommon, recorder
class TestApisTags(ApiCommon):
"""Tests the Tags API endpoint."""
def setUp(self):
super(TestApisTags, self).setUp()
self.__endpoint__ = self.api.Tags
@recorder.use_cassette()
def test_apis_tags_get(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.update(None)
@recorder.use_cassette()
def test_apis_tags_delete(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.delete(None)
@recorder.use_cassette()
def | (self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.update(None)
@recorder.use_cassette()
def test_apis_tags_create(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.create(None)
@recorder.use_cassette()
def test_apis_tags_list(self):
"""It should list the tags in the tag."""
self._test_list()
@recorder.use_cassette()
def test_apis_tags_search(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.search([], None)
| test_apis_tags_update | identifier_name |
test_apis_tags.py | # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
from .api_common import ApiCommon, recorder
class TestApisTags(ApiCommon):
"""Tests the Tags API endpoint."""
def setUp(self):
super(TestApisTags, self).setUp()
self.__endpoint__ = self.api.Tags
@recorder.use_cassette()
def test_apis_tags_get(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.update(None)
@recorder.use_cassette()
def test_apis_tags_delete(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.delete(None)
@recorder.use_cassette()
def test_apis_tags_update(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.update(None)
@recorder.use_cassette()
def test_apis_tags_create(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.create(None)
@recorder.use_cassette()
def test_apis_tags_list(self):
|
@recorder.use_cassette()
def test_apis_tags_search(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.search([], None)
| """It should list the tags in the tag."""
self._test_list() | identifier_body |
version.py | # -*- coding: utf-8 -*-
"""Module to determine the pywikibot version (tag, revision and date)."""
#
# (C) Merlijn 'valhallasw' van Deen, 2007-2014
# (C) xqt, 2010-2015
# (C) Pywikibot team, 2007-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import codecs
import datetime
import os
import subprocess
import sys
import time
import xml.dom.minidom
from distutils.sysconfig import get_python_lib
from io import BytesIO
from warnings import warn
try:
from setuptools import svn_utils
except ImportError:
try:
from setuptools_svn import svn_utils
except ImportError as e:
svn_utils = e
import pywikibot
from pywikibot import config2 as config
from pywikibot.tools import deprecated, PY2
if not PY2:
basestring = (str, )
cache = None
_logger = 'version'
class ParseError(Exception):
"""Parsing went wrong."""
def _get_program_dir():
_program_dir = os.path.normpath(os.path.split(os.path.dirname(__file__))[0])
return _program_dir
def getversion(online=True):
"""Return a pywikibot version string.
@param online: (optional) Include information obtained online
"""
data = dict(getversiondict()) # copy dict to prevent changes in 'cache'
data['cmp_ver'] = 'n/a'
if online:
try:
hsh2 = getversion_onlinerepo()
hsh1 = data['hsh']
data['cmp_ver'] = 'OUTDATED' if hsh1 != hsh2 else 'ok'
except Exception:
pass
data['hsh'] = data['hsh'][:7] # make short hash from full hash
return '%(tag)s (%(hsh)s, %(rev)s, %(date)s, %(cmp_ver)s)' % data
def getversiondict():
"""Get version info for the package.
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{dict} of four C{str}
"""
global cache
if cache:
return cache
_program_dir = _get_program_dir()
exceptions = {}
for vcs_func in (getversion_git,
getversion_svn_setuptools,
getversion_nightly,
getversion_svn,
getversion_package):
try:
(tag, rev, date, hsh) = vcs_func(_program_dir)
except Exception as e:
exceptions[vcs_func] = e
else:
break
else:
# nothing worked; version unknown (but suppress exceptions)
# the value is most likely '$Id' + '$', it means that
# pywikibot was imported without using version control at all.
tag, rev, date, hsh = (
'', '-1 (unknown)', '0 (unknown)', '(unknown)')
# git and svn can silently fail, as it may be a nightly.
if getversion_package in exceptions:
warn('Unable to detect version; exceptions raised:\n%r'
% exceptions, UserWarning)
elif exceptions:
pywikibot.debug('version algorithm exceptions:\n%r'
% exceptions, _logger)
if isinstance(date, basestring):
datestring = date
elif isinstance(date, time.struct_time):
datestring = time.strftime('%Y/%m/%d, %H:%M:%S', date)
else:
warn('Unable to detect package date', UserWarning)
datestring = '-2 (unknown)'
cache = dict(tag=tag, rev=rev, date=datestring, hsh=hsh)
return cache
@deprecated('getversion_svn_setuptools')
def svn_rev_info(path):
"""Fetch information about the current revision of an Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
@rtype: C{tuple} of two C{str} and a C{time.struct_time}
"""
if not os.path.isdir(os.path.join(path, '.svn')):
path = os.path.join(path, '..')
_program_dir = path
filename = os.path.join(_program_dir, '.svn/entries')
if os.path.isfile(filename):
with open(filename) as entries:
version = entries.readline().strip()
if version != '12':
for i in range(3):
entries.readline()
tag = entries.readline().strip()
t = tag.split('://')
t[1] = t[1].replace('svn.wikimedia.org/svnroot/pywikipedia/',
'')
tag = '[%s] %s' % (t[0], t[1])
for i in range(4):
entries.readline()
date = time.strptime(entries.readline()[:19],
'%Y-%m-%dT%H:%M:%S')
rev = entries.readline()[:-1]
return tag, rev, date
# We haven't found the information in entries file.
# Use sqlite table for new entries format
from sqlite3 import dbapi2 as sqlite
con = sqlite.connect(os.path.join(_program_dir, ".svn/wc.db"))
cur = con.cursor()
cur.execute("""select
local_relpath, repos_path, revision, changed_date, checksum from nodes
order by revision desc, changed_date desc""")
name, tag, rev, date, checksum = cur.fetchone()
cur.execute("select root from repository")
tag, = cur.fetchone()
con.close()
tag = os.path.split(tag)[1]
date = time.gmtime(date / 1000000)
return tag, rev, date
def github_svn_rev2hash(tag, rev):
"""Convert a Subversion revision to a Git hash using Github.
@param tag: name of the Subversion repo on Github
@param rev: Subversion revision identifier
@return: the git hash
@rtype: str
"""
from pywikibot.comms import http
uri = 'https://github.com/wikimedia/%s/!svn/vcc/default' % tag
request = http.fetch(uri=uri, method='PROPFIND',
body="<?xml version='1.0' encoding='utf-8'?>"
"<propfind xmlns=\"DAV:\"><allprop/></propfind>",
headers={'label': str(rev),
'user-agent': 'SVN/1.7.5 {pwb}'})
dom = xml.dom.minidom.parse(BytesIO(request.raw))
hsh = dom.getElementsByTagName("C:git-commit")[0].firstChild.nodeValue
date = dom.getElementsByTagName("S:date")[0].firstChild.nodeValue
date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')
return hsh, date
def getversion_svn_setuptools(path=None):
"""Get version info for a Subversion checkout using setuptools.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
- hash (git hash for the Subversion revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
if isinstance(svn_utils, Exception):
raise svn_utils
tag = 'pywikibot-core'
_program_dir = path or _get_program_dir()
svninfo = svn_utils.SvnInfo(_program_dir)
rev = svninfo.get_revision()
if not isinstance(rev, int):
raise TypeError('SvnInfo.get_revision() returned type %s' % type(rev))
if rev < 0:
raise ValueError('SvnInfo.get_revision() returned %d' % rev)
if rev == 0:
raise ParseError('SvnInfo: invalid workarea')
hsh, date = github_svn_rev2hash(tag, rev)
rev = 's%s' % rev
return (tag, rev, date, hsh)
@deprecated('getversion_svn_setuptools')
def getversion_svn(path=None):
"""Get version info for a Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
- hash (git hash for the Subversion revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
_program_dir = path or _get_program_dir()
tag, rev, date = svn_rev_info(_program_dir)
hsh, date2 = github_svn_rev2hash(tag, rev)
if date.tm_isdst >= 0 and date2.tm_isdst >= 0:
assert date == date2, 'Date of version is not consistent'
# date.tm_isdst is -1 means unknown state
# compare its contents except daylight saving time status
else:
for i in range(date.n_fields - 1):
assert date[i] == date2[i], 'Date of version is not consistent'
rev = 's%s' % rev
if (not date or not tag or not rev) and not path:
raise ParseError
return (tag, rev, date, hsh)
def getversion_git(path=None):
"""Get version info for a Git clone.
@param path: directory of the Git checkout
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
_program_dir = path or _get_program_dir()
cmd = 'git'
try:
subprocess.Popen([cmd], stdout=subprocess.PIPE).communicate()
except OSError:
# some windows git versions provide git.cmd instead of git.exe
cmd = 'git.cmd'
with open(os.path.join(_program_dir, '.git/config'), 'r') as f:
tag = f.read()
# Try 'origin' and then 'gerrit' as remote name; bail if can't find either.
remote_pos = tag.find('[remote "origin"]')
if remote_pos == -1:
remote_pos = tag.find('[remote "gerrit"]')
if remote_pos == -1:
tag = '?'
else:
s = tag.find('url = ', remote_pos)
e = tag.find('\n', s)
tag = tag[(s + 6):e]
t = tag.strip().split('/')
tag = '[%s] %s' % (t[0][:-1], '-'.join(t[3:]))
with subprocess.Popen([cmd, '--no-pager',
'log', '-1',
'--pretty=format:"%ad|%an|%h|%H|%d"'
'--abbrev-commit',
'--date=iso'],
cwd=_program_dir,
stdout=subprocess.PIPE).stdout as stdout:
info = stdout.read()
info = info.decode(config.console_encoding).split('|')
date = info[0][:-6]
date = time.strptime(date.strip('"'), '%Y-%m-%d %H:%M:%S')
with subprocess.Popen([cmd, 'rev-list', 'HEAD'],
cwd=_program_dir,
stdout=subprocess.PIPE).stdout as stdout:
rev = stdout.read()
rev = 'g%s' % len(rev.splitlines())
hsh = info[3] # also stored in '.git/refs/heads/master'
if (not date or not tag or not rev) and not path:
raise ParseError
return (tag, rev, date, hsh)
def getversion_nightly(path=None):
"""Get version info for a nightly release.
@param path: directory of the uncompressed nightly.
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
if not path:
path = _get_program_dir()
with open(os.path.join(path, 'version')) as data:
(tag, rev, date, hsh) = data.readlines()
date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')
if not date or not tag or not rev:
raise ParseError
return (tag, rev, date, hsh)
def getversion_package(path=None): # pylint: disable=unused-argument
"""Get version info for an installed package.
@param path: Unused argument
@return:
- tag: 'pywikibot/__init__.py'
- rev: '-1 (unknown)'
- date (date the package was installed locally),
- hash (git hash for the current revision of 'pywikibot/__init__.py')
@rtype: C{tuple} of four C{str}
"""
hsh = get_module_version(pywikibot)
date = get_module_mtime(pywikibot).timetuple()
tag = 'pywikibot/__init__.py'
rev = '-1 (unknown)'
return (tag, rev, date, hsh)
def getversion_onlinerepo(repo=None):
"""Retrieve current framework revision number from online repository.
@param repo: (optional) Online repository location
@type repo: URL or string
"""
from pywikibot.comms import http
url = repo or 'https://git.wikimedia.org/feed/pywikibot/core'
buf = http.fetch(uri=url,
headers={'user-agent': '{pwb}'}).content.splitlines()
try:
hsh = buf[13].split('/')[5][:-1]
return hsh
except Exception as e:
raise ParseError(repr(e) + ' while parsing ' + repr(buf))
@deprecated('get_module_version, get_module_filename and get_module_mtime')
def getfileversion(filename):
"""Retrieve revision number of file.
Extracts __version__ variable containing Id tag, without importing it.
(thus can be done for any file)
The version variable containing the Id tag is read and
returned. Because it doesn't import it, the version can
be retrieved from any file.
@param filename: Name of the file to get version
@type filename: string
"""
_program_dir = _get_program_dir()
__version__ = None
mtime = None
fn = os.path.join(_program_dir, filename)
if os.path.exists(fn):
with codecs.open(fn, 'r', "utf-8") as f:
for line in f.readlines():
if line.find('__version__') == 0:
try:
exec(line)
except:
pass
break
stat = os.stat(fn)
mtime = datetime.datetime.fromtimestamp(stat.st_mtime).isoformat(' ')
if mtime and __version__:
return u'%s %s %s' % (filename, __version__[5:-1][:7], mtime)
else:
return None
def get_module_version(module):
"""
Retrieve __version__ variable from an imported module.
| @param module: The module instance.
@type module: module
@return: The version hash without the surrounding text. If not present None.
@rtype: str or None
"""
if hasattr(module, '__version__'):
return module.__version__[5:-1]
def get_module_filename(module):
"""
Retrieve filename from an imported pywikibot module.
It uses the __file__ attribute of the module. If it's file extension ends
with py and another character the last character is discarded when the py
file exist.
@param module: The module instance.
@type module: module
@return: The filename if it's a pywikibot module otherwise None.
@rtype: str or None
"""
if hasattr(module, '__file__') and os.path.exists(module.__file__):
filename = module.__file__
if filename[-4:-1] == '.py' and os.path.exists(filename[:-1]):
filename = filename[:-1]
program_dir = _get_program_dir()
if filename[:len(program_dir)] == program_dir:
return filename
def get_module_mtime(module):
"""
Retrieve the modification time from an imported module.
@param module: The module instance.
@type module: module
@return: The modification time if it's a pywikibot module otherwise None.
@rtype: datetime or None
"""
filename = get_module_filename(module)
if filename:
return datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
def package_versions(modules=None, builtins=False, standard_lib=None):
"""Retrieve package version information.
When builtins or standard_lib are None, they will be included only
if a version was found in the package.
@param modules: Modules to inspect
@type modules: list of strings
@param builtins: Include builtins
@type builtins: Boolean, or None for automatic selection
@param standard_lib: Include standard library packages
@type standard_lib: Boolean, or None for automatic selection
"""
if not modules:
modules = sys.modules.keys()
std_lib_dir = get_python_lib(standard_lib=True)
root_packages = set([key.split('.')[0]
for key in modules])
builtin_packages = set([name.split('.')[0] for name in root_packages
if name in sys.builtin_module_names or
'_' + name in sys.builtin_module_names])
# Improve performance by removing builtins from the list if possible.
if builtins is False:
root_packages = list(root_packages - builtin_packages)
std_lib_packages = []
paths = {}
data = {}
for name in root_packages:
try:
package = __import__(name, level=0)
except Exception as e:
data[name] = {'name': name, 'err': e}
continue
info = {'package': package, 'name': name}
if name in builtin_packages:
info['type'] = 'builtins'
if '__file__' in package.__dict__:
# Determine if this file part is of the standard library.
if os.path.normcase(package.__file__).startswith(
os.path.normcase(std_lib_dir)):
std_lib_packages.append(name)
if standard_lib is False:
continue
info['type'] = 'standard libary'
# Strip '__init__.py' from the filename.
path = package.__file__
if '__init__.py' in path:
path = path[0:path.index('__init__.py')]
if PY2:
path = path.decode(sys.getfilesystemencoding())
info['path'] = path
assert path not in paths, 'Path of the package is in defined paths'
paths[path] = name
if '__version__' in package.__dict__:
info['ver'] = package.__version__
elif name.startswith('unicodedata'):
info['ver'] = package.unidata_version
# If builtins or standard_lib is None,
# only include package if a version was found.
if (builtins is None and name in builtin_packages) or \
(standard_lib is None and name in std_lib_packages):
if 'ver' in info:
data[name] = info
else:
# Remove the entry from paths, so it isnt processed below
del paths[info['path']]
else:
data[name] = info
# Remove any pywikibot sub-modules which were loaded as a package.
# e.g. 'wikipedia_family.py' is loaded as 'wikipedia'
_program_dir = _get_program_dir()
for path, name in paths.items():
if _program_dir in path:
del data[name]
return data | random_line_split | |
version.py | # -*- coding: utf-8 -*-
"""Module to determine the pywikibot version (tag, revision and date)."""
#
# (C) Merlijn 'valhallasw' van Deen, 2007-2014
# (C) xqt, 2010-2015
# (C) Pywikibot team, 2007-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import codecs
import datetime
import os
import subprocess
import sys
import time
import xml.dom.minidom
from distutils.sysconfig import get_python_lib
from io import BytesIO
from warnings import warn
try:
from setuptools import svn_utils
except ImportError:
try:
from setuptools_svn import svn_utils
except ImportError as e:
svn_utils = e
import pywikibot
from pywikibot import config2 as config
from pywikibot.tools import deprecated, PY2
if not PY2:
basestring = (str, )
cache = None
_logger = 'version'
class ParseError(Exception):
"""Parsing went wrong."""
def _get_program_dir():
_program_dir = os.path.normpath(os.path.split(os.path.dirname(__file__))[0])
return _program_dir
def getversion(online=True):
"""Return a pywikibot version string.
@param online: (optional) Include information obtained online
"""
data = dict(getversiondict()) # copy dict to prevent changes in 'cache'
data['cmp_ver'] = 'n/a'
if online:
try:
hsh2 = getversion_onlinerepo()
hsh1 = data['hsh']
data['cmp_ver'] = 'OUTDATED' if hsh1 != hsh2 else 'ok'
except Exception:
pass
data['hsh'] = data['hsh'][:7] # make short hash from full hash
return '%(tag)s (%(hsh)s, %(rev)s, %(date)s, %(cmp_ver)s)' % data
def getversiondict():
"""Get version info for the package.
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{dict} of four C{str}
"""
global cache
if cache:
return cache
_program_dir = _get_program_dir()
exceptions = {}
for vcs_func in (getversion_git,
getversion_svn_setuptools,
getversion_nightly,
getversion_svn,
getversion_package):
try:
(tag, rev, date, hsh) = vcs_func(_program_dir)
except Exception as e:
exceptions[vcs_func] = e
else:
break
else:
# nothing worked; version unknown (but suppress exceptions)
# the value is most likely '$Id' + '$', it means that
# pywikibot was imported without using version control at all.
tag, rev, date, hsh = (
'', '-1 (unknown)', '0 (unknown)', '(unknown)')
# git and svn can silently fail, as it may be a nightly.
if getversion_package in exceptions:
warn('Unable to detect version; exceptions raised:\n%r'
% exceptions, UserWarning)
elif exceptions:
pywikibot.debug('version algorithm exceptions:\n%r'
% exceptions, _logger)
if isinstance(date, basestring):
datestring = date
elif isinstance(date, time.struct_time):
datestring = time.strftime('%Y/%m/%d, %H:%M:%S', date)
else:
warn('Unable to detect package date', UserWarning)
datestring = '-2 (unknown)'
cache = dict(tag=tag, rev=rev, date=datestring, hsh=hsh)
return cache
@deprecated('getversion_svn_setuptools')
def svn_rev_info(path):
"""Fetch information about the current revision of an Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
@rtype: C{tuple} of two C{str} and a C{time.struct_time}
"""
if not os.path.isdir(os.path.join(path, '.svn')):
path = os.path.join(path, '..')
_program_dir = path
filename = os.path.join(_program_dir, '.svn/entries')
if os.path.isfile(filename):
with open(filename) as entries:
version = entries.readline().strip()
if version != '12':
for i in range(3):
entries.readline()
tag = entries.readline().strip()
t = tag.split('://')
t[1] = t[1].replace('svn.wikimedia.org/svnroot/pywikipedia/',
'')
tag = '[%s] %s' % (t[0], t[1])
for i in range(4):
entries.readline()
date = time.strptime(entries.readline()[:19],
'%Y-%m-%dT%H:%M:%S')
rev = entries.readline()[:-1]
return tag, rev, date
# We haven't found the information in entries file.
# Use sqlite table for new entries format
from sqlite3 import dbapi2 as sqlite
con = sqlite.connect(os.path.join(_program_dir, ".svn/wc.db"))
cur = con.cursor()
cur.execute("""select
local_relpath, repos_path, revision, changed_date, checksum from nodes
order by revision desc, changed_date desc""")
name, tag, rev, date, checksum = cur.fetchone()
cur.execute("select root from repository")
tag, = cur.fetchone()
con.close()
tag = os.path.split(tag)[1]
date = time.gmtime(date / 1000000)
return tag, rev, date
def github_svn_rev2hash(tag, rev):
"""Convert a Subversion revision to a Git hash using Github.
@param tag: name of the Subversion repo on Github
@param rev: Subversion revision identifier
@return: the git hash
@rtype: str
"""
from pywikibot.comms import http
uri = 'https://github.com/wikimedia/%s/!svn/vcc/default' % tag
request = http.fetch(uri=uri, method='PROPFIND',
body="<?xml version='1.0' encoding='utf-8'?>"
"<propfind xmlns=\"DAV:\"><allprop/></propfind>",
headers={'label': str(rev),
'user-agent': 'SVN/1.7.5 {pwb}'})
dom = xml.dom.minidom.parse(BytesIO(request.raw))
hsh = dom.getElementsByTagName("C:git-commit")[0].firstChild.nodeValue
date = dom.getElementsByTagName("S:date")[0].firstChild.nodeValue
date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')
return hsh, date
def getversion_svn_setuptools(path=None):
"""Get version info for a Subversion checkout using setuptools.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
- hash (git hash for the Subversion revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
if isinstance(svn_utils, Exception):
raise svn_utils
tag = 'pywikibot-core'
_program_dir = path or _get_program_dir()
svninfo = svn_utils.SvnInfo(_program_dir)
rev = svninfo.get_revision()
if not isinstance(rev, int):
raise TypeError('SvnInfo.get_revision() returned type %s' % type(rev))
if rev < 0:
raise ValueError('SvnInfo.get_revision() returned %d' % rev)
if rev == 0:
raise ParseError('SvnInfo: invalid workarea')
hsh, date = github_svn_rev2hash(tag, rev)
rev = 's%s' % rev
return (tag, rev, date, hsh)
@deprecated('getversion_svn_setuptools')
def getversion_svn(path=None):
"""Get version info for a Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
- hash (git hash for the Subversion revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
_program_dir = path or _get_program_dir()
tag, rev, date = svn_rev_info(_program_dir)
hsh, date2 = github_svn_rev2hash(tag, rev)
if date.tm_isdst >= 0 and date2.tm_isdst >= 0:
assert date == date2, 'Date of version is not consistent'
# date.tm_isdst is -1 means unknown state
# compare its contents except daylight saving time status
else:
for i in range(date.n_fields - 1):
assert date[i] == date2[i], 'Date of version is not consistent'
rev = 's%s' % rev
if (not date or not tag or not rev) and not path:
raise ParseError
return (tag, rev, date, hsh)
def getversion_git(path=None):
"""Get version info for a Git clone.
@param path: directory of the Git checkout
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
_program_dir = path or _get_program_dir()
cmd = 'git'
try:
subprocess.Popen([cmd], stdout=subprocess.PIPE).communicate()
except OSError:
# some windows git versions provide git.cmd instead of git.exe
cmd = 'git.cmd'
with open(os.path.join(_program_dir, '.git/config'), 'r') as f:
tag = f.read()
# Try 'origin' and then 'gerrit' as remote name; bail if can't find either.
remote_pos = tag.find('[remote "origin"]')
if remote_pos == -1:
remote_pos = tag.find('[remote "gerrit"]')
if remote_pos == -1:
tag = '?'
else:
s = tag.find('url = ', remote_pos)
e = tag.find('\n', s)
tag = tag[(s + 6):e]
t = tag.strip().split('/')
tag = '[%s] %s' % (t[0][:-1], '-'.join(t[3:]))
with subprocess.Popen([cmd, '--no-pager',
'log', '-1',
'--pretty=format:"%ad|%an|%h|%H|%d"'
'--abbrev-commit',
'--date=iso'],
cwd=_program_dir,
stdout=subprocess.PIPE).stdout as stdout:
info = stdout.read()
info = info.decode(config.console_encoding).split('|')
date = info[0][:-6]
date = time.strptime(date.strip('"'), '%Y-%m-%d %H:%M:%S')
with subprocess.Popen([cmd, 'rev-list', 'HEAD'],
cwd=_program_dir,
stdout=subprocess.PIPE).stdout as stdout:
rev = stdout.read()
rev = 'g%s' % len(rev.splitlines())
hsh = info[3] # also stored in '.git/refs/heads/master'
if (not date or not tag or not rev) and not path:
raise ParseError
return (tag, rev, date, hsh)
def getversion_nightly(path=None):
"""Get version info for a nightly release.
@param path: directory of the uncompressed nightly.
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
if not path:
path = _get_program_dir()
with open(os.path.join(path, 'version')) as data:
(tag, rev, date, hsh) = data.readlines()
date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')
if not date or not tag or not rev:
raise ParseError
return (tag, rev, date, hsh)
def getversion_package(path=None): # pylint: disable=unused-argument
"""Get version info for an installed package.
@param path: Unused argument
@return:
- tag: 'pywikibot/__init__.py'
- rev: '-1 (unknown)'
- date (date the package was installed locally),
- hash (git hash for the current revision of 'pywikibot/__init__.py')
@rtype: C{tuple} of four C{str}
"""
hsh = get_module_version(pywikibot)
date = get_module_mtime(pywikibot).timetuple()
tag = 'pywikibot/__init__.py'
rev = '-1 (unknown)'
return (tag, rev, date, hsh)
def getversion_onlinerepo(repo=None):
"""Retrieve current framework revision number from online repository.
@param repo: (optional) Online repository location
@type repo: URL or string
"""
from pywikibot.comms import http
url = repo or 'https://git.wikimedia.org/feed/pywikibot/core'
buf = http.fetch(uri=url,
headers={'user-agent': '{pwb}'}).content.splitlines()
try:
hsh = buf[13].split('/')[5][:-1]
return hsh
except Exception as e:
raise ParseError(repr(e) + ' while parsing ' + repr(buf))
@deprecated('get_module_version, get_module_filename and get_module_mtime')
def | (filename):
"""Retrieve revision number of file.
Extracts __version__ variable containing Id tag, without importing it.
(thus can be done for any file)
The version variable containing the Id tag is read and
returned. Because it doesn't import it, the version can
be retrieved from any file.
@param filename: Name of the file to get version
@type filename: string
"""
_program_dir = _get_program_dir()
__version__ = None
mtime = None
fn = os.path.join(_program_dir, filename)
if os.path.exists(fn):
with codecs.open(fn, 'r', "utf-8") as f:
for line in f.readlines():
if line.find('__version__') == 0:
try:
exec(line)
except:
pass
break
stat = os.stat(fn)
mtime = datetime.datetime.fromtimestamp(stat.st_mtime).isoformat(' ')
if mtime and __version__:
return u'%s %s %s' % (filename, __version__[5:-1][:7], mtime)
else:
return None
def get_module_version(module):
"""
Retrieve __version__ variable from an imported module.
@param module: The module instance.
@type module: module
@return: The version hash without the surrounding text. If not present None.
@rtype: str or None
"""
if hasattr(module, '__version__'):
return module.__version__[5:-1]
def get_module_filename(module):
"""
Retrieve filename from an imported pywikibot module.
It uses the __file__ attribute of the module. If it's file extension ends
with py and another character the last character is discarded when the py
file exist.
@param module: The module instance.
@type module: module
@return: The filename if it's a pywikibot module otherwise None.
@rtype: str or None
"""
if hasattr(module, '__file__') and os.path.exists(module.__file__):
filename = module.__file__
if filename[-4:-1] == '.py' and os.path.exists(filename[:-1]):
filename = filename[:-1]
program_dir = _get_program_dir()
if filename[:len(program_dir)] == program_dir:
return filename
def get_module_mtime(module):
"""
Retrieve the modification time from an imported module.
@param module: The module instance.
@type module: module
@return: The modification time if it's a pywikibot module otherwise None.
@rtype: datetime or None
"""
filename = get_module_filename(module)
if filename:
return datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
def package_versions(modules=None, builtins=False, standard_lib=None):
"""Retrieve package version information.
When builtins or standard_lib are None, they will be included only
if a version was found in the package.
@param modules: Modules to inspect
@type modules: list of strings
@param builtins: Include builtins
@type builtins: Boolean, or None for automatic selection
@param standard_lib: Include standard library packages
@type standard_lib: Boolean, or None for automatic selection
"""
if not modules:
modules = sys.modules.keys()
std_lib_dir = get_python_lib(standard_lib=True)
root_packages = set([key.split('.')[0]
for key in modules])
builtin_packages = set([name.split('.')[0] for name in root_packages
if name in sys.builtin_module_names or
'_' + name in sys.builtin_module_names])
# Improve performance by removing builtins from the list if possible.
if builtins is False:
root_packages = list(root_packages - builtin_packages)
std_lib_packages = []
paths = {}
data = {}
for name in root_packages:
try:
package = __import__(name, level=0)
except Exception as e:
data[name] = {'name': name, 'err': e}
continue
info = {'package': package, 'name': name}
if name in builtin_packages:
info['type'] = 'builtins'
if '__file__' in package.__dict__:
# Determine if this file part is of the standard library.
if os.path.normcase(package.__file__).startswith(
os.path.normcase(std_lib_dir)):
std_lib_packages.append(name)
if standard_lib is False:
continue
info['type'] = 'standard libary'
# Strip '__init__.py' from the filename.
path = package.__file__
if '__init__.py' in path:
path = path[0:path.index('__init__.py')]
if PY2:
path = path.decode(sys.getfilesystemencoding())
info['path'] = path
assert path not in paths, 'Path of the package is in defined paths'
paths[path] = name
if '__version__' in package.__dict__:
info['ver'] = package.__version__
elif name.startswith('unicodedata'):
info['ver'] = package.unidata_version
# If builtins or standard_lib is None,
# only include package if a version was found.
if (builtins is None and name in builtin_packages) or \
(standard_lib is None and name in std_lib_packages):
if 'ver' in info:
data[name] = info
else:
# Remove the entry from paths, so it isnt processed below
del paths[info['path']]
else:
data[name] = info
# Remove any pywikibot sub-modules which were loaded as a package.
# e.g. 'wikipedia_family.py' is loaded as 'wikipedia'
_program_dir = _get_program_dir()
for path, name in paths.items():
if _program_dir in path:
del data[name]
return data
| getfileversion | identifier_name |
version.py | # -*- coding: utf-8 -*-
"""Module to determine the pywikibot version (tag, revision and date)."""
#
# (C) Merlijn 'valhallasw' van Deen, 2007-2014
# (C) xqt, 2010-2015
# (C) Pywikibot team, 2007-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import codecs
import datetime
import os
import subprocess
import sys
import time
import xml.dom.minidom
from distutils.sysconfig import get_python_lib
from io import BytesIO
from warnings import warn
try:
from setuptools import svn_utils
except ImportError:
try:
from setuptools_svn import svn_utils
except ImportError as e:
svn_utils = e
import pywikibot
from pywikibot import config2 as config
from pywikibot.tools import deprecated, PY2
if not PY2:
basestring = (str, )
cache = None
_logger = 'version'
class ParseError(Exception):
"""Parsing went wrong."""
def _get_program_dir():
_program_dir = os.path.normpath(os.path.split(os.path.dirname(__file__))[0])
return _program_dir
def getversion(online=True):
"""Return a pywikibot version string.
@param online: (optional) Include information obtained online
"""
data = dict(getversiondict()) # copy dict to prevent changes in 'cache'
data['cmp_ver'] = 'n/a'
if online:
try:
hsh2 = getversion_onlinerepo()
hsh1 = data['hsh']
data['cmp_ver'] = 'OUTDATED' if hsh1 != hsh2 else 'ok'
except Exception:
pass
data['hsh'] = data['hsh'][:7] # make short hash from full hash
return '%(tag)s (%(hsh)s, %(rev)s, %(date)s, %(cmp_ver)s)' % data
def getversiondict():
"""Get version info for the package.
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{dict} of four C{str}
"""
global cache
if cache:
return cache
_program_dir = _get_program_dir()
exceptions = {}
for vcs_func in (getversion_git,
getversion_svn_setuptools,
getversion_nightly,
getversion_svn,
getversion_package):
try:
(tag, rev, date, hsh) = vcs_func(_program_dir)
except Exception as e:
exceptions[vcs_func] = e
else:
break
else:
# nothing worked; version unknown (but suppress exceptions)
# the value is most likely '$Id' + '$', it means that
# pywikibot was imported without using version control at all.
tag, rev, date, hsh = (
'', '-1 (unknown)', '0 (unknown)', '(unknown)')
# git and svn can silently fail, as it may be a nightly.
if getversion_package in exceptions:
warn('Unable to detect version; exceptions raised:\n%r'
% exceptions, UserWarning)
elif exceptions:
pywikibot.debug('version algorithm exceptions:\n%r'
% exceptions, _logger)
if isinstance(date, basestring):
datestring = date
elif isinstance(date, time.struct_time):
datestring = time.strftime('%Y/%m/%d, %H:%M:%S', date)
else:
warn('Unable to detect package date', UserWarning)
datestring = '-2 (unknown)'
cache = dict(tag=tag, rev=rev, date=datestring, hsh=hsh)
return cache
@deprecated('getversion_svn_setuptools')
def svn_rev_info(path):
"""Fetch information about the current revision of an Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
@rtype: C{tuple} of two C{str} and a C{time.struct_time}
"""
if not os.path.isdir(os.path.join(path, '.svn')):
path = os.path.join(path, '..')
_program_dir = path
filename = os.path.join(_program_dir, '.svn/entries')
if os.path.isfile(filename):
with open(filename) as entries:
version = entries.readline().strip()
if version != '12':
for i in range(3):
entries.readline()
tag = entries.readline().strip()
t = tag.split('://')
t[1] = t[1].replace('svn.wikimedia.org/svnroot/pywikipedia/',
'')
tag = '[%s] %s' % (t[0], t[1])
for i in range(4):
entries.readline()
date = time.strptime(entries.readline()[:19],
'%Y-%m-%dT%H:%M:%S')
rev = entries.readline()[:-1]
return tag, rev, date
# We haven't found the information in entries file.
# Use sqlite table for new entries format
from sqlite3 import dbapi2 as sqlite
con = sqlite.connect(os.path.join(_program_dir, ".svn/wc.db"))
cur = con.cursor()
cur.execute("""select
local_relpath, repos_path, revision, changed_date, checksum from nodes
order by revision desc, changed_date desc""")
name, tag, rev, date, checksum = cur.fetchone()
cur.execute("select root from repository")
tag, = cur.fetchone()
con.close()
tag = os.path.split(tag)[1]
date = time.gmtime(date / 1000000)
return tag, rev, date
def github_svn_rev2hash(tag, rev):
"""Convert a Subversion revision to a Git hash using Github.
@param tag: name of the Subversion repo on Github
@param rev: Subversion revision identifier
@return: the git hash
@rtype: str
"""
from pywikibot.comms import http
uri = 'https://github.com/wikimedia/%s/!svn/vcc/default' % tag
request = http.fetch(uri=uri, method='PROPFIND',
body="<?xml version='1.0' encoding='utf-8'?>"
"<propfind xmlns=\"DAV:\"><allprop/></propfind>",
headers={'label': str(rev),
'user-agent': 'SVN/1.7.5 {pwb}'})
dom = xml.dom.minidom.parse(BytesIO(request.raw))
hsh = dom.getElementsByTagName("C:git-commit")[0].firstChild.nodeValue
date = dom.getElementsByTagName("S:date")[0].firstChild.nodeValue
date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')
return hsh, date
def getversion_svn_setuptools(path=None):
"""Get version info for a Subversion checkout using setuptools.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
- hash (git hash for the Subversion revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
if isinstance(svn_utils, Exception):
raise svn_utils
tag = 'pywikibot-core'
_program_dir = path or _get_program_dir()
svninfo = svn_utils.SvnInfo(_program_dir)
rev = svninfo.get_revision()
if not isinstance(rev, int):
raise TypeError('SvnInfo.get_revision() returned type %s' % type(rev))
if rev < 0:
raise ValueError('SvnInfo.get_revision() returned %d' % rev)
if rev == 0:
raise ParseError('SvnInfo: invalid workarea')
hsh, date = github_svn_rev2hash(tag, rev)
rev = 's%s' % rev
return (tag, rev, date, hsh)
@deprecated('getversion_svn_setuptools')
def getversion_svn(path=None):
"""Get version info for a Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
- hash (git hash for the Subversion revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
_program_dir = path or _get_program_dir()
tag, rev, date = svn_rev_info(_program_dir)
hsh, date2 = github_svn_rev2hash(tag, rev)
if date.tm_isdst >= 0 and date2.tm_isdst >= 0:
assert date == date2, 'Date of version is not consistent'
# date.tm_isdst is -1 means unknown state
# compare its contents except daylight saving time status
else:
for i in range(date.n_fields - 1):
assert date[i] == date2[i], 'Date of version is not consistent'
rev = 's%s' % rev
if (not date or not tag or not rev) and not path:
raise ParseError
return (tag, rev, date, hsh)
def getversion_git(path=None):
|
def getversion_nightly(path=None):
"""Get version info for a nightly release.
@param path: directory of the uncompressed nightly.
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
if not path:
path = _get_program_dir()
with open(os.path.join(path, 'version')) as data:
(tag, rev, date, hsh) = data.readlines()
date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')
if not date or not tag or not rev:
raise ParseError
return (tag, rev, date, hsh)
def getversion_package(path=None): # pylint: disable=unused-argument
"""Get version info for an installed package.
@param path: Unused argument
@return:
- tag: 'pywikibot/__init__.py'
- rev: '-1 (unknown)'
- date (date the package was installed locally),
- hash (git hash for the current revision of 'pywikibot/__init__.py')
@rtype: C{tuple} of four C{str}
"""
hsh = get_module_version(pywikibot)
date = get_module_mtime(pywikibot).timetuple()
tag = 'pywikibot/__init__.py'
rev = '-1 (unknown)'
return (tag, rev, date, hsh)
def getversion_onlinerepo(repo=None):
"""Retrieve current framework revision number from online repository.
@param repo: (optional) Online repository location
@type repo: URL or string
"""
from pywikibot.comms import http
url = repo or 'https://git.wikimedia.org/feed/pywikibot/core'
buf = http.fetch(uri=url,
headers={'user-agent': '{pwb}'}).content.splitlines()
try:
hsh = buf[13].split('/')[5][:-1]
return hsh
except Exception as e:
raise ParseError(repr(e) + ' while parsing ' + repr(buf))
@deprecated('get_module_version, get_module_filename and get_module_mtime')
def getfileversion(filename):
"""Retrieve revision number of file.
Extracts __version__ variable containing Id tag, without importing it.
(thus can be done for any file)
The version variable containing the Id tag is read and
returned. Because it doesn't import it, the version can
be retrieved from any file.
@param filename: Name of the file to get version
@type filename: string
"""
_program_dir = _get_program_dir()
__version__ = None
mtime = None
fn = os.path.join(_program_dir, filename)
if os.path.exists(fn):
with codecs.open(fn, 'r', "utf-8") as f:
for line in f.readlines():
if line.find('__version__') == 0:
try:
exec(line)
except:
pass
break
stat = os.stat(fn)
mtime = datetime.datetime.fromtimestamp(stat.st_mtime).isoformat(' ')
if mtime and __version__:
return u'%s %s %s' % (filename, __version__[5:-1][:7], mtime)
else:
return None
def get_module_version(module):
"""
Retrieve __version__ variable from an imported module.
@param module: The module instance.
@type module: module
@return: The version hash without the surrounding text. If not present None.
@rtype: str or None
"""
if hasattr(module, '__version__'):
return module.__version__[5:-1]
def get_module_filename(module):
"""
Retrieve filename from an imported pywikibot module.
It uses the __file__ attribute of the module. If it's file extension ends
with py and another character the last character is discarded when the py
file exist.
@param module: The module instance.
@type module: module
@return: The filename if it's a pywikibot module otherwise None.
@rtype: str or None
"""
if hasattr(module, '__file__') and os.path.exists(module.__file__):
filename = module.__file__
if filename[-4:-1] == '.py' and os.path.exists(filename[:-1]):
filename = filename[:-1]
program_dir = _get_program_dir()
if filename[:len(program_dir)] == program_dir:
return filename
def get_module_mtime(module):
"""
Retrieve the modification time from an imported module.
@param module: The module instance.
@type module: module
@return: The modification time if it's a pywikibot module otherwise None.
@rtype: datetime or None
"""
filename = get_module_filename(module)
if filename:
return datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
def package_versions(modules=None, builtins=False, standard_lib=None):
"""Retrieve package version information.
When builtins or standard_lib are None, they will be included only
if a version was found in the package.
@param modules: Modules to inspect
@type modules: list of strings
@param builtins: Include builtins
@type builtins: Boolean, or None for automatic selection
@param standard_lib: Include standard library packages
@type standard_lib: Boolean, or None for automatic selection
"""
if not modules:
modules = sys.modules.keys()
std_lib_dir = get_python_lib(standard_lib=True)
root_packages = set([key.split('.')[0]
for key in modules])
builtin_packages = set([name.split('.')[0] for name in root_packages
if name in sys.builtin_module_names or
'_' + name in sys.builtin_module_names])
# Improve performance by removing builtins from the list if possible.
if builtins is False:
root_packages = list(root_packages - builtin_packages)
std_lib_packages = []
paths = {}
data = {}
for name in root_packages:
try:
package = __import__(name, level=0)
except Exception as e:
data[name] = {'name': name, 'err': e}
continue
info = {'package': package, 'name': name}
if name in builtin_packages:
info['type'] = 'builtins'
if '__file__' in package.__dict__:
# Determine if this file part is of the standard library.
if os.path.normcase(package.__file__).startswith(
os.path.normcase(std_lib_dir)):
std_lib_packages.append(name)
if standard_lib is False:
continue
info['type'] = 'standard libary'
# Strip '__init__.py' from the filename.
path = package.__file__
if '__init__.py' in path:
path = path[0:path.index('__init__.py')]
if PY2:
path = path.decode(sys.getfilesystemencoding())
info['path'] = path
assert path not in paths, 'Path of the package is in defined paths'
paths[path] = name
if '__version__' in package.__dict__:
info['ver'] = package.__version__
elif name.startswith('unicodedata'):
info['ver'] = package.unidata_version
# If builtins or standard_lib is None,
# only include package if a version was found.
if (builtins is None and name in builtin_packages) or \
(standard_lib is None and name in std_lib_packages):
if 'ver' in info:
data[name] = info
else:
# Remove the entry from paths, so it isnt processed below
del paths[info['path']]
else:
data[name] = info
# Remove any pywikibot sub-modules which were loaded as a package.
# e.g. 'wikipedia_family.py' is loaded as 'wikipedia'
_program_dir = _get_program_dir()
for path, name in paths.items():
if _program_dir in path:
del data[name]
return data
| """Get version info for a Git clone.
@param path: directory of the Git checkout
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
_program_dir = path or _get_program_dir()
cmd = 'git'
try:
subprocess.Popen([cmd], stdout=subprocess.PIPE).communicate()
except OSError:
# some windows git versions provide git.cmd instead of git.exe
cmd = 'git.cmd'
with open(os.path.join(_program_dir, '.git/config'), 'r') as f:
tag = f.read()
# Try 'origin' and then 'gerrit' as remote name; bail if can't find either.
remote_pos = tag.find('[remote "origin"]')
if remote_pos == -1:
remote_pos = tag.find('[remote "gerrit"]')
if remote_pos == -1:
tag = '?'
else:
s = tag.find('url = ', remote_pos)
e = tag.find('\n', s)
tag = tag[(s + 6):e]
t = tag.strip().split('/')
tag = '[%s] %s' % (t[0][:-1], '-'.join(t[3:]))
with subprocess.Popen([cmd, '--no-pager',
'log', '-1',
'--pretty=format:"%ad|%an|%h|%H|%d"'
'--abbrev-commit',
'--date=iso'],
cwd=_program_dir,
stdout=subprocess.PIPE).stdout as stdout:
info = stdout.read()
info = info.decode(config.console_encoding).split('|')
date = info[0][:-6]
date = time.strptime(date.strip('"'), '%Y-%m-%d %H:%M:%S')
with subprocess.Popen([cmd, 'rev-list', 'HEAD'],
cwd=_program_dir,
stdout=subprocess.PIPE).stdout as stdout:
rev = stdout.read()
rev = 'g%s' % len(rev.splitlines())
hsh = info[3] # also stored in '.git/refs/heads/master'
if (not date or not tag or not rev) and not path:
raise ParseError
return (tag, rev, date, hsh) | identifier_body |
version.py | # -*- coding: utf-8 -*-
"""Module to determine the pywikibot version (tag, revision and date)."""
#
# (C) Merlijn 'valhallasw' van Deen, 2007-2014
# (C) xqt, 2010-2015
# (C) Pywikibot team, 2007-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import codecs
import datetime
import os
import subprocess
import sys
import time
import xml.dom.minidom
from distutils.sysconfig import get_python_lib
from io import BytesIO
from warnings import warn
try:
from setuptools import svn_utils
except ImportError:
try:
from setuptools_svn import svn_utils
except ImportError as e:
svn_utils = e
import pywikibot
from pywikibot import config2 as config
from pywikibot.tools import deprecated, PY2
if not PY2:
basestring = (str, )
cache = None
_logger = 'version'
class ParseError(Exception):
"""Parsing went wrong."""
def _get_program_dir():
_program_dir = os.path.normpath(os.path.split(os.path.dirname(__file__))[0])
return _program_dir
def getversion(online=True):
"""Return a pywikibot version string.
@param online: (optional) Include information obtained online
"""
data = dict(getversiondict()) # copy dict to prevent changes in 'cache'
data['cmp_ver'] = 'n/a'
if online:
try:
hsh2 = getversion_onlinerepo()
hsh1 = data['hsh']
data['cmp_ver'] = 'OUTDATED' if hsh1 != hsh2 else 'ok'
except Exception:
pass
data['hsh'] = data['hsh'][:7] # make short hash from full hash
return '%(tag)s (%(hsh)s, %(rev)s, %(date)s, %(cmp_ver)s)' % data
def getversiondict():
"""Get version info for the package.
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{dict} of four C{str}
"""
global cache
if cache:
return cache
_program_dir = _get_program_dir()
exceptions = {}
for vcs_func in (getversion_git,
getversion_svn_setuptools,
getversion_nightly,
getversion_svn,
getversion_package):
try:
(tag, rev, date, hsh) = vcs_func(_program_dir)
except Exception as e:
exceptions[vcs_func] = e
else:
break
else:
# nothing worked; version unknown (but suppress exceptions)
# the value is most likely '$Id' + '$', it means that
# pywikibot was imported without using version control at all.
tag, rev, date, hsh = (
'', '-1 (unknown)', '0 (unknown)', '(unknown)')
# git and svn can silently fail, as it may be a nightly.
if getversion_package in exceptions:
warn('Unable to detect version; exceptions raised:\n%r'
% exceptions, UserWarning)
elif exceptions:
pywikibot.debug('version algorithm exceptions:\n%r'
% exceptions, _logger)
if isinstance(date, basestring):
datestring = date
elif isinstance(date, time.struct_time):
datestring = time.strftime('%Y/%m/%d, %H:%M:%S', date)
else:
warn('Unable to detect package date', UserWarning)
datestring = '-2 (unknown)'
cache = dict(tag=tag, rev=rev, date=datestring, hsh=hsh)
return cache
@deprecated('getversion_svn_setuptools')
def svn_rev_info(path):
"""Fetch information about the current revision of an Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
@rtype: C{tuple} of two C{str} and a C{time.struct_time}
"""
if not os.path.isdir(os.path.join(path, '.svn')):
path = os.path.join(path, '..')
_program_dir = path
filename = os.path.join(_program_dir, '.svn/entries')
if os.path.isfile(filename):
with open(filename) as entries:
version = entries.readline().strip()
if version != '12':
for i in range(3):
entries.readline()
tag = entries.readline().strip()
t = tag.split('://')
t[1] = t[1].replace('svn.wikimedia.org/svnroot/pywikipedia/',
'')
tag = '[%s] %s' % (t[0], t[1])
for i in range(4):
entries.readline()
date = time.strptime(entries.readline()[:19],
'%Y-%m-%dT%H:%M:%S')
rev = entries.readline()[:-1]
return tag, rev, date
# We haven't found the information in entries file.
# Use sqlite table for new entries format
from sqlite3 import dbapi2 as sqlite
con = sqlite.connect(os.path.join(_program_dir, ".svn/wc.db"))
cur = con.cursor()
cur.execute("""select
local_relpath, repos_path, revision, changed_date, checksum from nodes
order by revision desc, changed_date desc""")
name, tag, rev, date, checksum = cur.fetchone()
cur.execute("select root from repository")
tag, = cur.fetchone()
con.close()
tag = os.path.split(tag)[1]
date = time.gmtime(date / 1000000)
return tag, rev, date
def github_svn_rev2hash(tag, rev):
"""Convert a Subversion revision to a Git hash using Github.
@param tag: name of the Subversion repo on Github
@param rev: Subversion revision identifier
@return: the git hash
@rtype: str
"""
from pywikibot.comms import http
uri = 'https://github.com/wikimedia/%s/!svn/vcc/default' % tag
request = http.fetch(uri=uri, method='PROPFIND',
body="<?xml version='1.0' encoding='utf-8'?>"
"<propfind xmlns=\"DAV:\"><allprop/></propfind>",
headers={'label': str(rev),
'user-agent': 'SVN/1.7.5 {pwb}'})
dom = xml.dom.minidom.parse(BytesIO(request.raw))
hsh = dom.getElementsByTagName("C:git-commit")[0].firstChild.nodeValue
date = dom.getElementsByTagName("S:date")[0].firstChild.nodeValue
date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')
return hsh, date
def getversion_svn_setuptools(path=None):
"""Get version info for a Subversion checkout using setuptools.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
- hash (git hash for the Subversion revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
if isinstance(svn_utils, Exception):
raise svn_utils
tag = 'pywikibot-core'
_program_dir = path or _get_program_dir()
svninfo = svn_utils.SvnInfo(_program_dir)
rev = svninfo.get_revision()
if not isinstance(rev, int):
raise TypeError('SvnInfo.get_revision() returned type %s' % type(rev))
if rev < 0:
raise ValueError('SvnInfo.get_revision() returned %d' % rev)
if rev == 0:
raise ParseError('SvnInfo: invalid workarea')
hsh, date = github_svn_rev2hash(tag, rev)
rev = 's%s' % rev
return (tag, rev, date, hsh)
@deprecated('getversion_svn_setuptools')
def getversion_svn(path=None):
"""Get version info for a Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision identifier),
- date (date of current revision),
- hash (git hash for the Subversion revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
_program_dir = path or _get_program_dir()
tag, rev, date = svn_rev_info(_program_dir)
hsh, date2 = github_svn_rev2hash(tag, rev)
if date.tm_isdst >= 0 and date2.tm_isdst >= 0:
assert date == date2, 'Date of version is not consistent'
# date.tm_isdst is -1 means unknown state
# compare its contents except daylight saving time status
else:
for i in range(date.n_fields - 1):
assert date[i] == date2[i], 'Date of version is not consistent'
rev = 's%s' % rev
if (not date or not tag or not rev) and not path:
raise ParseError
return (tag, rev, date, hsh)
def getversion_git(path=None):
"""Get version info for a Git clone.
@param path: directory of the Git checkout
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
_program_dir = path or _get_program_dir()
cmd = 'git'
try:
subprocess.Popen([cmd], stdout=subprocess.PIPE).communicate()
except OSError:
# some windows git versions provide git.cmd instead of git.exe
cmd = 'git.cmd'
with open(os.path.join(_program_dir, '.git/config'), 'r') as f:
tag = f.read()
# Try 'origin' and then 'gerrit' as remote name; bail if can't find either.
remote_pos = tag.find('[remote "origin"]')
if remote_pos == -1:
remote_pos = tag.find('[remote "gerrit"]')
if remote_pos == -1:
tag = '?'
else:
s = tag.find('url = ', remote_pos)
e = tag.find('\n', s)
tag = tag[(s + 6):e]
t = tag.strip().split('/')
tag = '[%s] %s' % (t[0][:-1], '-'.join(t[3:]))
with subprocess.Popen([cmd, '--no-pager',
'log', '-1',
'--pretty=format:"%ad|%an|%h|%H|%d"'
'--abbrev-commit',
'--date=iso'],
cwd=_program_dir,
stdout=subprocess.PIPE).stdout as stdout:
info = stdout.read()
info = info.decode(config.console_encoding).split('|')
date = info[0][:-6]
date = time.strptime(date.strip('"'), '%Y-%m-%d %H:%M:%S')
with subprocess.Popen([cmd, 'rev-list', 'HEAD'],
cwd=_program_dir,
stdout=subprocess.PIPE).stdout as stdout:
rev = stdout.read()
rev = 'g%s' % len(rev.splitlines())
hsh = info[3] # also stored in '.git/refs/heads/master'
if (not date or not tag or not rev) and not path:
raise ParseError
return (tag, rev, date, hsh)
def getversion_nightly(path=None):
"""Get version info for a nightly release.
@param path: directory of the uncompressed nightly.
@return:
- tag (name for the repository),
- rev (current revision identifier),
- date (date of current revision),
- hash (git hash for the current revision)
@rtype: C{tuple} of three C{str} and a C{time.struct_time}
"""
if not path:
path = _get_program_dir()
with open(os.path.join(path, 'version')) as data:
(tag, rev, date, hsh) = data.readlines()
date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S')
if not date or not tag or not rev:
raise ParseError
return (tag, rev, date, hsh)
def getversion_package(path=None): # pylint: disable=unused-argument
"""Get version info for an installed package.
@param path: Unused argument
@return:
- tag: 'pywikibot/__init__.py'
- rev: '-1 (unknown)'
- date (date the package was installed locally),
- hash (git hash for the current revision of 'pywikibot/__init__.py')
@rtype: C{tuple} of four C{str}
"""
hsh = get_module_version(pywikibot)
date = get_module_mtime(pywikibot).timetuple()
tag = 'pywikibot/__init__.py'
rev = '-1 (unknown)'
return (tag, rev, date, hsh)
def getversion_onlinerepo(repo=None):
"""Retrieve current framework revision number from online repository.
@param repo: (optional) Online repository location
@type repo: URL or string
"""
from pywikibot.comms import http
url = repo or 'https://git.wikimedia.org/feed/pywikibot/core'
buf = http.fetch(uri=url,
headers={'user-agent': '{pwb}'}).content.splitlines()
try:
hsh = buf[13].split('/')[5][:-1]
return hsh
except Exception as e:
raise ParseError(repr(e) + ' while parsing ' + repr(buf))
@deprecated('get_module_version, get_module_filename and get_module_mtime')
def getfileversion(filename):
"""Retrieve revision number of file.
Extracts __version__ variable containing Id tag, without importing it.
(thus can be done for any file)
The version variable containing the Id tag is read and
returned. Because it doesn't import it, the version can
be retrieved from any file.
@param filename: Name of the file to get version
@type filename: string
"""
_program_dir = _get_program_dir()
__version__ = None
mtime = None
fn = os.path.join(_program_dir, filename)
if os.path.exists(fn):
with codecs.open(fn, 'r', "utf-8") as f:
for line in f.readlines():
|
stat = os.stat(fn)
mtime = datetime.datetime.fromtimestamp(stat.st_mtime).isoformat(' ')
if mtime and __version__:
return u'%s %s %s' % (filename, __version__[5:-1][:7], mtime)
else:
return None
def get_module_version(module):
"""
Retrieve __version__ variable from an imported module.
@param module: The module instance.
@type module: module
@return: The version hash without the surrounding text. If not present None.
@rtype: str or None
"""
if hasattr(module, '__version__'):
return module.__version__[5:-1]
def get_module_filename(module):
"""
Retrieve filename from an imported pywikibot module.
It uses the __file__ attribute of the module. If it's file extension ends
with py and another character the last character is discarded when the py
file exist.
@param module: The module instance.
@type module: module
@return: The filename if it's a pywikibot module otherwise None.
@rtype: str or None
"""
if hasattr(module, '__file__') and os.path.exists(module.__file__):
filename = module.__file__
if filename[-4:-1] == '.py' and os.path.exists(filename[:-1]):
filename = filename[:-1]
program_dir = _get_program_dir()
if filename[:len(program_dir)] == program_dir:
return filename
def get_module_mtime(module):
"""
Retrieve the modification time from an imported module.
@param module: The module instance.
@type module: module
@return: The modification time if it's a pywikibot module otherwise None.
@rtype: datetime or None
"""
filename = get_module_filename(module)
if filename:
return datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
def package_versions(modules=None, builtins=False, standard_lib=None):
"""Retrieve package version information.
When builtins or standard_lib are None, they will be included only
if a version was found in the package.
@param modules: Modules to inspect
@type modules: list of strings
@param builtins: Include builtins
@type builtins: Boolean, or None for automatic selection
@param standard_lib: Include standard library packages
@type standard_lib: Boolean, or None for automatic selection
"""
if not modules:
modules = sys.modules.keys()
std_lib_dir = get_python_lib(standard_lib=True)
root_packages = set([key.split('.')[0]
for key in modules])
builtin_packages = set([name.split('.')[0] for name in root_packages
if name in sys.builtin_module_names or
'_' + name in sys.builtin_module_names])
# Improve performance by removing builtins from the list if possible.
if builtins is False:
root_packages = list(root_packages - builtin_packages)
std_lib_packages = []
paths = {}
data = {}
for name in root_packages:
try:
package = __import__(name, level=0)
except Exception as e:
data[name] = {'name': name, 'err': e}
continue
info = {'package': package, 'name': name}
if name in builtin_packages:
info['type'] = 'builtins'
if '__file__' in package.__dict__:
# Determine if this file part is of the standard library.
if os.path.normcase(package.__file__).startswith(
os.path.normcase(std_lib_dir)):
std_lib_packages.append(name)
if standard_lib is False:
continue
info['type'] = 'standard libary'
# Strip '__init__.py' from the filename.
path = package.__file__
if '__init__.py' in path:
path = path[0:path.index('__init__.py')]
if PY2:
path = path.decode(sys.getfilesystemencoding())
info['path'] = path
assert path not in paths, 'Path of the package is in defined paths'
paths[path] = name
if '__version__' in package.__dict__:
info['ver'] = package.__version__
elif name.startswith('unicodedata'):
info['ver'] = package.unidata_version
# If builtins or standard_lib is None,
# only include package if a version was found.
if (builtins is None and name in builtin_packages) or \
(standard_lib is None and name in std_lib_packages):
if 'ver' in info:
data[name] = info
else:
# Remove the entry from paths, so it isnt processed below
del paths[info['path']]
else:
data[name] = info
# Remove any pywikibot sub-modules which were loaded as a package.
# e.g. 'wikipedia_family.py' is loaded as 'wikipedia'
_program_dir = _get_program_dir()
for path, name in paths.items():
if _program_dir in path:
del data[name]
return data
| if line.find('__version__') == 0:
try:
exec(line)
except:
pass
break | conditional_block |
Themer.tsx | import * as PropTypes from 'prop-types';
import * as React from 'react';
export interface ThemerProps {
readonly theme?: string;
}
const DEFAULT_THEME: string = 'Day';
const bodyClassList: DOMTokenList = document.body.classList;
/**
* Impure component that changes the theme on the `body` tag
*/
export default class Themer extends React.PureComponent<ThemerProps, {}> {
static propTypes = {
theme: PropTypes.string,
};
static defaultProps: Partial<ThemerProps> = {
theme: DEFAULT_THEME,
};
componentDidMount() {
this.addTheme({ theme: this.props.theme });
}
| ({ theme }: ThemerProps) {
this.removeTheme({ theme });
this.addTheme({ theme: this.props.theme });
}
componentWillUnmount() {
this.removeTheme({ theme: this.props.theme });
}
addTheme({ theme }: ThemerProps) {
if (theme) {
bodyClassList.add(theme);
}
}
removeTheme({ theme }: ThemerProps) {
if (theme) {
bodyClassList.remove(theme);
}
}
render() {
return (
<div data-testid="Themer">
{this.props.children}
</div>
);
}
}
| componentDidUpdate | identifier_name |
Themer.tsx | import * as PropTypes from 'prop-types';
import * as React from 'react';
export interface ThemerProps {
readonly theme?: string;
}
const DEFAULT_THEME: string = 'Day';
const bodyClassList: DOMTokenList = document.body.classList;
/**
* Impure component that changes the theme on the `body` tag
*/
export default class Themer extends React.PureComponent<ThemerProps, {}> {
static propTypes = {
theme: PropTypes.string,
};
static defaultProps: Partial<ThemerProps> = {
theme: DEFAULT_THEME,
};
componentDidMount() {
this.addTheme({ theme: this.props.theme });
}
componentDidUpdate({ theme }: ThemerProps) {
this.removeTheme({ theme });
this.addTheme({ theme: this.props.theme });
}
componentWillUnmount() {
this.removeTheme({ theme: this.props.theme });
}
addTheme({ theme }: ThemerProps) {
if (theme) {
bodyClassList.add(theme);
}
}
removeTheme({ theme }: ThemerProps) {
if (theme) |
}
render() {
return (
<div data-testid="Themer">
{this.props.children}
</div>
);
}
}
| {
bodyClassList.remove(theme);
} | conditional_block |
Themer.tsx | import * as PropTypes from 'prop-types';
import * as React from 'react';
export interface ThemerProps {
readonly theme?: string;
}
const DEFAULT_THEME: string = 'Day';
const bodyClassList: DOMTokenList = document.body.classList;
/**
* Impure component that changes the theme on the `body` tag
*/
export default class Themer extends React.PureComponent<ThemerProps, {}> {
static propTypes = {
theme: PropTypes.string,
};
static defaultProps: Partial<ThemerProps> = {
theme: DEFAULT_THEME,
};
componentDidMount() {
this.addTheme({ theme: this.props.theme });
}
componentDidUpdate({ theme }: ThemerProps) |
componentWillUnmount() {
this.removeTheme({ theme: this.props.theme });
}
addTheme({ theme }: ThemerProps) {
if (theme) {
bodyClassList.add(theme);
}
}
removeTheme({ theme }: ThemerProps) {
if (theme) {
bodyClassList.remove(theme);
}
}
render() {
return (
<div data-testid="Themer">
{this.props.children}
</div>
);
}
}
| {
this.removeTheme({ theme });
this.addTheme({ theme: this.props.theme });
} | identifier_body |
Themer.tsx | import * as PropTypes from 'prop-types';
import * as React from 'react';
export interface ThemerProps {
readonly theme?: string;
}
const DEFAULT_THEME: string = 'Day';
const bodyClassList: DOMTokenList = document.body.classList;
/**
* Impure component that changes the theme on the `body` tag
*/
export default class Themer extends React.PureComponent<ThemerProps, {}> {
static propTypes = {
theme: PropTypes.string,
};
static defaultProps: Partial<ThemerProps> = {
theme: DEFAULT_THEME,
};
componentDidMount() {
this.addTheme({ theme: this.props.theme });
}
componentDidUpdate({ theme }: ThemerProps) {
this.removeTheme({ theme });
this.addTheme({ theme: this.props.theme });
}
componentWillUnmount() { | addTheme({ theme }: ThemerProps) {
if (theme) {
bodyClassList.add(theme);
}
}
removeTheme({ theme }: ThemerProps) {
if (theme) {
bodyClassList.remove(theme);
}
}
render() {
return (
<div data-testid="Themer">
{this.props.children}
</div>
);
}
} | this.removeTheme({ theme: this.props.theme });
}
| random_line_split |
GlobalSearch.js | import React, { Component, PropTypes } from 'react'
import { Search, Grid } from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import Tag from './Tag'
import { search, setQuery, clearSearch } from '../actions/entities'
import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search'
const propTypes = {
dispatch: PropTypes.func.isRequired,
search: PropTypes.object.isRequired
}
const resultRenderer = ({ name, type, screenshots }) => {
return (
<Grid>
<Grid.Column floated="left" width={12}>
<Tag name={name} type={type} />
</Grid.Column>
<Grid.Column floated="right" width={4} textAlign="right">
<small className="text grey">{screenshots.length}</small>
</Grid.Column>
</Grid>
)
}
class | extends Component {
state = {
typingTimer: null
}
handleSearchChange = (e, value) => {
clearTimeout(this.state.typingTimer)
this.setState({
typingTimer: setTimeout(
() => this.handleDoneTyping(value.trim()),
DONE_TYPING_INTERVAL
)
})
const { dispatch } = this.props
dispatch(setQuery(value))
}
handleDoneTyping = value => {
if (value.length < MIN_CHARACTERS) return
const { dispatch } = this.props
dispatch(search({ query: value }))
}
handleResultSelect = (e, item) => {
const { dispatch } = this.props
const { name } = item
dispatch(clearSearch())
browserHistory.push(`/tag/${name}`)
}
render() {
const { search } = this.props
const { query, results } = search
return (
<Search
minCharacters={MIN_CHARACTERS}
onSearchChange={this.handleSearchChange}
onResultSelect={this.handleResultSelect}
resultRenderer={resultRenderer}
results={results}
value={query}
/>
)
}
}
GlobalSearch.propTypes = propTypes
export default GlobalSearch
| GlobalSearch | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.