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 |
|---|---|---|---|---|
models.py | #!/usr/bin/python
#
# Copyright 2010 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.
"""App Engine data model (schema) definition for Quiz."""
# Python imports
import base64
import logging
import md5
import operator
import os
import re
import time
# AppEngine imports
from google.appengine.ext import db
from google.appengine.api import memcache
class QuizBaseModel(db.Model):
"""Base class for quiz models."""
class QuizTrunkModel(QuizBaseModel):
"""Maintains trunk for quiz model.
Attributes:
head: Maintians the head of a quiz.
"""
head = db.StringProperty()
class QuizRevisionModel(QuizBaseModel):
"""Maintains list of revisions for a quiz.
Quiz trunk associated with the revision is made parent of the model.
Attributes:
quiz_id: Id (key) for particular version of the quiz.
time_stamp: Time_stamp for a new revision.
commit_message: Commit message associated with new version.
"""
quiz_id = db.StringProperty()
time_stamp = db.DateTimeProperty(auto_now=True)
commit_message = db.StringProperty(default='Commiting a new version')
class QuizPropertyModel(QuizBaseModel):
"""Defines various properties for a quiz.
Attributes:
shuffle_questions: If set questions are presented in random order.
min_options: minimum number of options to be presented.
max_options: maximum number of options to be presented.
min_questions: minimum number of questions required to complete the quiz.
Used to track the progress.
repeat_questions: If set questions are repeated.
repeat_wrongly_answered_questions: If set wrongly answered questions are
repeated.
"""
shuffle_questions = db.BooleanProperty(default=True)
min_options = db.IntegerProperty(default=2)
max_options = db.IntegerProperty(default=10) # 0 implies all
min_questions = db.IntegerProperty(default=0) # 0 implies all
repeat_questions = db.BooleanProperty(default=False)
repeat_wrongly_answered_questions = db.BooleanProperty(default=False)
class QuizModel(QuizBaseModel):
"""Represents a quiz.
Attributes:
difficulty_level: Difficulty level for the quiz (range 0-10).
quiz_property: Reference to property asscociated with quiz.
title: Title of the quiz.
tags: Associated tags with quiz.
trunk: Reference to asscociated trunk with the quiz.
introduction: Introduction text to be shown on the start page for quiz.
"""
# implicit id
difficulty_level = db.RatingProperty(default=5)
quiz_property = db.ReferenceProperty(QuizPropertyModel)
title = db.StringProperty()
tags = db.ListProperty(db.Category)
trunk = db.ReferenceProperty(QuizTrunkModel)
introduction = db.StringProperty()
class ChoiceModel(QuizBaseModel):
"""Represents a choice/option provided to user for a question model.
Attributes:
body: Body of the choice.
message: Message to be displayed when choice is selected.
May act like a hint.
is_correct: If the choice selected is correct.
"""
# implicit id
body = db.TextProperty()
message = db.StringProperty()
is_correct = db.BooleanProperty(default=False)
def dump_to_dict(self):
"""Dumps choice to a dictionary for passing around as JSON object."""
data_dict = {'body': self.body,
'id': str(self.key())}
return data_dict
class QuestionModel(QuizBaseModel):
"""Represents a question.
Attributes:
body: Text asscociated with quiz.
choices: List of possible choices.
shuffle_choices: If set choices are randomly shuffled.
hints: Ordered list of progressive hints
"""
# implicit id
body = db.TextProperty()
choices = db.ListProperty(db.Key)
shuffle_choices = db.BooleanProperty(default=True)
hints = db.StringListProperty()
def dump_to_dict(self):
"""Dumps the question model to a dictionary for passing
around as JSON object."""
data_dict = {'id': str(self.key()),
'body': self.body,
'hints': self.hints,
'choices': [db.get(el).dump_to_dict() for el in self.choices]
}
if self.shuffle_choices and data_dict['choices']:
|
return data_dict
class QuizQuestionListModel(QuizBaseModel):
"""Maintains a list of question with its quiz id.
This is necessary because questions may be shared between different quizes.
Attributes:
quiz: Reference to quiz object.
question: Reference to question object asscociated with quiz.
time_stamp: Time stamp.
"""
quiz = db.ReferenceProperty(QuizModel)
question = db.ReferenceProperty(QuestionModel)
time_stamp = db.DateTimeProperty(auto_now_add=True)
class ResponseModel(QuizBaseModel):
"""Stores response data required for producing next question.
Attributes:
session_id: Session Identifier.
answered_correctly: Set if the response resulted in correct answer.
question: Reference to question being answered.
quiz: Reference to associated quiz.
quiz_trunk: Reference to associated quiz trunk.
time_stamp: Time stamp of the response
attempts: Number of attempts so far, useful for scoring.
"""
session_id = db.StringProperty(required=True)
answered_correctly = db.BooleanProperty(db.Key)
question = db.ReferenceProperty(QuestionModel)
quiz = db.ReferenceProperty(QuizModel)
quiz_trunk = db.ReferenceProperty(QuizTrunkModel)
time_stamp = db.DateTimeProperty(auto_now=True)
attempts = db.IntegerProperty(default=0)
class QuizScoreModel(QuizBaseModel):
"""Stores progress status associated with a quiz and session.
Both score and progress are out of 100.
Attributes:
session_id: Session Identifier.
quiz: Reference to associated quiz.
quiz_trunk: Reference to associated quiz trunk.
score: Current score.
progress: Current progress status
questions_attempted: Number of questions attempted so far.
"""
quiz_trunk = db.ReferenceProperty(QuizTrunkModel)
session_id = db.StringProperty(required=True)
quiz = db.ReferenceProperty(QuizModel)
score = db.FloatProperty(default=0.0)
progress = db.FloatProperty(default=0.0)
questions_attempted = db.IntegerProperty(default=0)
| data_dict['choices'] = random.shuffle(data_dict['choices']) | conditional_block |
models.py | #!/usr/bin/python
#
# Copyright 2010 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.
"""App Engine data model (schema) definition for Quiz."""
# Python imports
import base64
import logging
import md5
import operator
import os
import re
import time
# AppEngine imports
from google.appengine.ext import db
from google.appengine.api import memcache
class QuizBaseModel(db.Model):
"""Base class for quiz models."""
class QuizTrunkModel(QuizBaseModel):
"""Maintains trunk for quiz model.
Attributes:
head: Maintians the head of a quiz.
"""
head = db.StringProperty()
class QuizRevisionModel(QuizBaseModel):
"""Maintains list of revisions for a quiz.
Quiz trunk associated with the revision is made parent of the model.
Attributes:
quiz_id: Id (key) for particular version of the quiz.
time_stamp: Time_stamp for a new revision.
commit_message: Commit message associated with new version.
"""
quiz_id = db.StringProperty()
time_stamp = db.DateTimeProperty(auto_now=True)
commit_message = db.StringProperty(default='Commiting a new version')
class QuizPropertyModel(QuizBaseModel):
"""Defines various properties for a quiz.
Attributes:
shuffle_questions: If set questions are presented in random order.
min_options: minimum number of options to be presented.
max_options: maximum number of options to be presented.
min_questions: minimum number of questions required to complete the quiz.
Used to track the progress.
repeat_questions: If set questions are repeated.
repeat_wrongly_answered_questions: If set wrongly answered questions are
repeated.
"""
shuffle_questions = db.BooleanProperty(default=True)
min_options = db.IntegerProperty(default=2)
max_options = db.IntegerProperty(default=10) # 0 implies all
min_questions = db.IntegerProperty(default=0) # 0 implies all
repeat_questions = db.BooleanProperty(default=False)
repeat_wrongly_answered_questions = db.BooleanProperty(default=False)
class | (QuizBaseModel):
"""Represents a quiz.
Attributes:
difficulty_level: Difficulty level for the quiz (range 0-10).
quiz_property: Reference to property asscociated with quiz.
title: Title of the quiz.
tags: Associated tags with quiz.
trunk: Reference to asscociated trunk with the quiz.
introduction: Introduction text to be shown on the start page for quiz.
"""
# implicit id
difficulty_level = db.RatingProperty(default=5)
quiz_property = db.ReferenceProperty(QuizPropertyModel)
title = db.StringProperty()
tags = db.ListProperty(db.Category)
trunk = db.ReferenceProperty(QuizTrunkModel)
introduction = db.StringProperty()
class ChoiceModel(QuizBaseModel):
"""Represents a choice/option provided to user for a question model.
Attributes:
body: Body of the choice.
message: Message to be displayed when choice is selected.
May act like a hint.
is_correct: If the choice selected is correct.
"""
# implicit id
body = db.TextProperty()
message = db.StringProperty()
is_correct = db.BooleanProperty(default=False)
def dump_to_dict(self):
"""Dumps choice to a dictionary for passing around as JSON object."""
data_dict = {'body': self.body,
'id': str(self.key())}
return data_dict
class QuestionModel(QuizBaseModel):
"""Represents a question.
Attributes:
body: Text asscociated with quiz.
choices: List of possible choices.
shuffle_choices: If set choices are randomly shuffled.
hints: Ordered list of progressive hints
"""
# implicit id
body = db.TextProperty()
choices = db.ListProperty(db.Key)
shuffle_choices = db.BooleanProperty(default=True)
hints = db.StringListProperty()
def dump_to_dict(self):
"""Dumps the question model to a dictionary for passing
around as JSON object."""
data_dict = {'id': str(self.key()),
'body': self.body,
'hints': self.hints,
'choices': [db.get(el).dump_to_dict() for el in self.choices]
}
if self.shuffle_choices and data_dict['choices']:
data_dict['choices'] = random.shuffle(data_dict['choices'])
return data_dict
class QuizQuestionListModel(QuizBaseModel):
"""Maintains a list of question with its quiz id.
This is necessary because questions may be shared between different quizes.
Attributes:
quiz: Reference to quiz object.
question: Reference to question object asscociated with quiz.
time_stamp: Time stamp.
"""
quiz = db.ReferenceProperty(QuizModel)
question = db.ReferenceProperty(QuestionModel)
time_stamp = db.DateTimeProperty(auto_now_add=True)
class ResponseModel(QuizBaseModel):
"""Stores response data required for producing next question.
Attributes:
session_id: Session Identifier.
answered_correctly: Set if the response resulted in correct answer.
question: Reference to question being answered.
quiz: Reference to associated quiz.
quiz_trunk: Reference to associated quiz trunk.
time_stamp: Time stamp of the response
attempts: Number of attempts so far, useful for scoring.
"""
session_id = db.StringProperty(required=True)
answered_correctly = db.BooleanProperty(db.Key)
question = db.ReferenceProperty(QuestionModel)
quiz = db.ReferenceProperty(QuizModel)
quiz_trunk = db.ReferenceProperty(QuizTrunkModel)
time_stamp = db.DateTimeProperty(auto_now=True)
attempts = db.IntegerProperty(default=0)
class QuizScoreModel(QuizBaseModel):
"""Stores progress status associated with a quiz and session.
Both score and progress are out of 100.
Attributes:
session_id: Session Identifier.
quiz: Reference to associated quiz.
quiz_trunk: Reference to associated quiz trunk.
score: Current score.
progress: Current progress status
questions_attempted: Number of questions attempted so far.
"""
quiz_trunk = db.ReferenceProperty(QuizTrunkModel)
session_id = db.StringProperty(required=True)
quiz = db.ReferenceProperty(QuizModel)
score = db.FloatProperty(default=0.0)
progress = db.FloatProperty(default=0.0)
questions_attempted = db.IntegerProperty(default=0)
| QuizModel | identifier_name |
models.py | #!/usr/bin/python
#
# Copyright 2010 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.
"""App Engine data model (schema) definition for Quiz."""
# Python imports
import base64
import logging
import md5
import operator
import os
import re
import time
# AppEngine imports
from google.appengine.ext import db
from google.appengine.api import memcache
class QuizBaseModel(db.Model):
"""Base class for quiz models."""
class QuizTrunkModel(QuizBaseModel):
"""Maintains trunk for quiz model.
Attributes:
head: Maintians the head of a quiz.
"""
head = db.StringProperty()
class QuizRevisionModel(QuizBaseModel):
"""Maintains list of revisions for a quiz.
Quiz trunk associated with the revision is made parent of the model.
Attributes:
quiz_id: Id (key) for particular version of the quiz.
time_stamp: Time_stamp for a new revision.
commit_message: Commit message associated with new version.
"""
quiz_id = db.StringProperty()
time_stamp = db.DateTimeProperty(auto_now=True)
commit_message = db.StringProperty(default='Commiting a new version')
class QuizPropertyModel(QuizBaseModel):
"""Defines various properties for a quiz.
Attributes:
shuffle_questions: If set questions are presented in random order.
min_options: minimum number of options to be presented.
max_options: maximum number of options to be presented.
min_questions: minimum number of questions required to complete the quiz.
Used to track the progress.
repeat_questions: If set questions are repeated.
repeat_wrongly_answered_questions: If set wrongly answered questions are
repeated.
"""
shuffle_questions = db.BooleanProperty(default=True)
min_options = db.IntegerProperty(default=2)
max_options = db.IntegerProperty(default=10) # 0 implies all
min_questions = db.IntegerProperty(default=0) # 0 implies all
repeat_questions = db.BooleanProperty(default=False)
repeat_wrongly_answered_questions = db.BooleanProperty(default=False)
class QuizModel(QuizBaseModel):
"""Represents a quiz.
Attributes:
difficulty_level: Difficulty level for the quiz (range 0-10).
quiz_property: Reference to property asscociated with quiz.
title: Title of the quiz.
tags: Associated tags with quiz.
trunk: Reference to asscociated trunk with the quiz.
introduction: Introduction text to be shown on the start page for quiz.
"""
# implicit id
difficulty_level = db.RatingProperty(default=5)
quiz_property = db.ReferenceProperty(QuizPropertyModel)
title = db.StringProperty()
tags = db.ListProperty(db.Category)
trunk = db.ReferenceProperty(QuizTrunkModel)
introduction = db.StringProperty()
class ChoiceModel(QuizBaseModel):
"""Represents a choice/option provided to user for a question model.
Attributes:
body: Body of the choice.
message: Message to be displayed when choice is selected.
May act like a hint.
is_correct: If the choice selected is correct.
"""
# implicit id
body = db.TextProperty()
message = db.StringProperty()
is_correct = db.BooleanProperty(default=False) | data_dict = {'body': self.body,
'id': str(self.key())}
return data_dict
class QuestionModel(QuizBaseModel):
"""Represents a question.
Attributes:
body: Text asscociated with quiz.
choices: List of possible choices.
shuffle_choices: If set choices are randomly shuffled.
hints: Ordered list of progressive hints
"""
# implicit id
body = db.TextProperty()
choices = db.ListProperty(db.Key)
shuffle_choices = db.BooleanProperty(default=True)
hints = db.StringListProperty()
def dump_to_dict(self):
"""Dumps the question model to a dictionary for passing
around as JSON object."""
data_dict = {'id': str(self.key()),
'body': self.body,
'hints': self.hints,
'choices': [db.get(el).dump_to_dict() for el in self.choices]
}
if self.shuffle_choices and data_dict['choices']:
data_dict['choices'] = random.shuffle(data_dict['choices'])
return data_dict
class QuizQuestionListModel(QuizBaseModel):
"""Maintains a list of question with its quiz id.
This is necessary because questions may be shared between different quizes.
Attributes:
quiz: Reference to quiz object.
question: Reference to question object asscociated with quiz.
time_stamp: Time stamp.
"""
quiz = db.ReferenceProperty(QuizModel)
question = db.ReferenceProperty(QuestionModel)
time_stamp = db.DateTimeProperty(auto_now_add=True)
class ResponseModel(QuizBaseModel):
"""Stores response data required for producing next question.
Attributes:
session_id: Session Identifier.
answered_correctly: Set if the response resulted in correct answer.
question: Reference to question being answered.
quiz: Reference to associated quiz.
quiz_trunk: Reference to associated quiz trunk.
time_stamp: Time stamp of the response
attempts: Number of attempts so far, useful for scoring.
"""
session_id = db.StringProperty(required=True)
answered_correctly = db.BooleanProperty(db.Key)
question = db.ReferenceProperty(QuestionModel)
quiz = db.ReferenceProperty(QuizModel)
quiz_trunk = db.ReferenceProperty(QuizTrunkModel)
time_stamp = db.DateTimeProperty(auto_now=True)
attempts = db.IntegerProperty(default=0)
class QuizScoreModel(QuizBaseModel):
"""Stores progress status associated with a quiz and session.
Both score and progress are out of 100.
Attributes:
session_id: Session Identifier.
quiz: Reference to associated quiz.
quiz_trunk: Reference to associated quiz trunk.
score: Current score.
progress: Current progress status
questions_attempted: Number of questions attempted so far.
"""
quiz_trunk = db.ReferenceProperty(QuizTrunkModel)
session_id = db.StringProperty(required=True)
quiz = db.ReferenceProperty(QuizModel)
score = db.FloatProperty(default=0.0)
progress = db.FloatProperty(default=0.0)
questions_attempted = db.IntegerProperty(default=0) |
def dump_to_dict(self):
"""Dumps choice to a dictionary for passing around as JSON object.""" | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
#
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import datetime as dt
class Lammps(CMakePackage):
"""LAMMPS stands for Large-scale Atomic/Molecular Massively
Parallel Simulator. This package uses patch releases, not
stable release.
See https://github.com/spack/spack/pull/5342 for a detailed
discussion.
"""
homepage = "http://lammps.sandia.gov/"
url = "https://github.com/lammps/lammps/archive/patch_1Sep2017.tar.gz"
git = "https://github.com/lammps/lammps.git"
tags = ['ecp', 'ecp-apps']
version('develop', branch='master')
version('20180629', '6d5941863ee25ad2227ff3b7577d5e7c')
version('20180316', '25bad35679583e0dd8cb8753665bb84b')
version('20180222', '4d0513e3183bd57721814d217fdaf957')
version('20170922', '4306071f919ec7e759bda195c26cfd9a')
version('20170901', '767e7f07289663f033474dfe974974e7')
def url_for_version(self, version):
vdate = dt.datetime.strptime(str(version), "%Y%m%d")
return "https://github.com/lammps/lammps/archive/patch_{0}.tar.gz".format(
vdate.strftime("%d%b%Y").lstrip('0'))
supported_packages = ['asphere', 'body', 'class2', 'colloid', 'compress',
'coreshell', 'dipole', 'granular', 'kspace', 'latte',
'manybody', 'mc', 'meam', 'misc', 'molecule',
'mpiio', 'peri', 'poems', 'python', 'qeq', 'reax',
'replica', 'rigid', 'shock', 'snap', 'srd',
'user-atc', 'user-h5md', 'user-lb', 'user-misc',
'user-netcdf', 'user-omp', 'voronoi']
for pkg in supported_packages:
variant(pkg, default=False,
description='Activate the {0} package'.format(pkg))
variant('lib', default=True,
description='Build the liblammps in addition to the executable')
variant('mpi', default=True,
description='Build with mpi')
depends_on('mpi', when='+mpi')
depends_on('mpi', when='+mpiio')
depends_on('fftw', when='+kspace')
depends_on('voropp', when='+voronoi')
depends_on('netcdf+mpi', when='+user-netcdf')
depends_on('blas', when='+user-atc')
depends_on('lapack', when='+user-atc')
depends_on('latte@1.0.1', when='@:20180222+latte')
depends_on('latte@1.1.1:', when='@20180316:20180628+latte')
depends_on('latte@1.2.1:', when='@20180629:+latte')
depends_on('blas', when='+latte')
depends_on('lapack', when='+latte')
depends_on('python', when='+python')
depends_on('mpi', when='+user-lb')
depends_on('mpi', when='+user-h5md')
depends_on('hdf5', when='+user-h5md')
conflicts('+body', when='+poems@:20180628')
conflicts('+latte', when='@:20170921')
conflicts('+python', when='~lib')
conflicts('+qeq', when='~manybody')
conflicts('+user-atc', when='~manybody')
conflicts('+user-misc', when='~manybody')
conflicts('+user-phonon', when='~kspace')
conflicts('+user-misc', when='~manybody')
patch("lib.patch", when="@20170901")
patch("660.patch", when="@20170922")
root_cmakelists_dir = 'cmake'
def cmake_args(self):
spec = self.spec
mpi_prefix = 'ENABLE'
pkg_prefix = 'ENABLE'
if spec.satisfies('@20180629:'):
mpi_prefix = 'BUILD'
pkg_prefix = 'PKG'
args = [
'-DBUILD_SHARED_LIBS={0}'.format(
'ON' if '+lib' in spec else 'OFF'),
'-D{0}_MPI={1}'.format(
mpi_prefix,
'ON' if '+mpi' in spec else 'OFF')
]
if spec.satisfies('@20180629:+lib'):
args.append('-DBUILD_LIB=ON')
for pkg in self.supported_packages:
opt = '-D{0}_{1}'.format(pkg_prefix, pkg.upper())
if '+{0}'.format(pkg) in spec:
args.append('{0}=ON'.format(opt))
else:
|
if '+kspace' in spec:
args.append('-DFFT=FFTW3')
return args
| args.append('{0}=OFF'.format(opt)) | conditional_block |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
#
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import datetime as dt
class Lammps(CMakePackage):
"""LAMMPS stands for Large-scale Atomic/Molecular Massively
Parallel Simulator. This package uses patch releases, not
stable release.
See https://github.com/spack/spack/pull/5342 for a detailed
discussion.
"""
homepage = "http://lammps.sandia.gov/"
url = "https://github.com/lammps/lammps/archive/patch_1Sep2017.tar.gz"
git = "https://github.com/lammps/lammps.git"
tags = ['ecp', 'ecp-apps']
version('develop', branch='master')
version('20180629', '6d5941863ee25ad2227ff3b7577d5e7c')
version('20180316', '25bad35679583e0dd8cb8753665bb84b')
version('20180222', '4d0513e3183bd57721814d217fdaf957')
version('20170922', '4306071f919ec7e759bda195c26cfd9a')
version('20170901', '767e7f07289663f033474dfe974974e7')
def | (self, version):
vdate = dt.datetime.strptime(str(version), "%Y%m%d")
return "https://github.com/lammps/lammps/archive/patch_{0}.tar.gz".format(
vdate.strftime("%d%b%Y").lstrip('0'))
supported_packages = ['asphere', 'body', 'class2', 'colloid', 'compress',
'coreshell', 'dipole', 'granular', 'kspace', 'latte',
'manybody', 'mc', 'meam', 'misc', 'molecule',
'mpiio', 'peri', 'poems', 'python', 'qeq', 'reax',
'replica', 'rigid', 'shock', 'snap', 'srd',
'user-atc', 'user-h5md', 'user-lb', 'user-misc',
'user-netcdf', 'user-omp', 'voronoi']
for pkg in supported_packages:
variant(pkg, default=False,
description='Activate the {0} package'.format(pkg))
variant('lib', default=True,
description='Build the liblammps in addition to the executable')
variant('mpi', default=True,
description='Build with mpi')
depends_on('mpi', when='+mpi')
depends_on('mpi', when='+mpiio')
depends_on('fftw', when='+kspace')
depends_on('voropp', when='+voronoi')
depends_on('netcdf+mpi', when='+user-netcdf')
depends_on('blas', when='+user-atc')
depends_on('lapack', when='+user-atc')
depends_on('latte@1.0.1', when='@:20180222+latte')
depends_on('latte@1.1.1:', when='@20180316:20180628+latte')
depends_on('latte@1.2.1:', when='@20180629:+latte')
depends_on('blas', when='+latte')
depends_on('lapack', when='+latte')
depends_on('python', when='+python')
depends_on('mpi', when='+user-lb')
depends_on('mpi', when='+user-h5md')
depends_on('hdf5', when='+user-h5md')
conflicts('+body', when='+poems@:20180628')
conflicts('+latte', when='@:20170921')
conflicts('+python', when='~lib')
conflicts('+qeq', when='~manybody')
conflicts('+user-atc', when='~manybody')
conflicts('+user-misc', when='~manybody')
conflicts('+user-phonon', when='~kspace')
conflicts('+user-misc', when='~manybody')
patch("lib.patch", when="@20170901")
patch("660.patch", when="@20170922")
root_cmakelists_dir = 'cmake'
def cmake_args(self):
spec = self.spec
mpi_prefix = 'ENABLE'
pkg_prefix = 'ENABLE'
if spec.satisfies('@20180629:'):
mpi_prefix = 'BUILD'
pkg_prefix = 'PKG'
args = [
'-DBUILD_SHARED_LIBS={0}'.format(
'ON' if '+lib' in spec else 'OFF'),
'-D{0}_MPI={1}'.format(
mpi_prefix,
'ON' if '+mpi' in spec else 'OFF')
]
if spec.satisfies('@20180629:+lib'):
args.append('-DBUILD_LIB=ON')
for pkg in self.supported_packages:
opt = '-D{0}_{1}'.format(pkg_prefix, pkg.upper())
if '+{0}'.format(pkg) in spec:
args.append('{0}=ON'.format(opt))
else:
args.append('{0}=OFF'.format(opt))
if '+kspace' in spec:
args.append('-DFFT=FFTW3')
return args
| url_for_version | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
#
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import datetime as dt
class Lammps(CMakePackage):
"""LAMMPS stands for Large-scale Atomic/Molecular Massively
Parallel Simulator. This package uses patch releases, not
stable release.
See https://github.com/spack/spack/pull/5342 for a detailed
discussion.
""" |
tags = ['ecp', 'ecp-apps']
version('develop', branch='master')
version('20180629', '6d5941863ee25ad2227ff3b7577d5e7c')
version('20180316', '25bad35679583e0dd8cb8753665bb84b')
version('20180222', '4d0513e3183bd57721814d217fdaf957')
version('20170922', '4306071f919ec7e759bda195c26cfd9a')
version('20170901', '767e7f07289663f033474dfe974974e7')
def url_for_version(self, version):
vdate = dt.datetime.strptime(str(version), "%Y%m%d")
return "https://github.com/lammps/lammps/archive/patch_{0}.tar.gz".format(
vdate.strftime("%d%b%Y").lstrip('0'))
supported_packages = ['asphere', 'body', 'class2', 'colloid', 'compress',
'coreshell', 'dipole', 'granular', 'kspace', 'latte',
'manybody', 'mc', 'meam', 'misc', 'molecule',
'mpiio', 'peri', 'poems', 'python', 'qeq', 'reax',
'replica', 'rigid', 'shock', 'snap', 'srd',
'user-atc', 'user-h5md', 'user-lb', 'user-misc',
'user-netcdf', 'user-omp', 'voronoi']
for pkg in supported_packages:
variant(pkg, default=False,
description='Activate the {0} package'.format(pkg))
variant('lib', default=True,
description='Build the liblammps in addition to the executable')
variant('mpi', default=True,
description='Build with mpi')
depends_on('mpi', when='+mpi')
depends_on('mpi', when='+mpiio')
depends_on('fftw', when='+kspace')
depends_on('voropp', when='+voronoi')
depends_on('netcdf+mpi', when='+user-netcdf')
depends_on('blas', when='+user-atc')
depends_on('lapack', when='+user-atc')
depends_on('latte@1.0.1', when='@:20180222+latte')
depends_on('latte@1.1.1:', when='@20180316:20180628+latte')
depends_on('latte@1.2.1:', when='@20180629:+latte')
depends_on('blas', when='+latte')
depends_on('lapack', when='+latte')
depends_on('python', when='+python')
depends_on('mpi', when='+user-lb')
depends_on('mpi', when='+user-h5md')
depends_on('hdf5', when='+user-h5md')
conflicts('+body', when='+poems@:20180628')
conflicts('+latte', when='@:20170921')
conflicts('+python', when='~lib')
conflicts('+qeq', when='~manybody')
conflicts('+user-atc', when='~manybody')
conflicts('+user-misc', when='~manybody')
conflicts('+user-phonon', when='~kspace')
conflicts('+user-misc', when='~manybody')
patch("lib.patch", when="@20170901")
patch("660.patch", when="@20170922")
root_cmakelists_dir = 'cmake'
def cmake_args(self):
spec = self.spec
mpi_prefix = 'ENABLE'
pkg_prefix = 'ENABLE'
if spec.satisfies('@20180629:'):
mpi_prefix = 'BUILD'
pkg_prefix = 'PKG'
args = [
'-DBUILD_SHARED_LIBS={0}'.format(
'ON' if '+lib' in spec else 'OFF'),
'-D{0}_MPI={1}'.format(
mpi_prefix,
'ON' if '+mpi' in spec else 'OFF')
]
if spec.satisfies('@20180629:+lib'):
args.append('-DBUILD_LIB=ON')
for pkg in self.supported_packages:
opt = '-D{0}_{1}'.format(pkg_prefix, pkg.upper())
if '+{0}'.format(pkg) in spec:
args.append('{0}=ON'.format(opt))
else:
args.append('{0}=OFF'.format(opt))
if '+kspace' in spec:
args.append('-DFFT=FFTW3')
return args | homepage = "http://lammps.sandia.gov/"
url = "https://github.com/lammps/lammps/archive/patch_1Sep2017.tar.gz"
git = "https://github.com/lammps/lammps.git" | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
#
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import datetime as dt
class Lammps(CMakePackage):
| """LAMMPS stands for Large-scale Atomic/Molecular Massively
Parallel Simulator. This package uses patch releases, not
stable release.
See https://github.com/spack/spack/pull/5342 for a detailed
discussion.
"""
homepage = "http://lammps.sandia.gov/"
url = "https://github.com/lammps/lammps/archive/patch_1Sep2017.tar.gz"
git = "https://github.com/lammps/lammps.git"
tags = ['ecp', 'ecp-apps']
version('develop', branch='master')
version('20180629', '6d5941863ee25ad2227ff3b7577d5e7c')
version('20180316', '25bad35679583e0dd8cb8753665bb84b')
version('20180222', '4d0513e3183bd57721814d217fdaf957')
version('20170922', '4306071f919ec7e759bda195c26cfd9a')
version('20170901', '767e7f07289663f033474dfe974974e7')
def url_for_version(self, version):
vdate = dt.datetime.strptime(str(version), "%Y%m%d")
return "https://github.com/lammps/lammps/archive/patch_{0}.tar.gz".format(
vdate.strftime("%d%b%Y").lstrip('0'))
supported_packages = ['asphere', 'body', 'class2', 'colloid', 'compress',
'coreshell', 'dipole', 'granular', 'kspace', 'latte',
'manybody', 'mc', 'meam', 'misc', 'molecule',
'mpiio', 'peri', 'poems', 'python', 'qeq', 'reax',
'replica', 'rigid', 'shock', 'snap', 'srd',
'user-atc', 'user-h5md', 'user-lb', 'user-misc',
'user-netcdf', 'user-omp', 'voronoi']
for pkg in supported_packages:
variant(pkg, default=False,
description='Activate the {0} package'.format(pkg))
variant('lib', default=True,
description='Build the liblammps in addition to the executable')
variant('mpi', default=True,
description='Build with mpi')
depends_on('mpi', when='+mpi')
depends_on('mpi', when='+mpiio')
depends_on('fftw', when='+kspace')
depends_on('voropp', when='+voronoi')
depends_on('netcdf+mpi', when='+user-netcdf')
depends_on('blas', when='+user-atc')
depends_on('lapack', when='+user-atc')
depends_on('latte@1.0.1', when='@:20180222+latte')
depends_on('latte@1.1.1:', when='@20180316:20180628+latte')
depends_on('latte@1.2.1:', when='@20180629:+latte')
depends_on('blas', when='+latte')
depends_on('lapack', when='+latte')
depends_on('python', when='+python')
depends_on('mpi', when='+user-lb')
depends_on('mpi', when='+user-h5md')
depends_on('hdf5', when='+user-h5md')
conflicts('+body', when='+poems@:20180628')
conflicts('+latte', when='@:20170921')
conflicts('+python', when='~lib')
conflicts('+qeq', when='~manybody')
conflicts('+user-atc', when='~manybody')
conflicts('+user-misc', when='~manybody')
conflicts('+user-phonon', when='~kspace')
conflicts('+user-misc', when='~manybody')
patch("lib.patch", when="@20170901")
patch("660.patch", when="@20170922")
root_cmakelists_dir = 'cmake'
def cmake_args(self):
spec = self.spec
mpi_prefix = 'ENABLE'
pkg_prefix = 'ENABLE'
if spec.satisfies('@20180629:'):
mpi_prefix = 'BUILD'
pkg_prefix = 'PKG'
args = [
'-DBUILD_SHARED_LIBS={0}'.format(
'ON' if '+lib' in spec else 'OFF'),
'-D{0}_MPI={1}'.format(
mpi_prefix,
'ON' if '+mpi' in spec else 'OFF')
]
if spec.satisfies('@20180629:+lib'):
args.append('-DBUILD_LIB=ON')
for pkg in self.supported_packages:
opt = '-D{0}_{1}'.format(pkg_prefix, pkg.upper())
if '+{0}'.format(pkg) in spec:
args.append('{0}=ON'.format(opt))
else:
args.append('{0}=OFF'.format(opt))
if '+kspace' in spec:
args.append('-DFFT=FFTW3')
return args | identifier_body | |
MediaAttachmentEditorUI.tsx | import {GetErrorMessagesUnderElement, Clone, E, CloneWithPrototypes} from "js-vextensions";
import {Column, Pre, RowLR, Spinner, TextInput, Row, DropDown, DropDownTrigger, Button, DropDownContent, Text, CheckBox} from "react-vcomponents";
import {BaseComponent, GetDOM, BaseComponentPlus} from "react-vextensions";
import {ScrollView} from "react-vscrollview";
import {TermDefinitionPanel} from "../../NodeUI/Panels/DefinitionsPanel";
import {ShowAddMediaDialog} from "UI/Database/Medias/AddMediaDialog";
import {MediaAttachment} from "@debate-map/server-link/Source/Link";
import {Validate} from "mobx-firelink";
import {GetMedia, GetMediasByURL} from "@debate-map/server-link/Source/Link";
import {Link, Observer, InfoButton} from "vwebapp-framework";
import {HasModPermissions} from "@debate-map/server-link/Source/Link";
import {MeID, GetUser} from "@debate-map/server-link/Source/Link";
import {Media} from "@debate-map/server-link/Source/Link";
import {SourceChainsEditorUI} from "../../SourceChainsEditorUI";
type Props = {baseData: MediaAttachment, creating: boolean, editing?: boolean, style?, onChange?: (newData: MediaAttachment)=>void};
export class MediaAttachmentEditorUI extends BaseComponent<Props, {newData: MediaAttachment}> {
ComponentWillMountOrReceiveProps(props, forMount) |
scrollView: ScrollView;
render() {
const {creating, editing, style, onChange} = this.props;
const {newData} = this.state;
const Change = (..._)=>{
if (onChange) { onChange(this.GetNewData()); }
this.Update();
};
const image = Validate("UUID", newData.id) == null ? GetMedia(newData.id) : null;
const enabled = creating || editing;
return (
<Column style={style}>
<Row>
<TextInput placeholder="Media ID or URL..." enabled={enabled} style={{width: "100%", borderRadius: "5px 5px 0 0"}}
value={newData.id} onChange={val=>Change(newData.id = val)}/>
</Row>
<Row style={{position: "relative", flex: 1}}>
<DropDown style={{flex: 1}}>
<DropDownTrigger>
<Button style={{height: "100%", borderRadius: "0 0 5px 5px", display: "flex", whiteSpace: "normal", padding: 5}}
text={image
? `${image.name}: ${image.url}`
: `(click to search/create)`}/>
</DropDownTrigger>
<DropDownContent style={{left: 0, width: 600, zIndex: 1, borderRadius: "0 5px 5px 5px", padding: image ? 10 : 0}}><Column>
{image &&
<Row>
<Link style={{marginTop: 5, alignSelf: "flex-start"}} onContextMenu={e=>e.nativeEvent["handled"] = true} actionFunc={s=>{
s.main.page = "database";
s.main.database.subpage = "media";
s.main.database.selectedMediaID = image._key;
}}>
<Button text="Show details"/>
</Link>
</Row>}
{!image &&
<Column>
<MediaSearchOrCreateUI url={newData.id} enabled={enabled} onSelect={id=>Change(newData.id = id)}/>
</Column>}
</Column></DropDownContent>
</DropDown>
</Row>
<Row center mt={5} style={{width: "100%"}}>
<CheckBox text="Captured" enabled={creating || editing} value={newData.captured} onChange={val=>Change(newData.captured = val)}/>
<InfoButton ml={5} text="Whether the image/video is claimed to be a capturing of real-world footage."/>
</Row>
<Row mt={5} style={{display: "flex", alignItems: "center"}}>
<Pre>Preview width:</Pre>
<Spinner ml={5} max={100} enabled={creating || editing}
value={newData.previewWidth | 0} onChange={val=>Change(newData.previewWidth = val != 0 ? val : null)}/>
<Pre>% (0 for auto)</Pre>
</Row>
<Row mt={10}>
<SourceChainsEditorUI ref={c=>this.chainsEditor = c} enabled={creating || editing} baseData={newData.sourceChains} onChange={val=>Change(newData.sourceChains = val)}/>
</Row>
</Column>
);
}
chainsEditor: SourceChainsEditorUI;
GetValidationError() {
return GetErrorMessagesUnderElement(GetDOM(this))[0] || this.chainsEditor.GetValidationError();
}
GetNewData() {
const {newData} = this.state;
return CloneWithPrototypes(newData) as MediaAttachment;
}
}
@Observer
class MediaSearchOrCreateUI extends BaseComponentPlus({} as {url: string, enabled: boolean, onSelect: (id: string)=>void}, {}) {
render() {
const {url, enabled, onSelect} = this.props;
const mediasWithMatchingURL = GetMediasByURL(url);
return (
<>
{mediasWithMatchingURL.length == 0 && <Row style={{padding: 5}}>No media found with the url "{url}".</Row>}
{mediasWithMatchingURL.map((media, index)=>{
return <FoundMediaUI key={media._key} media={media} index={index} enabled={enabled} onSelect={()=>onSelect(media._key)}/>;
})}
<Row mt={5} style={{
//borderTop: `1px solid ${HSLA(0, 0, 1, .5)}`,
background: mediasWithMatchingURL.length % 2 == 0 ? "rgba(30,30,30,.7)" : "rgba(0,0,0,.7)",
padding: 5,
borderRadius: "0 0 5px 5px",
}}>
<Button text="Create new image" enabled={enabled && HasModPermissions(MeID())}
title={HasModPermissions(MeID()) ? null : "Only moderators can add media currently. (till review/approval system is implemented)"}
onClick={e=>{
ShowAddMediaDialog({url}, onSelect);
}}/>
</Row>
</>
);
}
}
export class FoundMediaUI extends BaseComponentPlus({} as {media: Media, index: number, enabled: boolean, onSelect: ()=>void}, {}) {
render() {
const {media, index, enabled, onSelect} = this.props;
const creator = GetUser(media.creator);
return (
<Row center
style={E(
{
whiteSpace: "normal", //cursor: "pointer",
background: index % 2 == 0 ? "rgba(30,30,30,.7)" : "rgba(0,0,0,.7)",
padding: 5,
},
index == 0 && {borderRadius: "5px 5px 0 0"},
)}
>
<Link text={`${media._key}\n(by ${creator?.displayName ?? "n/a"})`} style={{fontSize: 13, whiteSpace: "pre"}}
onContextMenu={e=>e.nativeEvent["handled"] = true}
actionFunc={s=>{
s.main.page = "database";
s.main.database.subpage = "media";
s.main.database.selectedMediaID = media._key;
}}/>
<Text ml={5} sel style={{fontSize: 13}}>{media.name}</Text>
<Button ml="auto" text="Select" enabled={enabled} style={{flexShrink: 0}} onClick={onSelect}/>
</Row>
);
}
} | {
if (forMount || props.baseData != this.props.baseData) // if base-data changed
{ this.SetState({newData: CloneWithPrototypes(props.baseData)}); }
} | identifier_body |
MediaAttachmentEditorUI.tsx | import {GetErrorMessagesUnderElement, Clone, E, CloneWithPrototypes} from "js-vextensions";
import {Column, Pre, RowLR, Spinner, TextInput, Row, DropDown, DropDownTrigger, Button, DropDownContent, Text, CheckBox} from "react-vcomponents";
import {BaseComponent, GetDOM, BaseComponentPlus} from "react-vextensions";
import {ScrollView} from "react-vscrollview";
import {TermDefinitionPanel} from "../../NodeUI/Panels/DefinitionsPanel";
import {ShowAddMediaDialog} from "UI/Database/Medias/AddMediaDialog";
import {MediaAttachment} from "@debate-map/server-link/Source/Link";
import {Validate} from "mobx-firelink";
import {GetMedia, GetMediasByURL} from "@debate-map/server-link/Source/Link";
import {Link, Observer, InfoButton} from "vwebapp-framework";
import {HasModPermissions} from "@debate-map/server-link/Source/Link";
import {MeID, GetUser} from "@debate-map/server-link/Source/Link";
import {Media} from "@debate-map/server-link/Source/Link";
import {SourceChainsEditorUI} from "../../SourceChainsEditorUI";
type Props = {baseData: MediaAttachment, creating: boolean, editing?: boolean, style?, onChange?: (newData: MediaAttachment)=>void};
export class MediaAttachmentEditorUI extends BaseComponent<Props, {newData: MediaAttachment}> {
ComponentWillMountOrReceiveProps(props, forMount) {
if (forMount || props.baseData != this.props.baseData) // if base-data changed
|
}
scrollView: ScrollView;
render() {
const {creating, editing, style, onChange} = this.props;
const {newData} = this.state;
const Change = (..._)=>{
if (onChange) { onChange(this.GetNewData()); }
this.Update();
};
const image = Validate("UUID", newData.id) == null ? GetMedia(newData.id) : null;
const enabled = creating || editing;
return (
<Column style={style}>
<Row>
<TextInput placeholder="Media ID or URL..." enabled={enabled} style={{width: "100%", borderRadius: "5px 5px 0 0"}}
value={newData.id} onChange={val=>Change(newData.id = val)}/>
</Row>
<Row style={{position: "relative", flex: 1}}>
<DropDown style={{flex: 1}}>
<DropDownTrigger>
<Button style={{height: "100%", borderRadius: "0 0 5px 5px", display: "flex", whiteSpace: "normal", padding: 5}}
text={image
? `${image.name}: ${image.url}`
: `(click to search/create)`}/>
</DropDownTrigger>
<DropDownContent style={{left: 0, width: 600, zIndex: 1, borderRadius: "0 5px 5px 5px", padding: image ? 10 : 0}}><Column>
{image &&
<Row>
<Link style={{marginTop: 5, alignSelf: "flex-start"}} onContextMenu={e=>e.nativeEvent["handled"] = true} actionFunc={s=>{
s.main.page = "database";
s.main.database.subpage = "media";
s.main.database.selectedMediaID = image._key;
}}>
<Button text="Show details"/>
</Link>
</Row>}
{!image &&
<Column>
<MediaSearchOrCreateUI url={newData.id} enabled={enabled} onSelect={id=>Change(newData.id = id)}/>
</Column>}
</Column></DropDownContent>
</DropDown>
</Row>
<Row center mt={5} style={{width: "100%"}}>
<CheckBox text="Captured" enabled={creating || editing} value={newData.captured} onChange={val=>Change(newData.captured = val)}/>
<InfoButton ml={5} text="Whether the image/video is claimed to be a capturing of real-world footage."/>
</Row>
<Row mt={5} style={{display: "flex", alignItems: "center"}}>
<Pre>Preview width:</Pre>
<Spinner ml={5} max={100} enabled={creating || editing}
value={newData.previewWidth | 0} onChange={val=>Change(newData.previewWidth = val != 0 ? val : null)}/>
<Pre>% (0 for auto)</Pre>
</Row>
<Row mt={10}>
<SourceChainsEditorUI ref={c=>this.chainsEditor = c} enabled={creating || editing} baseData={newData.sourceChains} onChange={val=>Change(newData.sourceChains = val)}/>
</Row>
</Column>
);
}
chainsEditor: SourceChainsEditorUI;
GetValidationError() {
return GetErrorMessagesUnderElement(GetDOM(this))[0] || this.chainsEditor.GetValidationError();
}
GetNewData() {
const {newData} = this.state;
return CloneWithPrototypes(newData) as MediaAttachment;
}
}
@Observer
class MediaSearchOrCreateUI extends BaseComponentPlus({} as {url: string, enabled: boolean, onSelect: (id: string)=>void}, {}) {
render() {
const {url, enabled, onSelect} = this.props;
const mediasWithMatchingURL = GetMediasByURL(url);
return (
<>
{mediasWithMatchingURL.length == 0 && <Row style={{padding: 5}}>No media found with the url "{url}".</Row>}
{mediasWithMatchingURL.map((media, index)=>{
return <FoundMediaUI key={media._key} media={media} index={index} enabled={enabled} onSelect={()=>onSelect(media._key)}/>;
})}
<Row mt={5} style={{
//borderTop: `1px solid ${HSLA(0, 0, 1, .5)}`,
background: mediasWithMatchingURL.length % 2 == 0 ? "rgba(30,30,30,.7)" : "rgba(0,0,0,.7)",
padding: 5,
borderRadius: "0 0 5px 5px",
}}>
<Button text="Create new image" enabled={enabled && HasModPermissions(MeID())}
title={HasModPermissions(MeID()) ? null : "Only moderators can add media currently. (till review/approval system is implemented)"}
onClick={e=>{
ShowAddMediaDialog({url}, onSelect);
}}/>
</Row>
</>
);
}
}
export class FoundMediaUI extends BaseComponentPlus({} as {media: Media, index: number, enabled: boolean, onSelect: ()=>void}, {}) {
render() {
const {media, index, enabled, onSelect} = this.props;
const creator = GetUser(media.creator);
return (
<Row center
style={E(
{
whiteSpace: "normal", //cursor: "pointer",
background: index % 2 == 0 ? "rgba(30,30,30,.7)" : "rgba(0,0,0,.7)",
padding: 5,
},
index == 0 && {borderRadius: "5px 5px 0 0"},
)}
>
<Link text={`${media._key}\n(by ${creator?.displayName ?? "n/a"})`} style={{fontSize: 13, whiteSpace: "pre"}}
onContextMenu={e=>e.nativeEvent["handled"] = true}
actionFunc={s=>{
s.main.page = "database";
s.main.database.subpage = "media";
s.main.database.selectedMediaID = media._key;
}}/>
<Text ml={5} sel style={{fontSize: 13}}>{media.name}</Text>
<Button ml="auto" text="Select" enabled={enabled} style={{flexShrink: 0}} onClick={onSelect}/>
</Row>
);
}
} | { this.SetState({newData: CloneWithPrototypes(props.baseData)}); } | conditional_block |
MediaAttachmentEditorUI.tsx | import {GetErrorMessagesUnderElement, Clone, E, CloneWithPrototypes} from "js-vextensions";
import {Column, Pre, RowLR, Spinner, TextInput, Row, DropDown, DropDownTrigger, Button, DropDownContent, Text, CheckBox} from "react-vcomponents";
import {BaseComponent, GetDOM, BaseComponentPlus} from "react-vextensions";
import {ScrollView} from "react-vscrollview";
import {TermDefinitionPanel} from "../../NodeUI/Panels/DefinitionsPanel";
import {ShowAddMediaDialog} from "UI/Database/Medias/AddMediaDialog";
import {MediaAttachment} from "@debate-map/server-link/Source/Link";
import {Validate} from "mobx-firelink";
import {GetMedia, GetMediasByURL} from "@debate-map/server-link/Source/Link";
import {Link, Observer, InfoButton} from "vwebapp-framework";
import {HasModPermissions} from "@debate-map/server-link/Source/Link";
import {MeID, GetUser} from "@debate-map/server-link/Source/Link";
import {Media} from "@debate-map/server-link/Source/Link";
import {SourceChainsEditorUI} from "../../SourceChainsEditorUI";
type Props = {baseData: MediaAttachment, creating: boolean, editing?: boolean, style?, onChange?: (newData: MediaAttachment)=>void};
export class MediaAttachmentEditorUI extends BaseComponent<Props, {newData: MediaAttachment}> {
ComponentWillMountOrReceiveProps(props, forMount) {
if (forMount || props.baseData != this.props.baseData) // if base-data changed
{ this.SetState({newData: CloneWithPrototypes(props.baseData)}); }
}
scrollView: ScrollView;
| () {
const {creating, editing, style, onChange} = this.props;
const {newData} = this.state;
const Change = (..._)=>{
if (onChange) { onChange(this.GetNewData()); }
this.Update();
};
const image = Validate("UUID", newData.id) == null ? GetMedia(newData.id) : null;
const enabled = creating || editing;
return (
<Column style={style}>
<Row>
<TextInput placeholder="Media ID or URL..." enabled={enabled} style={{width: "100%", borderRadius: "5px 5px 0 0"}}
value={newData.id} onChange={val=>Change(newData.id = val)}/>
</Row>
<Row style={{position: "relative", flex: 1}}>
<DropDown style={{flex: 1}}>
<DropDownTrigger>
<Button style={{height: "100%", borderRadius: "0 0 5px 5px", display: "flex", whiteSpace: "normal", padding: 5}}
text={image
? `${image.name}: ${image.url}`
: `(click to search/create)`}/>
</DropDownTrigger>
<DropDownContent style={{left: 0, width: 600, zIndex: 1, borderRadius: "0 5px 5px 5px", padding: image ? 10 : 0}}><Column>
{image &&
<Row>
<Link style={{marginTop: 5, alignSelf: "flex-start"}} onContextMenu={e=>e.nativeEvent["handled"] = true} actionFunc={s=>{
s.main.page = "database";
s.main.database.subpage = "media";
s.main.database.selectedMediaID = image._key;
}}>
<Button text="Show details"/>
</Link>
</Row>}
{!image &&
<Column>
<MediaSearchOrCreateUI url={newData.id} enabled={enabled} onSelect={id=>Change(newData.id = id)}/>
</Column>}
</Column></DropDownContent>
</DropDown>
</Row>
<Row center mt={5} style={{width: "100%"}}>
<CheckBox text="Captured" enabled={creating || editing} value={newData.captured} onChange={val=>Change(newData.captured = val)}/>
<InfoButton ml={5} text="Whether the image/video is claimed to be a capturing of real-world footage."/>
</Row>
<Row mt={5} style={{display: "flex", alignItems: "center"}}>
<Pre>Preview width:</Pre>
<Spinner ml={5} max={100} enabled={creating || editing}
value={newData.previewWidth | 0} onChange={val=>Change(newData.previewWidth = val != 0 ? val : null)}/>
<Pre>% (0 for auto)</Pre>
</Row>
<Row mt={10}>
<SourceChainsEditorUI ref={c=>this.chainsEditor = c} enabled={creating || editing} baseData={newData.sourceChains} onChange={val=>Change(newData.sourceChains = val)}/>
</Row>
</Column>
);
}
chainsEditor: SourceChainsEditorUI;
GetValidationError() {
return GetErrorMessagesUnderElement(GetDOM(this))[0] || this.chainsEditor.GetValidationError();
}
GetNewData() {
const {newData} = this.state;
return CloneWithPrototypes(newData) as MediaAttachment;
}
}
@Observer
class MediaSearchOrCreateUI extends BaseComponentPlus({} as {url: string, enabled: boolean, onSelect: (id: string)=>void}, {}) {
render() {
const {url, enabled, onSelect} = this.props;
const mediasWithMatchingURL = GetMediasByURL(url);
return (
<>
{mediasWithMatchingURL.length == 0 && <Row style={{padding: 5}}>No media found with the url "{url}".</Row>}
{mediasWithMatchingURL.map((media, index)=>{
return <FoundMediaUI key={media._key} media={media} index={index} enabled={enabled} onSelect={()=>onSelect(media._key)}/>;
})}
<Row mt={5} style={{
//borderTop: `1px solid ${HSLA(0, 0, 1, .5)}`,
background: mediasWithMatchingURL.length % 2 == 0 ? "rgba(30,30,30,.7)" : "rgba(0,0,0,.7)",
padding: 5,
borderRadius: "0 0 5px 5px",
}}>
<Button text="Create new image" enabled={enabled && HasModPermissions(MeID())}
title={HasModPermissions(MeID()) ? null : "Only moderators can add media currently. (till review/approval system is implemented)"}
onClick={e=>{
ShowAddMediaDialog({url}, onSelect);
}}/>
</Row>
</>
);
}
}
export class FoundMediaUI extends BaseComponentPlus({} as {media: Media, index: number, enabled: boolean, onSelect: ()=>void}, {}) {
render() {
const {media, index, enabled, onSelect} = this.props;
const creator = GetUser(media.creator);
return (
<Row center
style={E(
{
whiteSpace: "normal", //cursor: "pointer",
background: index % 2 == 0 ? "rgba(30,30,30,.7)" : "rgba(0,0,0,.7)",
padding: 5,
},
index == 0 && {borderRadius: "5px 5px 0 0"},
)}
>
<Link text={`${media._key}\n(by ${creator?.displayName ?? "n/a"})`} style={{fontSize: 13, whiteSpace: "pre"}}
onContextMenu={e=>e.nativeEvent["handled"] = true}
actionFunc={s=>{
s.main.page = "database";
s.main.database.subpage = "media";
s.main.database.selectedMediaID = media._key;
}}/>
<Text ml={5} sel style={{fontSize: 13}}>{media.name}</Text>
<Button ml="auto" text="Select" enabled={enabled} style={{flexShrink: 0}} onClick={onSelect}/>
</Row>
);
}
} | render | identifier_name |
MediaAttachmentEditorUI.tsx | import {GetErrorMessagesUnderElement, Clone, E, CloneWithPrototypes} from "js-vextensions";
import {Column, Pre, RowLR, Spinner, TextInput, Row, DropDown, DropDownTrigger, Button, DropDownContent, Text, CheckBox} from "react-vcomponents";
import {BaseComponent, GetDOM, BaseComponentPlus} from "react-vextensions";
import {ScrollView} from "react-vscrollview";
import {TermDefinitionPanel} from "../../NodeUI/Panels/DefinitionsPanel";
import {ShowAddMediaDialog} from "UI/Database/Medias/AddMediaDialog";
import {MediaAttachment} from "@debate-map/server-link/Source/Link";
import {Validate} from "mobx-firelink";
import {GetMedia, GetMediasByURL} from "@debate-map/server-link/Source/Link";
import {Link, Observer, InfoButton} from "vwebapp-framework";
import {HasModPermissions} from "@debate-map/server-link/Source/Link";
import {MeID, GetUser} from "@debate-map/server-link/Source/Link"; | import {SourceChainsEditorUI} from "../../SourceChainsEditorUI";
type Props = {baseData: MediaAttachment, creating: boolean, editing?: boolean, style?, onChange?: (newData: MediaAttachment)=>void};
export class MediaAttachmentEditorUI extends BaseComponent<Props, {newData: MediaAttachment}> {
ComponentWillMountOrReceiveProps(props, forMount) {
if (forMount || props.baseData != this.props.baseData) // if base-data changed
{ this.SetState({newData: CloneWithPrototypes(props.baseData)}); }
}
scrollView: ScrollView;
render() {
const {creating, editing, style, onChange} = this.props;
const {newData} = this.state;
const Change = (..._)=>{
if (onChange) { onChange(this.GetNewData()); }
this.Update();
};
const image = Validate("UUID", newData.id) == null ? GetMedia(newData.id) : null;
const enabled = creating || editing;
return (
<Column style={style}>
<Row>
<TextInput placeholder="Media ID or URL..." enabled={enabled} style={{width: "100%", borderRadius: "5px 5px 0 0"}}
value={newData.id} onChange={val=>Change(newData.id = val)}/>
</Row>
<Row style={{position: "relative", flex: 1}}>
<DropDown style={{flex: 1}}>
<DropDownTrigger>
<Button style={{height: "100%", borderRadius: "0 0 5px 5px", display: "flex", whiteSpace: "normal", padding: 5}}
text={image
? `${image.name}: ${image.url}`
: `(click to search/create)`}/>
</DropDownTrigger>
<DropDownContent style={{left: 0, width: 600, zIndex: 1, borderRadius: "0 5px 5px 5px", padding: image ? 10 : 0}}><Column>
{image &&
<Row>
<Link style={{marginTop: 5, alignSelf: "flex-start"}} onContextMenu={e=>e.nativeEvent["handled"] = true} actionFunc={s=>{
s.main.page = "database";
s.main.database.subpage = "media";
s.main.database.selectedMediaID = image._key;
}}>
<Button text="Show details"/>
</Link>
</Row>}
{!image &&
<Column>
<MediaSearchOrCreateUI url={newData.id} enabled={enabled} onSelect={id=>Change(newData.id = id)}/>
</Column>}
</Column></DropDownContent>
</DropDown>
</Row>
<Row center mt={5} style={{width: "100%"}}>
<CheckBox text="Captured" enabled={creating || editing} value={newData.captured} onChange={val=>Change(newData.captured = val)}/>
<InfoButton ml={5} text="Whether the image/video is claimed to be a capturing of real-world footage."/>
</Row>
<Row mt={5} style={{display: "flex", alignItems: "center"}}>
<Pre>Preview width:</Pre>
<Spinner ml={5} max={100} enabled={creating || editing}
value={newData.previewWidth | 0} onChange={val=>Change(newData.previewWidth = val != 0 ? val : null)}/>
<Pre>% (0 for auto)</Pre>
</Row>
<Row mt={10}>
<SourceChainsEditorUI ref={c=>this.chainsEditor = c} enabled={creating || editing} baseData={newData.sourceChains} onChange={val=>Change(newData.sourceChains = val)}/>
</Row>
</Column>
);
}
chainsEditor: SourceChainsEditorUI;
GetValidationError() {
return GetErrorMessagesUnderElement(GetDOM(this))[0] || this.chainsEditor.GetValidationError();
}
GetNewData() {
const {newData} = this.state;
return CloneWithPrototypes(newData) as MediaAttachment;
}
}
@Observer
class MediaSearchOrCreateUI extends BaseComponentPlus({} as {url: string, enabled: boolean, onSelect: (id: string)=>void}, {}) {
render() {
const {url, enabled, onSelect} = this.props;
const mediasWithMatchingURL = GetMediasByURL(url);
return (
<>
{mediasWithMatchingURL.length == 0 && <Row style={{padding: 5}}>No media found with the url "{url}".</Row>}
{mediasWithMatchingURL.map((media, index)=>{
return <FoundMediaUI key={media._key} media={media} index={index} enabled={enabled} onSelect={()=>onSelect(media._key)}/>;
})}
<Row mt={5} style={{
//borderTop: `1px solid ${HSLA(0, 0, 1, .5)}`,
background: mediasWithMatchingURL.length % 2 == 0 ? "rgba(30,30,30,.7)" : "rgba(0,0,0,.7)",
padding: 5,
borderRadius: "0 0 5px 5px",
}}>
<Button text="Create new image" enabled={enabled && HasModPermissions(MeID())}
title={HasModPermissions(MeID()) ? null : "Only moderators can add media currently. (till review/approval system is implemented)"}
onClick={e=>{
ShowAddMediaDialog({url}, onSelect);
}}/>
</Row>
</>
);
}
}
export class FoundMediaUI extends BaseComponentPlus({} as {media: Media, index: number, enabled: boolean, onSelect: ()=>void}, {}) {
render() {
const {media, index, enabled, onSelect} = this.props;
const creator = GetUser(media.creator);
return (
<Row center
style={E(
{
whiteSpace: "normal", //cursor: "pointer",
background: index % 2 == 0 ? "rgba(30,30,30,.7)" : "rgba(0,0,0,.7)",
padding: 5,
},
index == 0 && {borderRadius: "5px 5px 0 0"},
)}
>
<Link text={`${media._key}\n(by ${creator?.displayName ?? "n/a"})`} style={{fontSize: 13, whiteSpace: "pre"}}
onContextMenu={e=>e.nativeEvent["handled"] = true}
actionFunc={s=>{
s.main.page = "database";
s.main.database.subpage = "media";
s.main.database.selectedMediaID = media._key;
}}/>
<Text ml={5} sel style={{fontSize: 13}}>{media.name}</Text>
<Button ml="auto" text="Select" enabled={enabled} style={{flexShrink: 0}} onClick={onSelect}/>
</Row>
);
}
} | import {Media} from "@debate-map/server-link/Source/Link"; | random_line_split |
settings.py | """
Django settings for news_project project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
from django.core.mail import send_mail
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'dtou6-c)r2@t$p2tudrq2gjy92wsfdkst2yng^5y-akom$$f13'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ACCOUNT_ACTIVATION_DAYS = 7
LOGIN_REDIRECT_URL = 'home'
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'news_project',
'articles',
'profiles',
'taggit'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'news_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'news_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'newssitedb',
'USER': os.environ.get('DB_USER', ''),
'PASSWORD': os.environ.get("DB_PASSWORD", ''),
'HOST': '127.0.0.1',
'PORT': '5432',
'TEST': {
'NAME': 'IMAGER_TEST_DB'
}
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization | # https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
# Email Settings
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'julienawilson@gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('EM_PASS', '')
SERVER_EMAIL = 'julienawilson@gmail.com'
DEFAULT_FROM_EMAIL = "News Project" | random_line_split | |
HotkeyDialog.tsx | import React, { useState } from 'react'
import TextField from '@mui/material/TextField' | import Help from './Help'
import Fade from '@mui/material/Fade'
import { useStore } from 'components/hooks/useStore'
import { useTheme } from '@mui/material'
import CloseButton from 'components/CloseButton'
import useReduceMotion from 'libs/useReduceMotion'
import { defaultTransitionDuration } from 'libs/transition'
export default observer(() => {
const theme = useTheme()
const [search, setSearch] = useState('')
const fullScreen = useMediaQuery(theme.breakpoints.down('sm'))
const { shortcutStore } = useStore()
const { dialogOpen, closeDialog } = shortcutStore
const reduceMotion = useReduceMotion()
return (
<Dialog
open={dialogOpen}
TransitionComponent={Fade}
transitionDuration={reduceMotion ? 1 : defaultTransitionDuration}
onClose={closeDialog}
onBackdropClick={closeDialog}
fullWidth
{...{ maxWidth: 'lg', fullScreen }}
>
<DialogTitle>
<div className="flex items-end">
<h2>Keyboard Shortcuts</h2>
<div className="flex-1 mx-6">
<TextField
fullWidth
label="Search"
type="search"
variant="standard"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<div className="absolute top-0 right-0 p-2">
<CloseButton onClick={closeDialog} />
</div>
</div>
</DialogTitle>
<DialogContent style={{ minHeight: 'calc(100vh - 142px)' }}>
<Help search={search.toLowerCase()} />
</DialogContent>
</Dialog>
)
}) | import useMediaQuery from '@mui/material/useMediaQuery'
import { observer } from 'mobx-react-lite'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent' | random_line_split |
models.py | from datetime import datetime
from pymongo.connection import Connection
from django.db import models
from eventtracker.conf import settings
def get_mongo_collection():
"Open a connection to MongoDB and return the collection to use."
if settings.RIGHT_MONGODB_HOST:
connection = Connection.paired(
left=(settings.MONGODB_HOST, settings.MONGODB_PORT),
right=(settings.RIGHT_MONGODB_HOST, settings.RIGHT_MONGODB_PORT)
)
else:
connection = Connection(host=settings.MONGODB_HOST, port=settings.MONGODB_PORT)
return connection[settings.MONGODB_DB][settings.MONGODB_COLLECTION]
def save_event(collection, event, timestamp, params):
"Save the event in MongoDB collection"
collection.insert({
'event': event,
'timestamp': datetime.fromtimestamp(timestamp),
'params': params
})
class Event(models.Model):
| "Dummy model for development."
timestamp = models.DateTimeField(auto_now_add=True)
event = models.SlugField()
params = models.TextField() | identifier_body | |
models.py | from datetime import datetime
from pymongo.connection import Connection
from django.db import models
from eventtracker.conf import settings
def get_mongo_collection():
"Open a connection to MongoDB and return the collection to use."
if settings.RIGHT_MONGODB_HOST:
connection = Connection.paired(
left=(settings.MONGODB_HOST, settings.MONGODB_PORT),
right=(settings.RIGHT_MONGODB_HOST, settings.RIGHT_MONGODB_PORT)
)
else:
|
return connection[settings.MONGODB_DB][settings.MONGODB_COLLECTION]
def save_event(collection, event, timestamp, params):
"Save the event in MongoDB collection"
collection.insert({
'event': event,
'timestamp': datetime.fromtimestamp(timestamp),
'params': params
})
class Event(models.Model):
"Dummy model for development."
timestamp = models.DateTimeField(auto_now_add=True)
event = models.SlugField()
params = models.TextField()
| connection = Connection(host=settings.MONGODB_HOST, port=settings.MONGODB_PORT) | conditional_block |
models.py | from datetime import datetime
from pymongo.connection import Connection
from django.db import models
from eventtracker.conf import settings
def | ():
"Open a connection to MongoDB and return the collection to use."
if settings.RIGHT_MONGODB_HOST:
connection = Connection.paired(
left=(settings.MONGODB_HOST, settings.MONGODB_PORT),
right=(settings.RIGHT_MONGODB_HOST, settings.RIGHT_MONGODB_PORT)
)
else:
connection = Connection(host=settings.MONGODB_HOST, port=settings.MONGODB_PORT)
return connection[settings.MONGODB_DB][settings.MONGODB_COLLECTION]
def save_event(collection, event, timestamp, params):
"Save the event in MongoDB collection"
collection.insert({
'event': event,
'timestamp': datetime.fromtimestamp(timestamp),
'params': params
})
class Event(models.Model):
"Dummy model for development."
timestamp = models.DateTimeField(auto_now_add=True)
event = models.SlugField()
params = models.TextField()
| get_mongo_collection | identifier_name |
models.py | from datetime import datetime
from pymongo.connection import Connection
from django.db import models
from eventtracker.conf import settings
def get_mongo_collection():
"Open a connection to MongoDB and return the collection to use."
if settings.RIGHT_MONGODB_HOST: | left=(settings.MONGODB_HOST, settings.MONGODB_PORT),
right=(settings.RIGHT_MONGODB_HOST, settings.RIGHT_MONGODB_PORT)
)
else:
connection = Connection(host=settings.MONGODB_HOST, port=settings.MONGODB_PORT)
return connection[settings.MONGODB_DB][settings.MONGODB_COLLECTION]
def save_event(collection, event, timestamp, params):
"Save the event in MongoDB collection"
collection.insert({
'event': event,
'timestamp': datetime.fromtimestamp(timestamp),
'params': params
})
class Event(models.Model):
"Dummy model for development."
timestamp = models.DateTimeField(auto_now_add=True)
event = models.SlugField()
params = models.TextField() | connection = Connection.paired( | random_line_split |
interface.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
use tokenizer::states;
use std::borrow::Cow;
use string_cache::{Atom, QualName};
use tendril::StrTendril;
pub use self::TagKind::{StartTag, EndTag};
pub use self::Token::{DoctypeToken, TagToken, CommentToken, CharacterTokens};
pub use self::Token::{NullCharacterToken, EOFToken, ParseError};
/// A `DOCTYPE` token.
// FIXME: already exists in Servo DOM
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Doctype {
pub name: Option<StrTendril>,
pub public_id: Option<StrTendril>,
pub system_id: Option<StrTendril>,
pub force_quirks: bool,
}
impl Doctype {
pub fn new() -> Doctype {
Doctype {
name: None,
public_id: None,
system_id: None,
force_quirks: false,
}
}
}
/// A tag attribute.
///
/// The namespace on the attribute name is almost always ns!("").
/// The tokenizer creates all attributes this way, but the tree
/// builder will adjust certain attribute names inside foreign
/// content (MathML, SVG).
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
pub struct Attribute {
pub name: QualName,
pub value: StrTendril,
}
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
pub enum TagKind {
StartTag,
EndTag,
}
/// A tag token.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Tag {
pub kind: TagKind,
pub name: Atom,
pub self_closing: bool,
pub attrs: Vec<Attribute>,
}
impl Tag {
/// Are the tags equivalent when we don't care about attribute order?
/// Also ignores the self-closing flag.
pub fn equiv_modulo_attr_order(&self, other: &Tag) -> bool |
}
#[derive(PartialEq, Eq, Debug)]
pub enum Token {
DoctypeToken(Doctype),
TagToken(Tag),
CommentToken(StrTendril),
CharacterTokens(StrTendril),
NullCharacterToken,
EOFToken,
ParseError(Cow<'static, str>),
}
// FIXME: rust-lang/rust#22629
unsafe impl Send for Token { }
/// Types which can receive tokens from the tokenizer.
pub trait TokenSink {
/// Process a token.
fn process_token(&mut self, token: Token);
/// Used in the markup declaration open state. By default, this always
/// returns false and thus all CDATA sections are tokenized as bogus
/// comments.
/// https://html.spec.whatwg.org/multipage/#markup-declaration-open-state
fn adjusted_current_node_present_but_not_in_html_namespace(&self) -> bool {
false
}
/// The tokenizer will call this after emitting any tag.
/// This allows the tree builder to change the tokenizer's state.
/// By default no state changes occur.
fn query_state_change(&mut self) -> Option<states::State> {
None
}
}
| {
if (self.kind != other.kind) || (self.name != other.name) {
return false;
}
let mut self_attrs = self.attrs.clone();
let mut other_attrs = other.attrs.clone();
self_attrs.sort();
other_attrs.sort();
self_attrs == other_attrs
} | identifier_body |
interface.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
use tokenizer::states;
use std::borrow::Cow;
use string_cache::{Atom, QualName};
use tendril::StrTendril;
pub use self::TagKind::{StartTag, EndTag};
pub use self::Token::{DoctypeToken, TagToken, CommentToken, CharacterTokens};
pub use self::Token::{NullCharacterToken, EOFToken, ParseError};
/// A `DOCTYPE` token.
// FIXME: already exists in Servo DOM
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Doctype {
pub name: Option<StrTendril>,
pub public_id: Option<StrTendril>,
pub system_id: Option<StrTendril>,
pub force_quirks: bool,
}
impl Doctype {
pub fn new() -> Doctype {
Doctype {
name: None,
public_id: None,
system_id: None,
force_quirks: false,
}
}
}
/// A tag attribute.
///
/// The namespace on the attribute name is almost always ns!("").
/// The tokenizer creates all attributes this way, but the tree
/// builder will adjust certain attribute names inside foreign
/// content (MathML, SVG).
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
pub struct Attribute {
pub name: QualName,
pub value: StrTendril,
}
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
pub enum TagKind {
StartTag,
EndTag,
}
/// A tag token.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Tag {
pub kind: TagKind,
pub name: Atom,
pub self_closing: bool,
pub attrs: Vec<Attribute>,
}
impl Tag {
/// Are the tags equivalent when we don't care about attribute order?
/// Also ignores the self-closing flag.
pub fn | (&self, other: &Tag) -> bool {
if (self.kind != other.kind) || (self.name != other.name) {
return false;
}
let mut self_attrs = self.attrs.clone();
let mut other_attrs = other.attrs.clone();
self_attrs.sort();
other_attrs.sort();
self_attrs == other_attrs
}
}
#[derive(PartialEq, Eq, Debug)]
pub enum Token {
DoctypeToken(Doctype),
TagToken(Tag),
CommentToken(StrTendril),
CharacterTokens(StrTendril),
NullCharacterToken,
EOFToken,
ParseError(Cow<'static, str>),
}
// FIXME: rust-lang/rust#22629
unsafe impl Send for Token { }
/// Types which can receive tokens from the tokenizer.
pub trait TokenSink {
/// Process a token.
fn process_token(&mut self, token: Token);
/// Used in the markup declaration open state. By default, this always
/// returns false and thus all CDATA sections are tokenized as bogus
/// comments.
/// https://html.spec.whatwg.org/multipage/#markup-declaration-open-state
fn adjusted_current_node_present_but_not_in_html_namespace(&self) -> bool {
false
}
/// The tokenizer will call this after emitting any tag.
/// This allows the tree builder to change the tokenizer's state.
/// By default no state changes occur.
fn query_state_change(&mut self) -> Option<states::State> {
None
}
}
| equiv_modulo_attr_order | identifier_name |
interface.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
use tokenizer::states;
use std::borrow::Cow;
use string_cache::{Atom, QualName};
use tendril::StrTendril;
pub use self::TagKind::{StartTag, EndTag};
pub use self::Token::{DoctypeToken, TagToken, CommentToken, CharacterTokens};
pub use self::Token::{NullCharacterToken, EOFToken, ParseError};
/// A `DOCTYPE` token.
// FIXME: already exists in Servo DOM
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Doctype {
pub name: Option<StrTendril>,
pub public_id: Option<StrTendril>,
pub system_id: Option<StrTendril>,
pub force_quirks: bool,
}
impl Doctype {
pub fn new() -> Doctype {
Doctype {
name: None,
public_id: None,
system_id: None,
force_quirks: false,
}
}
}
/// A tag attribute.
///
/// The namespace on the attribute name is almost always ns!("").
/// The tokenizer creates all attributes this way, but the tree
/// builder will adjust certain attribute names inside foreign
/// content (MathML, SVG).
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
pub struct Attribute {
pub name: QualName,
pub value: StrTendril,
}
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
pub enum TagKind {
StartTag,
EndTag,
}
/// A tag token.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Tag {
pub kind: TagKind,
pub name: Atom,
pub self_closing: bool,
pub attrs: Vec<Attribute>,
}
impl Tag {
/// Are the tags equivalent when we don't care about attribute order?
/// Also ignores the self-closing flag.
pub fn equiv_modulo_attr_order(&self, other: &Tag) -> bool {
if (self.kind != other.kind) || (self.name != other.name) {
return false;
}
let mut self_attrs = self.attrs.clone();
let mut other_attrs = other.attrs.clone();
self_attrs.sort();
other_attrs.sort();
self_attrs == other_attrs
}
}
#[derive(PartialEq, Eq, Debug)]
pub enum Token {
DoctypeToken(Doctype),
TagToken(Tag),
CommentToken(StrTendril),
CharacterTokens(StrTendril),
NullCharacterToken,
EOFToken,
ParseError(Cow<'static, str>),
}
// FIXME: rust-lang/rust#22629
unsafe impl Send for Token { }
/// Types which can receive tokens from the tokenizer.
pub trait TokenSink {
/// Process a token.
fn process_token(&mut self, token: Token);
/// Used in the markup declaration open state. By default, this always
/// returns false and thus all CDATA sections are tokenized as bogus
/// comments.
/// https://html.spec.whatwg.org/multipage/#markup-declaration-open-state
fn adjusted_current_node_present_but_not_in_html_namespace(&self) -> bool {
false
} | None
}
} |
/// The tokenizer will call this after emitting any tag.
/// This allows the tree builder to change the tokenizer's state.
/// By default no state changes occur.
fn query_state_change(&mut self) -> Option<states::State> { | random_line_split |
interface.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
use tokenizer::states;
use std::borrow::Cow;
use string_cache::{Atom, QualName};
use tendril::StrTendril;
pub use self::TagKind::{StartTag, EndTag};
pub use self::Token::{DoctypeToken, TagToken, CommentToken, CharacterTokens};
pub use self::Token::{NullCharacterToken, EOFToken, ParseError};
/// A `DOCTYPE` token.
// FIXME: already exists in Servo DOM
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Doctype {
pub name: Option<StrTendril>,
pub public_id: Option<StrTendril>,
pub system_id: Option<StrTendril>,
pub force_quirks: bool,
}
impl Doctype {
pub fn new() -> Doctype {
Doctype {
name: None,
public_id: None,
system_id: None,
force_quirks: false,
}
}
}
/// A tag attribute.
///
/// The namespace on the attribute name is almost always ns!("").
/// The tokenizer creates all attributes this way, but the tree
/// builder will adjust certain attribute names inside foreign
/// content (MathML, SVG).
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
pub struct Attribute {
pub name: QualName,
pub value: StrTendril,
}
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
pub enum TagKind {
StartTag,
EndTag,
}
/// A tag token.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Tag {
pub kind: TagKind,
pub name: Atom,
pub self_closing: bool,
pub attrs: Vec<Attribute>,
}
impl Tag {
/// Are the tags equivalent when we don't care about attribute order?
/// Also ignores the self-closing flag.
pub fn equiv_modulo_attr_order(&self, other: &Tag) -> bool {
if (self.kind != other.kind) || (self.name != other.name) |
let mut self_attrs = self.attrs.clone();
let mut other_attrs = other.attrs.clone();
self_attrs.sort();
other_attrs.sort();
self_attrs == other_attrs
}
}
#[derive(PartialEq, Eq, Debug)]
pub enum Token {
DoctypeToken(Doctype),
TagToken(Tag),
CommentToken(StrTendril),
CharacterTokens(StrTendril),
NullCharacterToken,
EOFToken,
ParseError(Cow<'static, str>),
}
// FIXME: rust-lang/rust#22629
unsafe impl Send for Token { }
/// Types which can receive tokens from the tokenizer.
pub trait TokenSink {
/// Process a token.
fn process_token(&mut self, token: Token);
/// Used in the markup declaration open state. By default, this always
/// returns false and thus all CDATA sections are tokenized as bogus
/// comments.
/// https://html.spec.whatwg.org/multipage/#markup-declaration-open-state
fn adjusted_current_node_present_but_not_in_html_namespace(&self) -> bool {
false
}
/// The tokenizer will call this after emitting any tag.
/// This allows the tree builder to change the tokenizer's state.
/// By default no state changes occur.
fn query_state_change(&mut self) -> Option<states::State> {
None
}
}
| {
return false;
} | conditional_block |
settings.py | # Django settings for wireframe project.
import os
PROJECT_DIR = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'wire.db' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'wire.db'
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
WIREFRAME_MEDIA_ROOT = os.path.join(PROJECT_DIR, os.pardir, 'wireframes', 'media', 'wireframes')
ADMIN_MEDIA_ROOT = os.path.join(PROJECT_DIR, os.pardir, 'admin_media', '')
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody. | TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
#'django.middleware.doc.XViewMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
ROOT_URLCONF = 'example.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), "templates"),
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.i18n",
"django.core.context_processors.debug",
"django.core.context_processors.request",
"django.core.context_processors.media",
)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'wireframes',
) | SECRET_KEY = 'p)vc32rphaob@!7nze8@6ih5c_@ygjc%@csf*6^+d^((+%$4p#'
| random_line_split |
filemanager.rs | use std::path::Path;
use crate::channel::*;
use crate::threadpool::*;
use crossbeam_channel::*;
pub enum FileManagerRequests {
ReadAll {
file: String,
sender: Sender<Message>,
},
}
pub struct ReadAllResult {}
pub enum FileManagerRequestsResponses {
Ok,
ReadAllResult(ReadAllResult),
}
pub struct FileManager<'a> {
epoll: libc::c_int,
dispatcher: TypedThreadDispatcher<'a, FileManagerRequests, FileManagerRequestsResponses>,
}
pub struct TempFile {
pub path: std::path::PathBuf,
}
impl TempFile {
pub fn all_equal(path: &str, data: u8) -> std::io::Result<Self> {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut f = std::fs::File::create(&path)?;
let data = vec![data; 16 * 1024];
f.write_all(&data)?;
f.sync_all()?;
Ok(Self { path: path.into() })
}
pub fn with_callback<F>(path: &str, f: F) -> std::io::Result<Self>
where
F: Fn(usize) -> u8,
{
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut file = std::fs::File::create(&path)?;
let mut data = vec![0u8; 16 * 1024];
for (i, v) in data.iter_mut().enumerate() {
*v = f(i);
}
file.write_all(&data)?;
file.sync_all()?;
Ok(Self { path: path.into() })
}
pub fn random(path: &str, mut size: usize) -> std::io::Result<Self> {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut file = std::fs::File::create(&path)?;
let mut data = vec![0u8; 4 * 1024];
while size > 0 {
for v in (4 * 1024).min(0) {
*v = rand::random::<u8>()
}
size -= data.len();
file.write_all(&data)?;
}
file.sync_all()?;
Ok(Self { path: path.into() })
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.path.as_path());
}
}
pub fn handle_read_all<P: AsRef<Path>>(file: P, sender: &Sender<Message>) -> ReadAllResult {
let mut path = file.as_ref().to_str().unwrap().to_string();
path.push('\0');
let fd = {
let r = unsafe {
libc::open(
path.as_ptr() as *const i8,
libc::O_RDONLY, /*| libc::O_NONBLOCK*/
)
};
if r < 0 {
let err = errno::errno();
eprintln!("{}", err);
}
// let flags = unsafe { libc::fcntl(r, libc::F_GETFL, 0) };
// let _rcontrol = unsafe { libc::fcntl(r, libc::F_SETFL, flags | libc::O_NONBLOCK) };
r
};
// let _r = unsafe {
// libc::posix_fadvise(fd, 0, 0, libc::POSIX_FADV_NORMAL | libc::POSIX_FADV_NOREUSE)
// };
let mut offset = 0;
loop {
let mut buffer = Buffer::all_zero(4 * 1024);
buffer.size = unsafe {
let r = libc::pread(
fd,
buffer.data.as_mut_ptr() as *mut libc::c_void,
buffer.size,
offset,
);
if r == 0 {
break;
}
if r < 0 {
let err = errno::errno();
eprintln!("{}", err); // TODO
break;
}
r as usize
};
offset += buffer.size as i64;
let _ = sender.send(Message::Buffer(buffer));
}
let _ = sender.send(Message::Eof);
unsafe { libc::close(fd) };
ReadAllResult {}
}
impl<'a> FileManager<'a> {
pub fn new(pool: &mut Threadpool<'a>) -> Self {
let dispatcher = pool.new_dispatcher(move |request| match request {
FileManagerRequests::ReadAll { file, sender } => {
FileManagerRequestsResponses::ReadAllResult(handle_read_all(file, sender))
}
});
let epoll = {
let r = unsafe { libc::epoll_create1(0) };
if r < 0 {
let err = errno::errno();
eprintln!("{}", err); //TODO
}
r
};
Self { dispatcher, epoll }
}
fn send(&mut self, req: FileManagerRequests) -> RunResult<FileManagerRequestsResponses> {
self.dispatcher.send(req)
}
pub fn read_all(
&mut self,
file: &str,
sender: Sender<Message>,
) -> std::result::Result<
ReceiverFutureMap<FileManagerRequestsResponses, ReadAllResult>,
ThreadpoolRunError,
> {
let future = self
.send(FileManagerRequests::ReadAll {
file: file.to_string(),
sender,
})?
.map(|x| {
if let FileManagerRequestsResponses::ReadAllResult(r) = x {
r | }
});
Ok(future)
}
}
impl<'a> Drop for FileManager<'a> {
fn drop(&mut self) {
if self.epoll > 0 {
unsafe { libc::close(self.epoll) };
}
}
}
#[cfg(test)]
mod tests {
use crate::threadpool::Threadpool;
use crossbeam_channel::*;
#[test]
fn read_all() {
let file =
super::TempFile::all_equal(".test.read_all", 1).expect("Cannot create temo file");
let mut pool = Threadpool::with_qty(1).expect("Cannot create Threadpool");
let mut mgr = super::FileManager::new(&mut pool);
let (sender, receiver) = bounded(4);
let readl_all_result = mgr
.read_all(file.path.to_str().unwrap(), 1, sender)
.expect("Cannot read file");
for _ in 0..4 {
if let Ok(crate::channel::Message::Buffer(buffer, next)) =
receiver.recv_timeout(std::time::Duration::from_secs(1))
{
testlib::assert!(next == 1);
testlib::assert!(buffer.data.len() == 4096);
testlib::assert!(buffer.data.iter().all(|x| *x == 1u8));
}
}
readl_all_result
.wait(std::time::Duration::from_secs(1))
.expect("Read all timeout");
}
} | } else {
panic!("unexpected result") | random_line_split |
filemanager.rs | use std::path::Path;
use crate::channel::*;
use crate::threadpool::*;
use crossbeam_channel::*;
pub enum FileManagerRequests {
ReadAll {
file: String,
sender: Sender<Message>,
},
}
pub struct ReadAllResult {}
pub enum | {
Ok,
ReadAllResult(ReadAllResult),
}
pub struct FileManager<'a> {
epoll: libc::c_int,
dispatcher: TypedThreadDispatcher<'a, FileManagerRequests, FileManagerRequestsResponses>,
}
pub struct TempFile {
pub path: std::path::PathBuf,
}
impl TempFile {
pub fn all_equal(path: &str, data: u8) -> std::io::Result<Self> {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut f = std::fs::File::create(&path)?;
let data = vec![data; 16 * 1024];
f.write_all(&data)?;
f.sync_all()?;
Ok(Self { path: path.into() })
}
pub fn with_callback<F>(path: &str, f: F) -> std::io::Result<Self>
where
F: Fn(usize) -> u8,
{
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut file = std::fs::File::create(&path)?;
let mut data = vec![0u8; 16 * 1024];
for (i, v) in data.iter_mut().enumerate() {
*v = f(i);
}
file.write_all(&data)?;
file.sync_all()?;
Ok(Self { path: path.into() })
}
pub fn random(path: &str, mut size: usize) -> std::io::Result<Self> {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut file = std::fs::File::create(&path)?;
let mut data = vec![0u8; 4 * 1024];
while size > 0 {
for v in (4 * 1024).min(0) {
*v = rand::random::<u8>()
}
size -= data.len();
file.write_all(&data)?;
}
file.sync_all()?;
Ok(Self { path: path.into() })
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.path.as_path());
}
}
pub fn handle_read_all<P: AsRef<Path>>(file: P, sender: &Sender<Message>) -> ReadAllResult {
let mut path = file.as_ref().to_str().unwrap().to_string();
path.push('\0');
let fd = {
let r = unsafe {
libc::open(
path.as_ptr() as *const i8,
libc::O_RDONLY, /*| libc::O_NONBLOCK*/
)
};
if r < 0 {
let err = errno::errno();
eprintln!("{}", err);
}
// let flags = unsafe { libc::fcntl(r, libc::F_GETFL, 0) };
// let _rcontrol = unsafe { libc::fcntl(r, libc::F_SETFL, flags | libc::O_NONBLOCK) };
r
};
// let _r = unsafe {
// libc::posix_fadvise(fd, 0, 0, libc::POSIX_FADV_NORMAL | libc::POSIX_FADV_NOREUSE)
// };
let mut offset = 0;
loop {
let mut buffer = Buffer::all_zero(4 * 1024);
buffer.size = unsafe {
let r = libc::pread(
fd,
buffer.data.as_mut_ptr() as *mut libc::c_void,
buffer.size,
offset,
);
if r == 0 {
break;
}
if r < 0 {
let err = errno::errno();
eprintln!("{}", err); // TODO
break;
}
r as usize
};
offset += buffer.size as i64;
let _ = sender.send(Message::Buffer(buffer));
}
let _ = sender.send(Message::Eof);
unsafe { libc::close(fd) };
ReadAllResult {}
}
impl<'a> FileManager<'a> {
pub fn new(pool: &mut Threadpool<'a>) -> Self {
let dispatcher = pool.new_dispatcher(move |request| match request {
FileManagerRequests::ReadAll { file, sender } => {
FileManagerRequestsResponses::ReadAllResult(handle_read_all(file, sender))
}
});
let epoll = {
let r = unsafe { libc::epoll_create1(0) };
if r < 0 {
let err = errno::errno();
eprintln!("{}", err); //TODO
}
r
};
Self { dispatcher, epoll }
}
fn send(&mut self, req: FileManagerRequests) -> RunResult<FileManagerRequestsResponses> {
self.dispatcher.send(req)
}
pub fn read_all(
&mut self,
file: &str,
sender: Sender<Message>,
) -> std::result::Result<
ReceiverFutureMap<FileManagerRequestsResponses, ReadAllResult>,
ThreadpoolRunError,
> {
let future = self
.send(FileManagerRequests::ReadAll {
file: file.to_string(),
sender,
})?
.map(|x| {
if let FileManagerRequestsResponses::ReadAllResult(r) = x {
r
} else {
panic!("unexpected result")
}
});
Ok(future)
}
}
impl<'a> Drop for FileManager<'a> {
fn drop(&mut self) {
if self.epoll > 0 {
unsafe { libc::close(self.epoll) };
}
}
}
#[cfg(test)]
mod tests {
use crate::threadpool::Threadpool;
use crossbeam_channel::*;
#[test]
fn read_all() {
let file =
super::TempFile::all_equal(".test.read_all", 1).expect("Cannot create temo file");
let mut pool = Threadpool::with_qty(1).expect("Cannot create Threadpool");
let mut mgr = super::FileManager::new(&mut pool);
let (sender, receiver) = bounded(4);
let readl_all_result = mgr
.read_all(file.path.to_str().unwrap(), 1, sender)
.expect("Cannot read file");
for _ in 0..4 {
if let Ok(crate::channel::Message::Buffer(buffer, next)) =
receiver.recv_timeout(std::time::Duration::from_secs(1))
{
testlib::assert!(next == 1);
testlib::assert!(buffer.data.len() == 4096);
testlib::assert!(buffer.data.iter().all(|x| *x == 1u8));
}
}
readl_all_result
.wait(std::time::Duration::from_secs(1))
.expect("Read all timeout");
}
}
| FileManagerRequestsResponses | identifier_name |
filemanager.rs | use std::path::Path;
use crate::channel::*;
use crate::threadpool::*;
use crossbeam_channel::*;
pub enum FileManagerRequests {
ReadAll {
file: String,
sender: Sender<Message>,
},
}
pub struct ReadAllResult {}
pub enum FileManagerRequestsResponses {
Ok,
ReadAllResult(ReadAllResult),
}
pub struct FileManager<'a> {
epoll: libc::c_int,
dispatcher: TypedThreadDispatcher<'a, FileManagerRequests, FileManagerRequestsResponses>,
}
pub struct TempFile {
pub path: std::path::PathBuf,
}
impl TempFile {
pub fn all_equal(path: &str, data: u8) -> std::io::Result<Self> {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut f = std::fs::File::create(&path)?;
let data = vec![data; 16 * 1024];
f.write_all(&data)?;
f.sync_all()?;
Ok(Self { path: path.into() })
}
pub fn with_callback<F>(path: &str, f: F) -> std::io::Result<Self>
where
F: Fn(usize) -> u8,
{
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut file = std::fs::File::create(&path)?;
let mut data = vec![0u8; 16 * 1024];
for (i, v) in data.iter_mut().enumerate() {
*v = f(i);
}
file.write_all(&data)?;
file.sync_all()?;
Ok(Self { path: path.into() })
}
pub fn random(path: &str, mut size: usize) -> std::io::Result<Self> {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut file = std::fs::File::create(&path)?;
let mut data = vec![0u8; 4 * 1024];
while size > 0 {
for v in (4 * 1024).min(0) {
*v = rand::random::<u8>()
}
size -= data.len();
file.write_all(&data)?;
}
file.sync_all()?;
Ok(Self { path: path.into() })
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.path.as_path());
}
}
pub fn handle_read_all<P: AsRef<Path>>(file: P, sender: &Sender<Message>) -> ReadAllResult {
let mut path = file.as_ref().to_str().unwrap().to_string();
path.push('\0');
let fd = {
let r = unsafe {
libc::open(
path.as_ptr() as *const i8,
libc::O_RDONLY, /*| libc::O_NONBLOCK*/
)
};
if r < 0 {
let err = errno::errno();
eprintln!("{}", err);
}
// let flags = unsafe { libc::fcntl(r, libc::F_GETFL, 0) };
// let _rcontrol = unsafe { libc::fcntl(r, libc::F_SETFL, flags | libc::O_NONBLOCK) };
r
};
// let _r = unsafe {
// libc::posix_fadvise(fd, 0, 0, libc::POSIX_FADV_NORMAL | libc::POSIX_FADV_NOREUSE)
// };
let mut offset = 0;
loop {
let mut buffer = Buffer::all_zero(4 * 1024);
buffer.size = unsafe {
let r = libc::pread(
fd,
buffer.data.as_mut_ptr() as *mut libc::c_void,
buffer.size,
offset,
);
if r == 0 {
break;
}
if r < 0 {
let err = errno::errno();
eprintln!("{}", err); // TODO
break;
}
r as usize
};
offset += buffer.size as i64;
let _ = sender.send(Message::Buffer(buffer));
}
let _ = sender.send(Message::Eof);
unsafe { libc::close(fd) };
ReadAllResult {}
}
impl<'a> FileManager<'a> {
pub fn new(pool: &mut Threadpool<'a>) -> Self {
let dispatcher = pool.new_dispatcher(move |request| match request {
FileManagerRequests::ReadAll { file, sender } => {
FileManagerRequestsResponses::ReadAllResult(handle_read_all(file, sender))
}
});
let epoll = {
let r = unsafe { libc::epoll_create1(0) };
if r < 0 {
let err = errno::errno();
eprintln!("{}", err); //TODO
}
r
};
Self { dispatcher, epoll }
}
fn send(&mut self, req: FileManagerRequests) -> RunResult<FileManagerRequestsResponses> {
self.dispatcher.send(req)
}
pub fn read_all(
&mut self,
file: &str,
sender: Sender<Message>,
) -> std::result::Result<
ReceiverFutureMap<FileManagerRequestsResponses, ReadAllResult>,
ThreadpoolRunError,
> {
let future = self
.send(FileManagerRequests::ReadAll {
file: file.to_string(),
sender,
})?
.map(|x| {
if let FileManagerRequestsResponses::ReadAllResult(r) = x | else {
panic!("unexpected result")
}
});
Ok(future)
}
}
impl<'a> Drop for FileManager<'a> {
fn drop(&mut self) {
if self.epoll > 0 {
unsafe { libc::close(self.epoll) };
}
}
}
#[cfg(test)]
mod tests {
use crate::threadpool::Threadpool;
use crossbeam_channel::*;
#[test]
fn read_all() {
let file =
super::TempFile::all_equal(".test.read_all", 1).expect("Cannot create temo file");
let mut pool = Threadpool::with_qty(1).expect("Cannot create Threadpool");
let mut mgr = super::FileManager::new(&mut pool);
let (sender, receiver) = bounded(4);
let readl_all_result = mgr
.read_all(file.path.to_str().unwrap(), 1, sender)
.expect("Cannot read file");
for _ in 0..4 {
if let Ok(crate::channel::Message::Buffer(buffer, next)) =
receiver.recv_timeout(std::time::Duration::from_secs(1))
{
testlib::assert!(next == 1);
testlib::assert!(buffer.data.len() == 4096);
testlib::assert!(buffer.data.iter().all(|x| *x == 1u8));
}
}
readl_all_result
.wait(std::time::Duration::from_secs(1))
.expect("Read all timeout");
}
}
| {
r
} | conditional_block |
filemanager.rs | use std::path::Path;
use crate::channel::*;
use crate::threadpool::*;
use crossbeam_channel::*;
pub enum FileManagerRequests {
ReadAll {
file: String,
sender: Sender<Message>,
},
}
pub struct ReadAllResult {}
pub enum FileManagerRequestsResponses {
Ok,
ReadAllResult(ReadAllResult),
}
pub struct FileManager<'a> {
epoll: libc::c_int,
dispatcher: TypedThreadDispatcher<'a, FileManagerRequests, FileManagerRequestsResponses>,
}
pub struct TempFile {
pub path: std::path::PathBuf,
}
impl TempFile {
pub fn all_equal(path: &str, data: u8) -> std::io::Result<Self> {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut f = std::fs::File::create(&path)?;
let data = vec![data; 16 * 1024];
f.write_all(&data)?;
f.sync_all()?;
Ok(Self { path: path.into() })
}
pub fn with_callback<F>(path: &str, f: F) -> std::io::Result<Self>
where
F: Fn(usize) -> u8,
|
pub fn random(path: &str, mut size: usize) -> std::io::Result<Self> {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut file = std::fs::File::create(&path)?;
let mut data = vec![0u8; 4 * 1024];
while size > 0 {
for v in (4 * 1024).min(0) {
*v = rand::random::<u8>()
}
size -= data.len();
file.write_all(&data)?;
}
file.sync_all()?;
Ok(Self { path: path.into() })
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.path.as_path());
}
}
pub fn handle_read_all<P: AsRef<Path>>(file: P, sender: &Sender<Message>) -> ReadAllResult {
let mut path = file.as_ref().to_str().unwrap().to_string();
path.push('\0');
let fd = {
let r = unsafe {
libc::open(
path.as_ptr() as *const i8,
libc::O_RDONLY, /*| libc::O_NONBLOCK*/
)
};
if r < 0 {
let err = errno::errno();
eprintln!("{}", err);
}
// let flags = unsafe { libc::fcntl(r, libc::F_GETFL, 0) };
// let _rcontrol = unsafe { libc::fcntl(r, libc::F_SETFL, flags | libc::O_NONBLOCK) };
r
};
// let _r = unsafe {
// libc::posix_fadvise(fd, 0, 0, libc::POSIX_FADV_NORMAL | libc::POSIX_FADV_NOREUSE)
// };
let mut offset = 0;
loop {
let mut buffer = Buffer::all_zero(4 * 1024);
buffer.size = unsafe {
let r = libc::pread(
fd,
buffer.data.as_mut_ptr() as *mut libc::c_void,
buffer.size,
offset,
);
if r == 0 {
break;
}
if r < 0 {
let err = errno::errno();
eprintln!("{}", err); // TODO
break;
}
r as usize
};
offset += buffer.size as i64;
let _ = sender.send(Message::Buffer(buffer));
}
let _ = sender.send(Message::Eof);
unsafe { libc::close(fd) };
ReadAllResult {}
}
impl<'a> FileManager<'a> {
pub fn new(pool: &mut Threadpool<'a>) -> Self {
let dispatcher = pool.new_dispatcher(move |request| match request {
FileManagerRequests::ReadAll { file, sender } => {
FileManagerRequestsResponses::ReadAllResult(handle_read_all(file, sender))
}
});
let epoll = {
let r = unsafe { libc::epoll_create1(0) };
if r < 0 {
let err = errno::errno();
eprintln!("{}", err); //TODO
}
r
};
Self { dispatcher, epoll }
}
fn send(&mut self, req: FileManagerRequests) -> RunResult<FileManagerRequestsResponses> {
self.dispatcher.send(req)
}
pub fn read_all(
&mut self,
file: &str,
sender: Sender<Message>,
) -> std::result::Result<
ReceiverFutureMap<FileManagerRequestsResponses, ReadAllResult>,
ThreadpoolRunError,
> {
let future = self
.send(FileManagerRequests::ReadAll {
file: file.to_string(),
sender,
})?
.map(|x| {
if let FileManagerRequestsResponses::ReadAllResult(r) = x {
r
} else {
panic!("unexpected result")
}
});
Ok(future)
}
}
impl<'a> Drop for FileManager<'a> {
fn drop(&mut self) {
if self.epoll > 0 {
unsafe { libc::close(self.epoll) };
}
}
}
#[cfg(test)]
mod tests {
use crate::threadpool::Threadpool;
use crossbeam_channel::*;
#[test]
fn read_all() {
let file =
super::TempFile::all_equal(".test.read_all", 1).expect("Cannot create temo file");
let mut pool = Threadpool::with_qty(1).expect("Cannot create Threadpool");
let mut mgr = super::FileManager::new(&mut pool);
let (sender, receiver) = bounded(4);
let readl_all_result = mgr
.read_all(file.path.to_str().unwrap(), 1, sender)
.expect("Cannot read file");
for _ in 0..4 {
if let Ok(crate::channel::Message::Buffer(buffer, next)) =
receiver.recv_timeout(std::time::Duration::from_secs(1))
{
testlib::assert!(next == 1);
testlib::assert!(buffer.data.len() == 4096);
testlib::assert!(buffer.data.iter().all(|x| *x == 1u8));
}
}
readl_all_result
.wait(std::time::Duration::from_secs(1))
.expect("Read all timeout");
}
}
| {
use std::io::*;
let _ = std::fs::remove_file(&path);
let mut file = std::fs::File::create(&path)?;
let mut data = vec![0u8; 16 * 1024];
for (i, v) in data.iter_mut().enumerate() {
*v = f(i);
}
file.write_all(&data)?;
file.sync_all()?;
Ok(Self { path: path.into() })
} | identifier_body |
macros.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | => ( ::syscall::syscall0(
::syscall::nr::$nr) );
($nr:ident, $a1:expr)
=> ( ::syscall::syscall1(
::syscall::nr::$nr,
$a1 as usize) );
($nr:ident, $a1:expr, $a2:expr)
=> ( ::syscall::syscall2(
::syscall::nr::$nr,
$a1 as usize, $a2 as usize) );
($nr:ident, $a1:expr, $a2:expr, $a3:expr)
=> ( ::syscall::syscall3(
::syscall::nr::$nr,
$a1 as usize, $a2 as usize, $a3 as usize) );
($nr:ident, $a1:expr, $a2:expr, $a3:expr, $a4:expr)
=> ( ::syscall::syscall4(
::syscall::nr::$nr,
$a1 as usize, $a2 as usize, $a3 as usize,
$a4 as usize) );
($nr:ident, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr)
=> ( ::syscall::syscall5(
::syscall::nr::$nr,
$a1 as usize, $a2 as usize, $a3 as usize,
$a4 as usize, $a5 as usize) );
($nr:ident, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr, $a6:expr)
=> ( ::syscall::syscall6(
::syscall::nr::$nr,
$a1 as usize, $a2 as usize, $a3 as usize,
$a4 as usize, $a5 as usize, $a6 as usize) );
} |
#[macro_export]
macro_rules! syscall {
($nr:ident) | random_line_split |
index.ts | import {
EffectPreRenderContext,
EffectRenderContext,
PluginSupport,
PostEffectBase,
Type,
Values,
} from '@ragg/delir-core'
import * as clamp from 'lodash/clamp'
interface Params {
threshold: number
keyColor: Values.ColorRGBA
}
export default class ChromakeyPostEffect extends PostEffectBase {
/**
* Provide usable parameters
*/
public static provideParameters() {
return Type.float('threshold', { label: 'Threshold', defaultValue: 1, animatable: true }).colorRgba(
'keyColor',
{ label: 'Key color', defaultValue: new Values.ColorRGBA(0, 0, 0, 1), animatable: true },
)
}
private static VERTEX_SHADER: string = require('./vertex.vert')
private static FRAGMENT_SHADER: string = require('./fragment.frag')
private ctxBindToken: PluginSupport.WebGLContextBindToken
private gl: WebGL2RenderingContext
private texCanvas: HTMLCanvasElement
private texCanvasCtx: CanvasRenderingContext2D
private fragShader: WebGLShader
private vertShader: WebGLShader
private program: WebGLProgram
private vertexBuffer: WebGLBuffer
private tex2DBuffer: WebGLBuffer
private tex: WebGLTexture
private attribs: Partial<{
position: number
coord: number
}> = {}
private uni: Partial<{
texture0: WebGLUniformLocation
keyColor: WebGLUniformLocation
threshold: WebGLUniformLocation
}> = {}
/**
* Called when before rendering start.
*
* If you want initializing before rendering (likes load audio, image, etc...)
* Do it in this method.
*/
public async initialize(req: EffectPreRenderContext<Params>) {
this.ctxBindToken = req.glContextPool.generateContextBindToken()
const gl = await req.glContextPool.getContext('webgl')
const canvas = gl.canvas
this.gl.cl
this.texCanvas = document.createElement('canvas')
this.texCanvasCtx = this.texCanvas.getContext('2d')
const program = (this.program = gl.createProgram())
gl.enable(gl.DEPTH_TEST)
const vertexShader = (this.vertShader = gl.createShader(gl.VERTEX_SHADER))
gl.shaderSource(vertexShader, ChromakeyPostEffect.VERTEX_SHADER)
gl.compileShader(vertexShader)
const fragShader = (this.fragShader = gl.createShader(gl.FRAGMENT_SHADER))
gl.shaderSource(fragShader, ChromakeyPostEffect.FRAGMENT_SHADER)
gl.compileShader(fragShader)
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragShader)
gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) |
this.tex = gl.createTexture()
// get uniform locations
this.uni.texture0 = gl.getUniformLocation(this.program, 'texture0')
this.uni.keyColor = gl.getUniformLocation(this.program, 'keyColor')
this.uni.threshold = gl.getUniformLocation(this.program, 'threshold')
// get attributes locations
this.attribs.position = gl.getAttribLocation(this.program, 'position')
this.attribs.coord = gl.getAttribLocation(this.program, 'coord')
// vertex buffer
this.vertexBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), gl.STATIC_DRAW)
// Tex 2D
this.tex2DBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
req.glContextPool.registerContextForToken(this.ctxBindToken, gl)
req.glContextPool.releaseContext(gl)
}
/**
* Render frame into destination canvas.
* @param req
*/
public async render(req: EffectRenderContext<Params>) {
const {
srcCanvas,
destCanvas,
parameters: { threshold, keyColor },
} = req
const destCtx = destCanvas.getContext('2d')
const gl = await req.glContextPool.getContextByToken(this.ctxBindToken)
const canvas = gl.canvas
// console.log(gl === this.glContext)
// Copy source to texture
const textureCanvas = this.texCanvas
const texCanvasCtx = this.texCanvasCtx
textureCanvas.width = textureCanvas.height = 2 ** Math.ceil(Math.log2(Math.max(req.width, req.height)))
texCanvasCtx.clearRect(0, 0, textureCanvas.width, textureCanvas.height)
texCanvasCtx.drawImage(srcCanvas, 0, 0, textureCanvas.width, textureCanvas.width)
gl.useProgram(this.program)
// Resize viewport
canvas.width = req.width
canvas.height = req.height
gl.viewport(0, 0, req.width, req.height)
gl.clearColor(0, 0, 0, 0)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer)
gl.enableVertexAttribArray(this.attribs.position)
gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
gl.enableVertexAttribArray(this.attribs.coord)
gl.vertexAttribPointer(this.attribs.coord, 2, gl.FLOAT, false, 0, 0)
// Update texture
gl.activeTexture(gl.TEXTURE0)
gl.bindTexture(gl.TEXTURE_2D, this.tex)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureCanvas)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
// gl.generateMipmap(gl.TEXTURE_2D)
// Attach variables
gl.uniform1i(this.uni.texture0, 0)
gl.uniform3f(this.uni.keyColor, keyColor.r / 255, keyColor.g / 255, keyColor.b / 255)
gl.uniform1f(this.uni.threshold, clamp(threshold, 0, 100) / 100)
// Render
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
gl.flush()
destCtx.clearRect(0, 0, req.width, req.height)
destCtx.drawImage(canvas, 0, 0)
req.glContextPool.releaseContext(gl)
}
}
| {
const error = gl.getProgramInfoLog(program)
throw new Error(`[@ragg/delir-posteffect-chromakey] Failed to compile shader. (${error})`)
} | conditional_block |
index.ts | import {
EffectPreRenderContext,
EffectRenderContext,
PluginSupport,
PostEffectBase,
Type,
Values,
} from '@ragg/delir-core'
import * as clamp from 'lodash/clamp'
interface Params {
threshold: number
keyColor: Values.ColorRGBA
}
export default class ChromakeyPostEffect extends PostEffectBase {
/**
* Provide usable parameters
*/
public static provideParameters() |
private static VERTEX_SHADER: string = require('./vertex.vert')
private static FRAGMENT_SHADER: string = require('./fragment.frag')
private ctxBindToken: PluginSupport.WebGLContextBindToken
private gl: WebGL2RenderingContext
private texCanvas: HTMLCanvasElement
private texCanvasCtx: CanvasRenderingContext2D
private fragShader: WebGLShader
private vertShader: WebGLShader
private program: WebGLProgram
private vertexBuffer: WebGLBuffer
private tex2DBuffer: WebGLBuffer
private tex: WebGLTexture
private attribs: Partial<{
position: number
coord: number
}> = {}
private uni: Partial<{
texture0: WebGLUniformLocation
keyColor: WebGLUniformLocation
threshold: WebGLUniformLocation
}> = {}
/**
* Called when before rendering start.
*
* If you want initializing before rendering (likes load audio, image, etc...)
* Do it in this method.
*/
public async initialize(req: EffectPreRenderContext<Params>) {
this.ctxBindToken = req.glContextPool.generateContextBindToken()
const gl = await req.glContextPool.getContext('webgl')
const canvas = gl.canvas
this.gl.cl
this.texCanvas = document.createElement('canvas')
this.texCanvasCtx = this.texCanvas.getContext('2d')
const program = (this.program = gl.createProgram())
gl.enable(gl.DEPTH_TEST)
const vertexShader = (this.vertShader = gl.createShader(gl.VERTEX_SHADER))
gl.shaderSource(vertexShader, ChromakeyPostEffect.VERTEX_SHADER)
gl.compileShader(vertexShader)
const fragShader = (this.fragShader = gl.createShader(gl.FRAGMENT_SHADER))
gl.shaderSource(fragShader, ChromakeyPostEffect.FRAGMENT_SHADER)
gl.compileShader(fragShader)
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragShader)
gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const error = gl.getProgramInfoLog(program)
throw new Error(`[@ragg/delir-posteffect-chromakey] Failed to compile shader. (${error})`)
}
this.tex = gl.createTexture()
// get uniform locations
this.uni.texture0 = gl.getUniformLocation(this.program, 'texture0')
this.uni.keyColor = gl.getUniformLocation(this.program, 'keyColor')
this.uni.threshold = gl.getUniformLocation(this.program, 'threshold')
// get attributes locations
this.attribs.position = gl.getAttribLocation(this.program, 'position')
this.attribs.coord = gl.getAttribLocation(this.program, 'coord')
// vertex buffer
this.vertexBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), gl.STATIC_DRAW)
// Tex 2D
this.tex2DBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
req.glContextPool.registerContextForToken(this.ctxBindToken, gl)
req.glContextPool.releaseContext(gl)
}
/**
* Render frame into destination canvas.
* @param req
*/
public async render(req: EffectRenderContext<Params>) {
const {
srcCanvas,
destCanvas,
parameters: { threshold, keyColor },
} = req
const destCtx = destCanvas.getContext('2d')
const gl = await req.glContextPool.getContextByToken(this.ctxBindToken)
const canvas = gl.canvas
// console.log(gl === this.glContext)
// Copy source to texture
const textureCanvas = this.texCanvas
const texCanvasCtx = this.texCanvasCtx
textureCanvas.width = textureCanvas.height = 2 ** Math.ceil(Math.log2(Math.max(req.width, req.height)))
texCanvasCtx.clearRect(0, 0, textureCanvas.width, textureCanvas.height)
texCanvasCtx.drawImage(srcCanvas, 0, 0, textureCanvas.width, textureCanvas.width)
gl.useProgram(this.program)
// Resize viewport
canvas.width = req.width
canvas.height = req.height
gl.viewport(0, 0, req.width, req.height)
gl.clearColor(0, 0, 0, 0)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer)
gl.enableVertexAttribArray(this.attribs.position)
gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
gl.enableVertexAttribArray(this.attribs.coord)
gl.vertexAttribPointer(this.attribs.coord, 2, gl.FLOAT, false, 0, 0)
// Update texture
gl.activeTexture(gl.TEXTURE0)
gl.bindTexture(gl.TEXTURE_2D, this.tex)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureCanvas)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
// gl.generateMipmap(gl.TEXTURE_2D)
// Attach variables
gl.uniform1i(this.uni.texture0, 0)
gl.uniform3f(this.uni.keyColor, keyColor.r / 255, keyColor.g / 255, keyColor.b / 255)
gl.uniform1f(this.uni.threshold, clamp(threshold, 0, 100) / 100)
// Render
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
gl.flush()
destCtx.clearRect(0, 0, req.width, req.height)
destCtx.drawImage(canvas, 0, 0)
req.glContextPool.releaseContext(gl)
}
}
| {
return Type.float('threshold', { label: 'Threshold', defaultValue: 1, animatable: true }).colorRgba(
'keyColor',
{ label: 'Key color', defaultValue: new Values.ColorRGBA(0, 0, 0, 1), animatable: true },
)
} | identifier_body |
index.ts | import {
EffectPreRenderContext,
EffectRenderContext,
PluginSupport,
PostEffectBase,
Type,
Values,
} from '@ragg/delir-core'
import * as clamp from 'lodash/clamp'
interface Params {
threshold: number
keyColor: Values.ColorRGBA
}
export default class ChromakeyPostEffect extends PostEffectBase {
/**
* Provide usable parameters
*/
public static provideParameters() {
return Type.float('threshold', { label: 'Threshold', defaultValue: 1, animatable: true }).colorRgba(
'keyColor',
{ label: 'Key color', defaultValue: new Values.ColorRGBA(0, 0, 0, 1), animatable: true },
)
}
private static VERTEX_SHADER: string = require('./vertex.vert')
private static FRAGMENT_SHADER: string = require('./fragment.frag')
private ctxBindToken: PluginSupport.WebGLContextBindToken
private gl: WebGL2RenderingContext
private texCanvas: HTMLCanvasElement
private texCanvasCtx: CanvasRenderingContext2D
private fragShader: WebGLShader
private vertShader: WebGLShader
private program: WebGLProgram
private vertexBuffer: WebGLBuffer
private tex2DBuffer: WebGLBuffer
private tex: WebGLTexture
private attribs: Partial<{
position: number
coord: number
}> = {}
private uni: Partial<{
texture0: WebGLUniformLocation
keyColor: WebGLUniformLocation
threshold: WebGLUniformLocation
}> = {}
/**
* Called when before rendering start.
*
* If you want initializing before rendering (likes load audio, image, etc...)
* Do it in this method.
*/
public async initialize(req: EffectPreRenderContext<Params>) {
this.ctxBindToken = req.glContextPool.generateContextBindToken()
const gl = await req.glContextPool.getContext('webgl')
const canvas = gl.canvas
this.gl.cl
this.texCanvas = document.createElement('canvas')
this.texCanvasCtx = this.texCanvas.getContext('2d')
const program = (this.program = gl.createProgram())
gl.enable(gl.DEPTH_TEST)
const vertexShader = (this.vertShader = gl.createShader(gl.VERTEX_SHADER))
gl.shaderSource(vertexShader, ChromakeyPostEffect.VERTEX_SHADER)
gl.compileShader(vertexShader)
const fragShader = (this.fragShader = gl.createShader(gl.FRAGMENT_SHADER))
gl.shaderSource(fragShader, ChromakeyPostEffect.FRAGMENT_SHADER)
gl.compileShader(fragShader)
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragShader)
gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const error = gl.getProgramInfoLog(program)
throw new Error(`[@ragg/delir-posteffect-chromakey] Failed to compile shader. (${error})`)
}
this.tex = gl.createTexture()
// get uniform locations
this.uni.texture0 = gl.getUniformLocation(this.program, 'texture0')
this.uni.keyColor = gl.getUniformLocation(this.program, 'keyColor')
this.uni.threshold = gl.getUniformLocation(this.program, 'threshold')
// get attributes locations
this.attribs.position = gl.getAttribLocation(this.program, 'position')
this.attribs.coord = gl.getAttribLocation(this.program, 'coord')
// vertex buffer
this.vertexBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), gl.STATIC_DRAW)
// Tex 2D
this.tex2DBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
req.glContextPool.registerContextForToken(this.ctxBindToken, gl)
req.glContextPool.releaseContext(gl)
}
/**
* Render frame into destination canvas.
* @param req
*/
public async render(req: EffectRenderContext<Params>) {
const {
srcCanvas,
destCanvas,
parameters: { threshold, keyColor },
} = req
const destCtx = destCanvas.getContext('2d')
const gl = await req.glContextPool.getContextByToken(this.ctxBindToken)
const canvas = gl.canvas
// console.log(gl === this.glContext)
// Copy source to texture
const textureCanvas = this.texCanvas
const texCanvasCtx = this.texCanvasCtx
textureCanvas.width = textureCanvas.height = 2 ** Math.ceil(Math.log2(Math.max(req.width, req.height)))
texCanvasCtx.clearRect(0, 0, textureCanvas.width, textureCanvas.height)
texCanvasCtx.drawImage(srcCanvas, 0, 0, textureCanvas.width, textureCanvas.width)
gl.useProgram(this.program)
// Resize viewport
canvas.width = req.width
canvas.height = req.height
gl.viewport(0, 0, req.width, req.height)
gl.clearColor(0, 0, 0, 0)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer) | gl.enableVertexAttribArray(this.attribs.coord)
gl.vertexAttribPointer(this.attribs.coord, 2, gl.FLOAT, false, 0, 0)
// Update texture
gl.activeTexture(gl.TEXTURE0)
gl.bindTexture(gl.TEXTURE_2D, this.tex)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureCanvas)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
// gl.generateMipmap(gl.TEXTURE_2D)
// Attach variables
gl.uniform1i(this.uni.texture0, 0)
gl.uniform3f(this.uni.keyColor, keyColor.r / 255, keyColor.g / 255, keyColor.b / 255)
gl.uniform1f(this.uni.threshold, clamp(threshold, 0, 100) / 100)
// Render
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
gl.flush()
destCtx.clearRect(0, 0, req.width, req.height)
destCtx.drawImage(canvas, 0, 0)
req.glContextPool.releaseContext(gl)
}
} | gl.enableVertexAttribArray(this.attribs.position)
gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer) | random_line_split |
index.ts | import {
EffectPreRenderContext,
EffectRenderContext,
PluginSupport,
PostEffectBase,
Type,
Values,
} from '@ragg/delir-core'
import * as clamp from 'lodash/clamp'
interface Params {
threshold: number
keyColor: Values.ColorRGBA
}
export default class ChromakeyPostEffect extends PostEffectBase {
/**
* Provide usable parameters
*/
public static provideParameters() {
return Type.float('threshold', { label: 'Threshold', defaultValue: 1, animatable: true }).colorRgba(
'keyColor',
{ label: 'Key color', defaultValue: new Values.ColorRGBA(0, 0, 0, 1), animatable: true },
)
}
private static VERTEX_SHADER: string = require('./vertex.vert')
private static FRAGMENT_SHADER: string = require('./fragment.frag')
private ctxBindToken: PluginSupport.WebGLContextBindToken
private gl: WebGL2RenderingContext
private texCanvas: HTMLCanvasElement
private texCanvasCtx: CanvasRenderingContext2D
private fragShader: WebGLShader
private vertShader: WebGLShader
private program: WebGLProgram
private vertexBuffer: WebGLBuffer
private tex2DBuffer: WebGLBuffer
private tex: WebGLTexture
private attribs: Partial<{
position: number
coord: number
}> = {}
private uni: Partial<{
texture0: WebGLUniformLocation
keyColor: WebGLUniformLocation
threshold: WebGLUniformLocation
}> = {}
/**
* Called when before rendering start.
*
* If you want initializing before rendering (likes load audio, image, etc...)
* Do it in this method.
*/
public async initialize(req: EffectPreRenderContext<Params>) {
this.ctxBindToken = req.glContextPool.generateContextBindToken()
const gl = await req.glContextPool.getContext('webgl')
const canvas = gl.canvas
this.gl.cl
this.texCanvas = document.createElement('canvas')
this.texCanvasCtx = this.texCanvas.getContext('2d')
const program = (this.program = gl.createProgram())
gl.enable(gl.DEPTH_TEST)
const vertexShader = (this.vertShader = gl.createShader(gl.VERTEX_SHADER))
gl.shaderSource(vertexShader, ChromakeyPostEffect.VERTEX_SHADER)
gl.compileShader(vertexShader)
const fragShader = (this.fragShader = gl.createShader(gl.FRAGMENT_SHADER))
gl.shaderSource(fragShader, ChromakeyPostEffect.FRAGMENT_SHADER)
gl.compileShader(fragShader)
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragShader)
gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const error = gl.getProgramInfoLog(program)
throw new Error(`[@ragg/delir-posteffect-chromakey] Failed to compile shader. (${error})`)
}
this.tex = gl.createTexture()
// get uniform locations
this.uni.texture0 = gl.getUniformLocation(this.program, 'texture0')
this.uni.keyColor = gl.getUniformLocation(this.program, 'keyColor')
this.uni.threshold = gl.getUniformLocation(this.program, 'threshold')
// get attributes locations
this.attribs.position = gl.getAttribLocation(this.program, 'position')
this.attribs.coord = gl.getAttribLocation(this.program, 'coord')
// vertex buffer
this.vertexBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), gl.STATIC_DRAW)
// Tex 2D
this.tex2DBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
req.glContextPool.registerContextForToken(this.ctxBindToken, gl)
req.glContextPool.releaseContext(gl)
}
/**
* Render frame into destination canvas.
* @param req
*/
public async | (req: EffectRenderContext<Params>) {
const {
srcCanvas,
destCanvas,
parameters: { threshold, keyColor },
} = req
const destCtx = destCanvas.getContext('2d')
const gl = await req.glContextPool.getContextByToken(this.ctxBindToken)
const canvas = gl.canvas
// console.log(gl === this.glContext)
// Copy source to texture
const textureCanvas = this.texCanvas
const texCanvasCtx = this.texCanvasCtx
textureCanvas.width = textureCanvas.height = 2 ** Math.ceil(Math.log2(Math.max(req.width, req.height)))
texCanvasCtx.clearRect(0, 0, textureCanvas.width, textureCanvas.height)
texCanvasCtx.drawImage(srcCanvas, 0, 0, textureCanvas.width, textureCanvas.width)
gl.useProgram(this.program)
// Resize viewport
canvas.width = req.width
canvas.height = req.height
gl.viewport(0, 0, req.width, req.height)
gl.clearColor(0, 0, 0, 0)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer)
gl.enableVertexAttribArray(this.attribs.position)
gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
gl.enableVertexAttribArray(this.attribs.coord)
gl.vertexAttribPointer(this.attribs.coord, 2, gl.FLOAT, false, 0, 0)
// Update texture
gl.activeTexture(gl.TEXTURE0)
gl.bindTexture(gl.TEXTURE_2D, this.tex)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureCanvas)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
// gl.generateMipmap(gl.TEXTURE_2D)
// Attach variables
gl.uniform1i(this.uni.texture0, 0)
gl.uniform3f(this.uni.keyColor, keyColor.r / 255, keyColor.g / 255, keyColor.b / 255)
gl.uniform1f(this.uni.threshold, clamp(threshold, 0, 100) / 100)
// Render
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
gl.flush()
destCtx.clearRect(0, 0, req.width, req.height)
destCtx.drawImage(canvas, 0, 0)
req.glContextPool.releaseContext(gl)
}
}
| render | identifier_name |
st_wc_merge_017.js | /*
Copyright 2010-2013 SourceGear, LLC
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.
*/
load("../js_test_lib/vscript_test_lib.js");
//////////////////////////////////////////////////////////////////
// Basic MERGE tests that DO NOT require UPDATE nor REVERT.
//////////////////////////////////////////////////////////////////
function | ()
{
var my_group = "st_wc_merge_017"; // this variable must match the above group name.
this.no_setup = true; // do not create an initial REPO and WD.
//////////////////////////////////////////////////////////////////
load("update_helpers.js"); // load the helper functions
initialize_update_helpers(this); // initialize helper functions
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
this.test_it = function()
{
var unique = my_group + "_" + new Date().getTime();
var repoName = unique;
var rootDir = pathCombine(tempDir, unique);
var wdDirs = [];
var csets = {};
var nrWD = 0;
var my_make_wd = function(obj)
{
var new_wd = pathCombine(rootDir, "wd_" + nrWD);
vscript_test_wc__print_section_divider("Creating WD[" + nrWD + "]: " + new_wd);
obj.do_fsobj_mkdir_recursive( new_wd );
obj.do_fsobj_cd( new_wd );
wdDirs.push( new_wd );
nrWD += 1;
return new_wd;
}
//////////////////////////////////////////////////////////////////
// stock content for creating files.
var content_equal = ("This is a test 1.\n"
+"This is a test 2.\n"
+"This is a test 3.\n"
+"This is a test 4.\n"
+"This is a test 5.\n"
+"This is a test 6.\n"
+"This is a test 7.\n"
+"This is a test 8.\n");
var content_B1 = "abcdefghij\n";
var content_C1 = "0123456789\n";
//////////////////////////////////////////////////////////////////
// Create the first WD and initialize the REPO.
my_make_wd(this);
sg.vv2.init_new_repo( { "repo" : repoName,
"hash" : "SHA1/160",
"path" : "."
} );
whoami_testing(repoName);
//////////////////////////////////////////////////////////////////
// Build a sequence of CSETs using current WD.
vscript_test_wc__write_file("file.txt", content_equal);
vscript_test_wc__addremove();
csets.A = vscript_test_wc__commit("A");
//////////////////////////////////////////////////////////////////
// Start a sequence of CSETS in a new WD.
my_make_wd(this);
sg.wc.checkout( { "repo" : repoName,
"attach" : "master",
"rev" : csets.A
} );
// re-write the file contents so that they look edited.
vscript_test_wc__write_file("file.txt", (content_B1 + content_equal));
csets.B = vscript_test_wc__commit("B");
//////////////////////////////////////////////////////////////////
// Start an alternate sequence of CSETS in a new WD.
my_make_wd(this);
sg.wc.checkout( { "repo" : repoName,
"attach" : "master",
"rev" : csets.A
} );
// re-write the file contents so that they look edited.
vscript_test_wc__write_file("file.txt", (content_equal + content_C1));
csets.C = vscript_test_wc__commit("C");
//////////////////////////////////////////////////////////////////
// Do a CLEAN MERGE.
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("Checkout B, Create B1, and clean merge C into it.");
my_make_wd(this);
vscript_test_wc__checkout_np( { "repo" : repoName,
"attach" : "master",
"rev" : csets.B
} );
vscript_test_wc__remove_file("file.txt");
var expect_test = new Array;
expect_test["Removed"] = [ "@b/file.txt" ];
vscript_test_wc__confirm_wii(expect_test);
csets.B1 = vscript_test_wc__commit("B1");
vscript_test_wc__merge_np( { "rev" : csets.C } );
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Added (Merge)"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__confirm_wii(expect_test);
// use MSTATUS
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Existence (A,!B,C,WC)"] = [ pathname ];
expect_test["Modified (C!=A,WC==C)"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
//////////////////////////////////////////////////////////////////
// Try the MERGE again, but do it DIRTY.
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("Checkout B, create dirt and dirty merge C into it.");
my_make_wd(this);
vscript_test_wc__checkout_np( { "repo" : repoName,
"attach" : "master",
"rev" : csets.B
} );
vscript_test_wc__remove_file("file.txt");
var expect_test = new Array;
expect_test["Removed"] = [ "@b/file.txt" ];
vscript_test_wc__confirm_wii(expect_test);
vscript_test_wc__merge_np__expect_error( { "rev" : csets.C }, "This type of merge requires a clean working copy" );
vscript_test_wc__merge_np( { "rev" : csets.C, "allow_dirty" : true } );
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Modified"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__confirm_wii(expect_test);
// use MSTATUS
var pathname = "@/file.txt";
var expect_test = new Array;
//expect_test["Existence (A,!B,C,WC)"] = [ pathname ];
expect_test["Modified (WC!=A,WC!=B,WC==C)"] = [ pathname ]; // not auto-merged, C assumed
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
}
}
| st_wc_merge_017 | identifier_name |
st_wc_merge_017.js | /*
Copyright 2010-2013 SourceGear, LLC
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.
*/
load("../js_test_lib/vscript_test_lib.js");
//////////////////////////////////////////////////////////////////
// Basic MERGE tests that DO NOT require UPDATE nor REVERT.
//////////////////////////////////////////////////////////////////
function st_wc_merge_017()
| {
var my_group = "st_wc_merge_017"; // this variable must match the above group name.
this.no_setup = true; // do not create an initial REPO and WD.
//////////////////////////////////////////////////////////////////
load("update_helpers.js"); // load the helper functions
initialize_update_helpers(this); // initialize helper functions
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
this.test_it = function()
{
var unique = my_group + "_" + new Date().getTime();
var repoName = unique;
var rootDir = pathCombine(tempDir, unique);
var wdDirs = [];
var csets = {};
var nrWD = 0;
var my_make_wd = function(obj)
{
var new_wd = pathCombine(rootDir, "wd_" + nrWD);
vscript_test_wc__print_section_divider("Creating WD[" + nrWD + "]: " + new_wd);
obj.do_fsobj_mkdir_recursive( new_wd );
obj.do_fsobj_cd( new_wd );
wdDirs.push( new_wd );
nrWD += 1;
return new_wd;
}
//////////////////////////////////////////////////////////////////
// stock content for creating files.
var content_equal = ("This is a test 1.\n"
+"This is a test 2.\n"
+"This is a test 3.\n"
+"This is a test 4.\n"
+"This is a test 5.\n"
+"This is a test 6.\n"
+"This is a test 7.\n"
+"This is a test 8.\n");
var content_B1 = "abcdefghij\n";
var content_C1 = "0123456789\n";
//////////////////////////////////////////////////////////////////
// Create the first WD and initialize the REPO.
my_make_wd(this);
sg.vv2.init_new_repo( { "repo" : repoName,
"hash" : "SHA1/160",
"path" : "."
} );
whoami_testing(repoName);
//////////////////////////////////////////////////////////////////
// Build a sequence of CSETs using current WD.
vscript_test_wc__write_file("file.txt", content_equal);
vscript_test_wc__addremove();
csets.A = vscript_test_wc__commit("A");
//////////////////////////////////////////////////////////////////
// Start a sequence of CSETS in a new WD.
my_make_wd(this);
sg.wc.checkout( { "repo" : repoName,
"attach" : "master",
"rev" : csets.A
} );
// re-write the file contents so that they look edited.
vscript_test_wc__write_file("file.txt", (content_B1 + content_equal));
csets.B = vscript_test_wc__commit("B");
//////////////////////////////////////////////////////////////////
// Start an alternate sequence of CSETS in a new WD.
my_make_wd(this);
sg.wc.checkout( { "repo" : repoName,
"attach" : "master",
"rev" : csets.A
} );
// re-write the file contents so that they look edited.
vscript_test_wc__write_file("file.txt", (content_equal + content_C1));
csets.C = vscript_test_wc__commit("C");
//////////////////////////////////////////////////////////////////
// Do a CLEAN MERGE.
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("Checkout B, Create B1, and clean merge C into it.");
my_make_wd(this);
vscript_test_wc__checkout_np( { "repo" : repoName,
"attach" : "master",
"rev" : csets.B
} );
vscript_test_wc__remove_file("file.txt");
var expect_test = new Array;
expect_test["Removed"] = [ "@b/file.txt" ];
vscript_test_wc__confirm_wii(expect_test);
csets.B1 = vscript_test_wc__commit("B1");
vscript_test_wc__merge_np( { "rev" : csets.C } );
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Added (Merge)"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__confirm_wii(expect_test);
// use MSTATUS
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Existence (A,!B,C,WC)"] = [ pathname ];
expect_test["Modified (C!=A,WC==C)"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
//////////////////////////////////////////////////////////////////
// Try the MERGE again, but do it DIRTY.
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("Checkout B, create dirt and dirty merge C into it.");
my_make_wd(this);
vscript_test_wc__checkout_np( { "repo" : repoName,
"attach" : "master",
"rev" : csets.B
} );
vscript_test_wc__remove_file("file.txt");
var expect_test = new Array;
expect_test["Removed"] = [ "@b/file.txt" ];
vscript_test_wc__confirm_wii(expect_test);
vscript_test_wc__merge_np__expect_error( { "rev" : csets.C }, "This type of merge requires a clean working copy" );
vscript_test_wc__merge_np( { "rev" : csets.C, "allow_dirty" : true } );
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Modified"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__confirm_wii(expect_test);
// use MSTATUS
var pathname = "@/file.txt";
var expect_test = new Array;
//expect_test["Existence (A,!B,C,WC)"] = [ pathname ];
expect_test["Modified (WC!=A,WC!=B,WC==C)"] = [ pathname ]; // not auto-merged, C assumed
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
}
} | identifier_body | |
st_wc_merge_017.js | /*
Copyright 2010-2013 SourceGear, LLC
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.
*/
load("../js_test_lib/vscript_test_lib.js");
//////////////////////////////////////////////////////////////////
// Basic MERGE tests that DO NOT require UPDATE nor REVERT.
//////////////////////////////////////////////////////////////////
function st_wc_merge_017()
{
var my_group = "st_wc_merge_017"; // this variable must match the above group name.
this.no_setup = true; // do not create an initial REPO and WD.
//////////////////////////////////////////////////////////////////
load("update_helpers.js"); // load the helper functions
initialize_update_helpers(this); // initialize helper functions
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
this.test_it = function()
{
var unique = my_group + "_" + new Date().getTime();
var repoName = unique;
var rootDir = pathCombine(tempDir, unique);
var wdDirs = [];
var csets = {};
var nrWD = 0;
var my_make_wd = function(obj)
{
var new_wd = pathCombine(rootDir, "wd_" + nrWD);
vscript_test_wc__print_section_divider("Creating WD[" + nrWD + "]: " + new_wd);
obj.do_fsobj_mkdir_recursive( new_wd );
obj.do_fsobj_cd( new_wd );
wdDirs.push( new_wd );
nrWD += 1;
return new_wd;
}
//////////////////////////////////////////////////////////////////
// stock content for creating files.
var content_equal = ("This is a test 1.\n"
+"This is a test 2.\n"
+"This is a test 3.\n"
+"This is a test 4.\n"
+"This is a test 5.\n"
+"This is a test 6.\n"
+"This is a test 7.\n"
+"This is a test 8.\n");
var content_B1 = "abcdefghij\n";
var content_C1 = "0123456789\n";
//////////////////////////////////////////////////////////////////
// Create the first WD and initialize the REPO.
my_make_wd(this);
sg.vv2.init_new_repo( { "repo" : repoName,
"hash" : "SHA1/160",
"path" : "."
} );
whoami_testing(repoName);
//////////////////////////////////////////////////////////////////
// Build a sequence of CSETs using current WD.
vscript_test_wc__write_file("file.txt", content_equal);
vscript_test_wc__addremove();
csets.A = vscript_test_wc__commit("A");
//////////////////////////////////////////////////////////////////
// Start a sequence of CSETS in a new WD.
my_make_wd(this);
sg.wc.checkout( { "repo" : repoName,
"attach" : "master",
"rev" : csets.A
} );
// re-write the file contents so that they look edited.
vscript_test_wc__write_file("file.txt", (content_B1 + content_equal));
csets.B = vscript_test_wc__commit("B");
//////////////////////////////////////////////////////////////////
// Start an alternate sequence of CSETS in a new WD.
my_make_wd(this);
sg.wc.checkout( { "repo" : repoName,
"attach" : "master",
"rev" : csets.A
} );
// re-write the file contents so that they look edited.
vscript_test_wc__write_file("file.txt", (content_equal + content_C1));
csets.C = vscript_test_wc__commit("C");
| //////////////////////////////////////////////////////////////////
// Do a CLEAN MERGE.
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("Checkout B, Create B1, and clean merge C into it.");
my_make_wd(this);
vscript_test_wc__checkout_np( { "repo" : repoName,
"attach" : "master",
"rev" : csets.B
} );
vscript_test_wc__remove_file("file.txt");
var expect_test = new Array;
expect_test["Removed"] = [ "@b/file.txt" ];
vscript_test_wc__confirm_wii(expect_test);
csets.B1 = vscript_test_wc__commit("B1");
vscript_test_wc__merge_np( { "rev" : csets.C } );
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Added (Merge)"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__confirm_wii(expect_test);
// use MSTATUS
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Existence (A,!B,C,WC)"] = [ pathname ];
expect_test["Modified (C!=A,WC==C)"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
//////////////////////////////////////////////////////////////////
// Try the MERGE again, but do it DIRTY.
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("Checkout B, create dirt and dirty merge C into it.");
my_make_wd(this);
vscript_test_wc__checkout_np( { "repo" : repoName,
"attach" : "master",
"rev" : csets.B
} );
vscript_test_wc__remove_file("file.txt");
var expect_test = new Array;
expect_test["Removed"] = [ "@b/file.txt" ];
vscript_test_wc__confirm_wii(expect_test);
vscript_test_wc__merge_np__expect_error( { "rev" : csets.C }, "This type of merge requires a clean working copy" );
vscript_test_wc__merge_np( { "rev" : csets.C, "allow_dirty" : true } );
var pathname = "@/file.txt";
var expect_test = new Array;
expect_test["Modified"] = [ pathname ];
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__confirm_wii(expect_test);
// use MSTATUS
var pathname = "@/file.txt";
var expect_test = new Array;
//expect_test["Existence (A,!B,C,WC)"] = [ pathname ];
expect_test["Modified (WC!=A,WC!=B,WC==C)"] = [ pathname ]; // not auto-merged, C assumed
expect_test["Unresolved"] = [ pathname ];
expect_test["Choice Unresolved (Existence)"] = [ pathname ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
}
} | random_line_split | |
constants.py | KEY_UP = "up"
KEY_DOWN = "down"
KEY_RIGHT = "right"
KEY_LEFT = "left"
KEY_INSERT = "insert"
KEY_HOME = "home"
KEY_END = "end"
KEY_PAGEUP = "pageup"
KEY_PAGEDOWN = "pagedown"
KEY_BACKSPACE = "backspace"
KEY_DELETE = "delete"
KEY_TAB = "tab"
KEY_ENTER = "enter"
KEY_PAUSE = "pause"
KEY_ESCAPE = "escape" | KEY_KEYPAD4 = "keypad4"
KEY_KEYPAD5 = "keypad5"
KEY_KEYPAD6 = "keypad6"
KEY_KEYPAD7 = "keypad7"
KEY_KEYPAD8 = "keypad8"
KEY_KEYPAD9 = "keypad9"
KEY_KEYPAD_PERIOD = "keypad_period"
KEY_KEYPAD_DIVIDE = "keypad_divide"
KEY_KEYPAD_MULTIPLY = "keypad_multiply"
KEY_KEYPAD_MINUS = "keypad_minus"
KEY_KEYPAD_PLUS = "keypad_plus"
KEY_KEYPAD_ENTER = "keypad_enter"
KEY_CLEAR = "clear"
KEY_F1 = "f1"
KEY_F2 = "f2"
KEY_F3 = "f3"
KEY_F4 = "f4"
KEY_F5 = "f5"
KEY_F6 = "f6"
KEY_F7 = "f7"
KEY_F8 = "f8"
KEY_F9 = "f9"
KEY_F10 = "f10"
KEY_F11 = "f11"
KEY_F12 = "f12"
KEY_F13 = "f13"
KEY_F14 = "f14"
KEY_F15 = "f15"
KEY_F16 = "f16"
KEY_F17 = "f17"
KEY_F18 = "f18"
KEY_F19 = "f19"
KEY_F20 = "f20"
KEY_SYSREQ = "sysreq"
KEY_BREAK = "break"
KEY_CONTEXT_MENU = "context_menu"
KEY_BROWSER_BACK = "browser_back"
KEY_BROWSER_FORWARD = "browser_forward"
KEY_BROWSER_REFRESH = "browser_refresh"
KEY_BROWSER_STOP = "browser_stop"
KEY_BROWSER_SEARCH = "browser_search"
KEY_BROWSER_FAVORITES = "browser_favorites"
KEY_BROWSER_HOME = "browser_home" | KEY_SPACE = "space"
KEY_KEYPAD0 = "keypad0"
KEY_KEYPAD1 = "keypad1"
KEY_KEYPAD2 = "keypad2"
KEY_KEYPAD3 = "keypad3" | random_line_split |
arg-modules-demo.js | /*let calculator = (function () {
let result = 0;
function add(x) {
result += x;
return this;
}
function subtract(x) {
result -= x;
return this;
}
function getResult() {
return result;
}
return{
add, subtract, getResult
}
})();*/
// our lasted obj starts as empty
let calculator = {};
// private iffe with every private functionality
(function (module) {
let result = 0;
function add(x) {
result += x;
return this;
}
function | (x) {
result -= x;
return this;
}
function getResult() {
return result;
}
module.add = add;
module.subtract = subtract;
module.getResult = getResult;
}(calculator));
// calling it with our obj
(function (module) {
module.add42 = function () {
this.add(42);
};
}(calculator));
calculator.add42();
console.log(calculator.add(5).getResult());
| subtract | identifier_name |
arg-modules-demo.js | /*let calculator = (function () {
let result = 0;
function add(x) {
result += x;
return this;
}
function subtract(x) {
result -= x;
return this;
}
function getResult() {
return result;
}
return{
add, subtract, getResult
}
})();*/
// our lasted obj starts as empty
let calculator = {};
// private iffe with every private functionality
(function (module) {
let result = 0;
function add(x) {
result += x;
return this;
}
function subtract(x) {
result -= x;
return this;
}
function getResult() {
return result;
}
module.add = add;
module.subtract = subtract;
module.getResult = getResult;
}(calculator)); | // calling it with our obj
(function (module) {
module.add42 = function () {
this.add(42);
};
}(calculator));
calculator.add42();
console.log(calculator.add(5).getResult()); | random_line_split | |
arg-modules-demo.js | /*let calculator = (function () {
let result = 0;
function add(x) {
result += x;
return this;
}
function subtract(x) {
result -= x;
return this;
}
function getResult() {
return result;
}
return{
add, subtract, getResult
}
})();*/
// our lasted obj starts as empty
let calculator = {};
// private iffe with every private functionality
(function (module) {
let result = 0;
function add(x) |
function subtract(x) {
result -= x;
return this;
}
function getResult() {
return result;
}
module.add = add;
module.subtract = subtract;
module.getResult = getResult;
}(calculator));
// calling it with our obj
(function (module) {
module.add42 = function () {
this.add(42);
};
}(calculator));
calculator.add42();
console.log(calculator.add(5).getResult());
| {
result += x;
return this;
} | identifier_body |
utils.py |
class TranslationDictionary(object):
"""
TranslationDictionary
"""
def __init__(self, dictionaries=None, default=None):
self.dictionaries = dictionaries or {
'pt': ('portuguese', _('Portuguese')),
'en': ('english', _('English')),
'es': ('spanish', _('Spanish')),
'de': ('german', _('German')),
'da': ('danish', _('Danish')),
'nl': ('dutch', _('Dutch')),
'fi': ('finnish', _('Finnish')),
'fr': ('french', _('French')),
'hu': ('hungarian', _('Hungarian')),
'it': ('italian', _('Italian')),
'nn': ('norwegian', _('Norwegian')),
'ro': ('romanian', _('Romanian')),
'ru': ('russian', _('Russian')),
'sv': ('swedish', _('Swedish')),
'tr': ('turkish', _('Turkish')),
}
self.default = default or ('simple', _('Simple'))
def get_dictionary_tuple(self, language):
return self.dictionaries.get(language.split('-')[0], self.default)
def get_dictionary_pg(self, language):
return self.get_dictionary_tuple(language)[0]
def | (self, languages=None):
if languages:
return tuple(self.get_dictionary(l) for l in self.dictionaries)
return self.dictionaries.values()
| get_dictionaries | identifier_name |
utils.py | class TranslationDictionary(object):
"""
TranslationDictionary
"""
def __init__(self, dictionaries=None, default=None):
self.dictionaries = dictionaries or {
'pt': ('portuguese', _('Portuguese')),
'en': ('english', _('English')),
'es': ('spanish', _('Spanish')),
'de': ('german', _('German')), | 'da': ('danish', _('Danish')),
'nl': ('dutch', _('Dutch')),
'fi': ('finnish', _('Finnish')),
'fr': ('french', _('French')),
'hu': ('hungarian', _('Hungarian')),
'it': ('italian', _('Italian')),
'nn': ('norwegian', _('Norwegian')),
'ro': ('romanian', _('Romanian')),
'ru': ('russian', _('Russian')),
'sv': ('swedish', _('Swedish')),
'tr': ('turkish', _('Turkish')),
}
self.default = default or ('simple', _('Simple'))
def get_dictionary_tuple(self, language):
return self.dictionaries.get(language.split('-')[0], self.default)
def get_dictionary_pg(self, language):
return self.get_dictionary_tuple(language)[0]
def get_dictionaries(self, languages=None):
if languages:
return tuple(self.get_dictionary(l) for l in self.dictionaries)
return self.dictionaries.values() | random_line_split | |
utils.py |
class TranslationDictionary(object):
"""
TranslationDictionary
"""
def __init__(self, dictionaries=None, default=None):
self.dictionaries = dictionaries or {
'pt': ('portuguese', _('Portuguese')),
'en': ('english', _('English')),
'es': ('spanish', _('Spanish')),
'de': ('german', _('German')),
'da': ('danish', _('Danish')),
'nl': ('dutch', _('Dutch')),
'fi': ('finnish', _('Finnish')),
'fr': ('french', _('French')),
'hu': ('hungarian', _('Hungarian')),
'it': ('italian', _('Italian')),
'nn': ('norwegian', _('Norwegian')),
'ro': ('romanian', _('Romanian')),
'ru': ('russian', _('Russian')),
'sv': ('swedish', _('Swedish')),
'tr': ('turkish', _('Turkish')),
}
self.default = default or ('simple', _('Simple'))
def get_dictionary_tuple(self, language):
return self.dictionaries.get(language.split('-')[0], self.default)
def get_dictionary_pg(self, language):
return self.get_dictionary_tuple(language)[0]
def get_dictionaries(self, languages=None):
if languages:
|
return self.dictionaries.values()
| return tuple(self.get_dictionary(l) for l in self.dictionaries) | conditional_block |
utils.py |
class TranslationDictionary(object):
"""
TranslationDictionary
"""
def __init__(self, dictionaries=None, default=None):
self.dictionaries = dictionaries or {
'pt': ('portuguese', _('Portuguese')),
'en': ('english', _('English')),
'es': ('spanish', _('Spanish')),
'de': ('german', _('German')),
'da': ('danish', _('Danish')),
'nl': ('dutch', _('Dutch')),
'fi': ('finnish', _('Finnish')),
'fr': ('french', _('French')),
'hu': ('hungarian', _('Hungarian')),
'it': ('italian', _('Italian')),
'nn': ('norwegian', _('Norwegian')),
'ro': ('romanian', _('Romanian')),
'ru': ('russian', _('Russian')),
'sv': ('swedish', _('Swedish')),
'tr': ('turkish', _('Turkish')),
}
self.default = default or ('simple', _('Simple'))
def get_dictionary_tuple(self, language):
return self.dictionaries.get(language.split('-')[0], self.default)
def get_dictionary_pg(self, language):
|
def get_dictionaries(self, languages=None):
if languages:
return tuple(self.get_dictionary(l) for l in self.dictionaries)
return self.dictionaries.values()
| return self.get_dictionary_tuple(language)[0] | identifier_body |
default_impl.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::collections::HashSet;
use std::future::Future;
use std::sync::Arc;
use futures::future::BoxFuture;
use futures::FutureExt;
use futures::StreamExt;
use futures::TryStreamExt;
use crate::namedag::MemNameDag;
use crate::nameset::hints::Hints;
use crate::ops::DagAddHeads;
use crate::ops::IdConvert;
use crate::ops::IdDagAlgorithm;
use crate::ops::Parents;
use crate::DagAlgorithm;
use crate::Id;
use crate::IdSet;
use crate::NameSet;
use crate::Result;
use crate::VertexName;
/// Re-create the graph so it looks better when rendered.
///
/// For example, the left-side graph will be rewritten to the right-side:
///
/// 1. Linearize.
///
/// ```plain,ignore
/// A A # Linearize is done by IdMap::assign_heads,
/// | | # as long as the heads provided are the heads
/// | C B # of the whole graph ("A", "C", not "B", "D").
/// | | |
/// B | -> | C
/// | | | |
/// | D | D
/// |/ |/
/// E E
/// ```
///
/// 2. Reorder branches (at different branching points) to reduce columns.
///
/// ```plain,ignore
/// D B
/// | | # Assuming the main branch is B-C-E.
/// B | | A # Branching point of the D branch is "C"
/// | | |/ # Branching point of the A branch is "C"
/// | | A -> C # The D branch should be moved to below
/// | |/ | # the A branch.
/// | | | D
/// |/| |/
/// C / E
/// |/
/// E
/// ```
///
/// 3. Reorder branches (at a same branching point) to reduce length of
/// edges.
///
/// ```plain,ignore
/// D A
/// | | # This is done by picking the longest
/// | A B # branch (A-B-C-E) as the "main branch"
/// | | | # and work on the remaining branches
/// | B -> C # recursively.
/// | | |
/// | C | D
/// |/ |/
/// E E
/// ```
///
/// `main_branch` optionally defines how to sort the heads. A head `x` will
/// be emitted first during iteration, if `ancestors(x) & main_branch`
/// contains larger vertexes. For example, if `main_branch` is `[C, D, E]`,
/// then `C` will be emitted first, and the returned DAG will have `all()`
/// output `[C, D, A, B, E]`. Practically, `main_branch` usually contains
/// "public" commits.
///
/// This function is expensive. Only run on small graphs.
///
/// This function is currently more optimized for "forking" cases. It is
/// not yet optimized for graphs with many merges.
pub(crate) async fn beautify(
this: &(impl DagAlgorithm + ?Sized),
main_branch: Option<NameSet>,
) -> Result<MemNameDag> {
// Find the "largest" branch.
async fn find_main_branch<F, O>(get_ancestors: &F, heads: &[VertexName]) -> Result<NameSet>
where
F: Fn(&VertexName) -> O,
F: Send,
O: Future<Output = Result<NameSet>>,
O: Send,
{
let mut best_branch = NameSet::empty();
let mut best_count = best_branch.count().await?;
for head in heads {
let branch = get_ancestors(head).await?;
let count = branch.count().await?;
if count > best_count {
best_count = count;
best_branch = branch;
}
}
Ok(best_branch)
}
// Sort heads recursively.
// Cannot use "async fn" due to rustc limitation on async recursion.
fn sort<'a: 't, 'b: 't, 't, F, O>(
get_ancestors: &'a F,
heads: &'b mut [VertexName],
main_branch: NameSet,
) -> BoxFuture<'t, Result<()>>
where
F: Fn(&VertexName) -> O,
F: Send + Sync,
O: Future<Output = Result<NameSet>>,
O: Send,
{
let fut = async move {
if heads.len() <= 1 {
return Ok(());
}
// Sort heads by "branching point" on the main branch.
let mut branching_points: HashMap<VertexName, usize> =
HashMap::with_capacity(heads.len());
for head in heads.iter() {
let count = (get_ancestors(head).await? & main_branch.clone())
.count()
.await?;
branching_points.insert(head.clone(), count);
}
heads.sort_by_key(|v| branching_points.get(v));
// For heads with a same branching point, sort them recursively
// using a different "main branch".
let mut start = 0;
let mut start_branching_point: Option<usize> = None;
for end in 0..=heads.len() {
let branching_point = heads
.get(end)
.and_then(|h| branching_points.get(&h).cloned());
if branching_point != start_branching_point {
if start + 1 < end {
let heads = &mut heads[start..end];
let main_branch = find_main_branch(get_ancestors, heads).await?;
// "boxed" is used to workaround async recursion.
sort(get_ancestors, heads, main_branch).boxed().await?;
}
start = end;
start_branching_point = branching_point;
}
}
Ok(())
};
Box::pin(fut)
}
let main_branch = main_branch.unwrap_or_else(NameSet::empty);
let heads = this
.heads_ancestors(this.all().await?)
.await?
.iter()
.await?;
let mut heads: Vec<_> = heads.try_collect().await?;
let get_ancestors = |head: &VertexName| this.ancestors(head.into());
// Stabilize output if the sort key conflicts.
heads.sort();
sort(&get_ancestors, &mut heads[..], main_branch).await?;
let mut dag = MemNameDag::new();
dag.add_heads(&this.dag_snapshot()?, &heads.into()).await?;
Ok(dag)
}
/// Convert `Set` to a `Parents` implementation that only returns vertexes in the set.
pub(crate) async fn set_to_parents(set: &NameSet) -> Result<Option<impl Parents>> {
let (id_set, id_map) = match set.to_id_set_and_id_map_in_o1() {
Some(v) => v,
None => return Ok(None),
};
let dag = match set.dag() {
None => return Ok(None),
Some(dag) => dag,
};
let id_dag = dag.id_dag_snapshot()?;
// Pre-resolve ids to vertexes. Reduce remote lookup round-trips.
let ids: Vec<Id> = id_set.iter_desc().collect();
id_map.vertex_name_batch(&ids).await?;
struct IdParents {
id_set: IdSet,
id_dag: Arc<dyn IdDagAlgorithm + Send + Sync>,
id_map: Arc<dyn IdConvert + Send + Sync>,
}
#[async_trait::async_trait]
impl Parents for IdParents {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
tracing::debug!(
target: "dag::idparents",
"resolving parents for {:?}", &name,
);
let id = self.id_map.vertex_id(name).await?;
let direct_parent_ids = self.id_dag.parent_ids(id)?;
let parent_ids = if direct_parent_ids.iter().all(|&id| self.id_set.contains(id)) {
// Fast path. No "leaked" parents.
direct_parent_ids
} else {
// Slower path.
// PERF: There might be room to optimize (ex. dedicated API like
// reachable_roots).
let parent_id_set = IdSet::from_spans(direct_parent_ids);
let ancestors = self.id_dag.ancestors(parent_id_set)?;
let heads = ancestors.intersection(&self.id_set);
let heads = self.id_dag.heads_ancestors(heads)?;
heads.iter_desc().collect()
};
let vertexes = self.id_map.vertex_name_batch(&parent_ids).await?;
let parents = vertexes.into_iter().collect::<Result<Vec<_>>>()?;
Ok(parents)
}
async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> {
// The `IdParents` is not intended to be inserted to other graphs.
tracing::warn!(
target: "dag::idparents",
"IdParents does not implement hint_subdag_for_insertion() for efficient insertion"
);
Ok(MemNameDag::new())
}
}
let parents = IdParents {
id_set,
id_dag,
id_map,
};
Ok(Some(parents))
}
pub(crate) async fn parents(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
let mut result: Vec<VertexName> = Vec::new();
let mut iter = set.iter().await?;
// PERF: This is not an efficient async implementation.
while let Some(vertex) = iter.next().await {
let parents = this.parent_names(vertex?).await?;
result.extend(parents);
}
Ok(NameSet::from_static_names(result))
}
pub(crate) async fn first_ancestor_nth(
this: &(impl DagAlgorithm + ?Sized),
name: VertexName,
n: u64,
) -> Result<Option<VertexName>> {
let mut vertex = name.clone();
for _ in 0..n {
let parents = this.parent_names(vertex).await?;
if parents.is_empty() {
return Ok(None);
}
vertex = parents[0].clone();
}
Ok(Some(vertex))
}
pub(crate) async fn | (
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
let mut to_visit: Vec<VertexName> = {
let mut list = Vec::with_capacity(set.count().await?);
let mut iter = set.iter().await?;
while let Some(next) = iter.next().await {
let vertex = next?;
list.push(vertex);
}
list
};
let mut visited: HashSet<VertexName> = to_visit.clone().into_iter().collect();
while let Some(v) = to_visit.pop() {
#[allow(clippy::never_loop)]
if let Some(parent) = this.parent_names(v).await?.into_iter().next() {
if visited.insert(parent.clone()) {
to_visit.push(parent);
}
}
}
let hints = Hints::new_inherit_idmap_dag(set.hints());
let set = NameSet::from_iter(visited.into_iter().map(Ok), hints);
this.sort(&set).await
}
pub(crate) async fn heads(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
Ok(set.clone() - this.parents(set).await?)
}
pub(crate) async fn roots(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
Ok(set.clone() - this.children(set).await?)
}
pub(crate) async fn merges(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
let this = this.dag_snapshot()?;
Ok(set.filter(Box::new(move |v: &VertexName| {
let this = this.clone();
Box::pin(async move {
DagAlgorithm::parent_names(&this, v.clone())
.await
.map(|ps| ps.len() >= 2)
})
})))
}
pub(crate) async fn reachable_roots(
this: &(impl DagAlgorithm + ?Sized),
roots: NameSet,
heads: NameSet,
) -> Result<NameSet> {
let heads_ancestors = this.ancestors(heads.clone()).await?;
let roots = roots & heads_ancestors.clone(); // Filter out "bogus" roots.
let only = heads_ancestors - this.ancestors(roots.clone()).await?;
Ok(roots.clone() & (heads.clone() | this.parents(only).await?))
}
pub(crate) async fn heads_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
this.heads(this.ancestors(set).await?).await
}
pub(crate) async fn only(
this: &(impl DagAlgorithm + ?Sized),
reachable: NameSet,
unreachable: NameSet,
) -> Result<NameSet> {
let reachable = this.ancestors(reachable).await?;
let unreachable = this.ancestors(unreachable).await?;
Ok(reachable - unreachable)
}
pub(crate) async fn only_both(
this: &(impl DagAlgorithm + ?Sized),
reachable: NameSet,
unreachable: NameSet,
) -> Result<(NameSet, NameSet)> {
let reachable = this.ancestors(reachable).await?;
let unreachable = this.ancestors(unreachable).await?;
Ok((reachable - unreachable.clone(), unreachable))
}
pub(crate) async fn gca_one(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<Option<VertexName>> {
this.gca_all(set)
.await?
.iter()
.await?
.next()
.await
.transpose()
}
pub(crate) async fn gca_all(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
this.heads_ancestors(this.common_ancestors(set).await?)
.await
}
pub(crate) async fn common_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
let result = match set.count().await? {
0 => set,
1 => this.ancestors(set).await?,
_ => {
// Try to reduce the size of `set`.
// `common_ancestors(X)` = `common_ancestors(roots(X))`.
let set = this.roots(set).await?;
let mut iter = set.iter().await?;
let mut result = this
.ancestors(NameSet::from(iter.next().await.unwrap()?))
.await?;
while let Some(v) = iter.next().await {
result = result.intersection(&this.ancestors(NameSet::from(v?)).await?);
}
result
}
};
Ok(result)
}
pub(crate) async fn is_ancestor(
this: &(impl DagAlgorithm + ?Sized),
ancestor: VertexName,
descendant: VertexName,
) -> Result<bool> {
let mut to_visit = vec![descendant];
let mut visited: HashSet<_> = to_visit.clone().into_iter().collect();
while let Some(v) = to_visit.pop() {
if v == ancestor {
return Ok(true);
}
for parent in this.parent_names(v).await? {
if visited.insert(parent.clone()) {
to_visit.push(parent);
}
}
}
Ok(false)
}
#[tracing::instrument(skip(this), level=tracing::Level::DEBUG)]
pub(crate) async fn hint_subdag_for_insertion(
this: &(impl Parents + ?Sized),
scope: &NameSet,
heads: &[VertexName],
) -> Result<MemNameDag> {
let count = scope.count().await?;
tracing::trace!("hint_subdag_for_insertion: pending vertexes: {}", count);
// ScopedParents only contains parents within "scope".
struct ScopedParents<'a, P: Parents + ?Sized> {
parents: &'a P,
scope: &'a NameSet,
}
#[async_trait::async_trait]
impl<'a, P: Parents + ?Sized> Parents for ScopedParents<'a, P> {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
let parents: Vec<VertexName> = self.parents.parent_names(name).await?;
// Filter by scope. We don't need to provide a "correct" parents here.
// It is only used to optimize network fetches, not used to actually insert
// to the graph.
let mut filtered_parents = Vec::with_capacity(parents.len());
for v in parents {
if self.scope.contains(&v).await? {
filtered_parents.push(v)
}
}
Ok(filtered_parents)
}
async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> {
// No need to use such a hint (to avoid infinite recursion).
// Pending names should exist in the graph without using remote fetching.
Ok(MemNameDag::new())
}
}
// Insert vertexes in `scope` to `dag`.
let mut dag = MemNameDag::new();
// The MemNameDag should not be lazy.
assert!(!dag.is_vertex_lazy());
let scoped_parents = ScopedParents {
parents: this,
scope,
};
dag.add_heads(&scoped_parents, &heads.into()).await?;
Ok(dag)
}
| first_ancestors | identifier_name |
default_impl.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::collections::HashSet;
use std::future::Future;
use std::sync::Arc;
use futures::future::BoxFuture;
use futures::FutureExt;
use futures::StreamExt;
use futures::TryStreamExt;
use crate::namedag::MemNameDag;
use crate::nameset::hints::Hints;
use crate::ops::DagAddHeads;
use crate::ops::IdConvert;
use crate::ops::IdDagAlgorithm;
use crate::ops::Parents;
use crate::DagAlgorithm;
use crate::Id;
use crate::IdSet;
use crate::NameSet;
use crate::Result;
use crate::VertexName;
/// Re-create the graph so it looks better when rendered.
///
/// For example, the left-side graph will be rewritten to the right-side:
///
/// 1. Linearize.
///
/// ```plain,ignore
/// A A # Linearize is done by IdMap::assign_heads,
/// | | # as long as the heads provided are the heads
/// | C B # of the whole graph ("A", "C", not "B", "D").
/// | | |
/// B | -> | C
/// | | | |
/// | D | D
/// |/ |/
/// E E
/// ```
///
/// 2. Reorder branches (at different branching points) to reduce columns.
///
/// ```plain,ignore
/// D B
/// | | # Assuming the main branch is B-C-E.
/// B | | A # Branching point of the D branch is "C"
/// | | |/ # Branching point of the A branch is "C"
/// | | A -> C # The D branch should be moved to below
/// | |/ | # the A branch.
/// | | | D
/// |/| |/
/// C / E
/// |/
/// E
/// ```
///
/// 3. Reorder branches (at a same branching point) to reduce length of
/// edges.
///
/// ```plain,ignore
/// D A
/// | | # This is done by picking the longest
/// | A B # branch (A-B-C-E) as the "main branch"
/// | | | # and work on the remaining branches
/// | B -> C # recursively.
/// | | |
/// | C | D
/// |/ |/
/// E E
/// ```
///
/// `main_branch` optionally defines how to sort the heads. A head `x` will
/// be emitted first during iteration, if `ancestors(x) & main_branch`
/// contains larger vertexes. For example, if `main_branch` is `[C, D, E]`,
/// then `C` will be emitted first, and the returned DAG will have `all()`
/// output `[C, D, A, B, E]`. Practically, `main_branch` usually contains
/// "public" commits.
///
/// This function is expensive. Only run on small graphs.
///
/// This function is currently more optimized for "forking" cases. It is
/// not yet optimized for graphs with many merges.
pub(crate) async fn beautify(
this: &(impl DagAlgorithm + ?Sized),
main_branch: Option<NameSet>,
) -> Result<MemNameDag> {
// Find the "largest" branch.
async fn find_main_branch<F, O>(get_ancestors: &F, heads: &[VertexName]) -> Result<NameSet>
where
F: Fn(&VertexName) -> O,
F: Send,
O: Future<Output = Result<NameSet>>,
O: Send,
{
let mut best_branch = NameSet::empty();
let mut best_count = best_branch.count().await?;
for head in heads {
let branch = get_ancestors(head).await?;
let count = branch.count().await?;
if count > best_count {
best_count = count;
best_branch = branch;
}
}
Ok(best_branch)
}
// Sort heads recursively.
// Cannot use "async fn" due to rustc limitation on async recursion.
fn sort<'a: 't, 'b: 't, 't, F, O>(
get_ancestors: &'a F,
heads: &'b mut [VertexName],
main_branch: NameSet,
) -> BoxFuture<'t, Result<()>>
where
F: Fn(&VertexName) -> O,
F: Send + Sync,
O: Future<Output = Result<NameSet>>,
O: Send,
{
let fut = async move {
if heads.len() <= 1 {
return Ok(());
}
// Sort heads by "branching point" on the main branch.
let mut branching_points: HashMap<VertexName, usize> =
HashMap::with_capacity(heads.len());
for head in heads.iter() {
let count = (get_ancestors(head).await? & main_branch.clone())
.count()
.await?;
branching_points.insert(head.clone(), count);
}
heads.sort_by_key(|v| branching_points.get(v));
// For heads with a same branching point, sort them recursively
// using a different "main branch".
let mut start = 0;
let mut start_branching_point: Option<usize> = None;
for end in 0..=heads.len() {
let branching_point = heads
.get(end)
.and_then(|h| branching_points.get(&h).cloned());
if branching_point != start_branching_point {
if start + 1 < end {
let heads = &mut heads[start..end];
let main_branch = find_main_branch(get_ancestors, heads).await?;
// "boxed" is used to workaround async recursion.
sort(get_ancestors, heads, main_branch).boxed().await?;
}
start = end;
start_branching_point = branching_point;
}
}
Ok(())
};
Box::pin(fut)
}
let main_branch = main_branch.unwrap_or_else(NameSet::empty);
let heads = this
.heads_ancestors(this.all().await?)
.await?
.iter()
.await?;
let mut heads: Vec<_> = heads.try_collect().await?;
let get_ancestors = |head: &VertexName| this.ancestors(head.into());
// Stabilize output if the sort key conflicts.
heads.sort();
sort(&get_ancestors, &mut heads[..], main_branch).await?;
let mut dag = MemNameDag::new();
dag.add_heads(&this.dag_snapshot()?, &heads.into()).await?;
Ok(dag)
}
/// Convert `Set` to a `Parents` implementation that only returns vertexes in the set.
pub(crate) async fn set_to_parents(set: &NameSet) -> Result<Option<impl Parents>> {
let (id_set, id_map) = match set.to_id_set_and_id_map_in_o1() {
Some(v) => v,
None => return Ok(None),
};
let dag = match set.dag() {
None => return Ok(None),
Some(dag) => dag,
};
let id_dag = dag.id_dag_snapshot()?;
// Pre-resolve ids to vertexes. Reduce remote lookup round-trips.
let ids: Vec<Id> = id_set.iter_desc().collect();
id_map.vertex_name_batch(&ids).await?;
struct IdParents {
id_set: IdSet,
id_dag: Arc<dyn IdDagAlgorithm + Send + Sync>,
id_map: Arc<dyn IdConvert + Send + Sync>,
}
#[async_trait::async_trait]
impl Parents for IdParents {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
tracing::debug!(
target: "dag::idparents",
"resolving parents for {:?}", &name,
);
let id = self.id_map.vertex_id(name).await?;
let direct_parent_ids = self.id_dag.parent_ids(id)?;
let parent_ids = if direct_parent_ids.iter().all(|&id| self.id_set.contains(id)) {
// Fast path. No "leaked" parents.
direct_parent_ids
} else {
// Slower path.
// PERF: There might be room to optimize (ex. dedicated API like
// reachable_roots).
let parent_id_set = IdSet::from_spans(direct_parent_ids);
let ancestors = self.id_dag.ancestors(parent_id_set)?;
let heads = ancestors.intersection(&self.id_set);
let heads = self.id_dag.heads_ancestors(heads)?;
heads.iter_desc().collect()
};
let vertexes = self.id_map.vertex_name_batch(&parent_ids).await?;
let parents = vertexes.into_iter().collect::<Result<Vec<_>>>()?;
Ok(parents)
}
async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> {
// The `IdParents` is not intended to be inserted to other graphs.
tracing::warn!(
target: "dag::idparents",
"IdParents does not implement hint_subdag_for_insertion() for efficient insertion"
);
Ok(MemNameDag::new())
}
}
let parents = IdParents {
id_set,
id_dag,
id_map,
};
Ok(Some(parents))
}
pub(crate) async fn parents(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
let mut result: Vec<VertexName> = Vec::new();
let mut iter = set.iter().await?;
// PERF: This is not an efficient async implementation.
while let Some(vertex) = iter.next().await {
let parents = this.parent_names(vertex?).await?;
result.extend(parents);
}
Ok(NameSet::from_static_names(result))
}
pub(crate) async fn first_ancestor_nth(
this: &(impl DagAlgorithm + ?Sized),
name: VertexName,
n: u64,
) -> Result<Option<VertexName>> {
let mut vertex = name.clone();
for _ in 0..n {
let parents = this.parent_names(vertex).await?;
if parents.is_empty() {
return Ok(None);
}
vertex = parents[0].clone();
}
Ok(Some(vertex))
}
pub(crate) async fn first_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
let mut to_visit: Vec<VertexName> = {
let mut list = Vec::with_capacity(set.count().await?);
let mut iter = set.iter().await?;
while let Some(next) = iter.next().await {
let vertex = next?;
list.push(vertex);
}
list
};
let mut visited: HashSet<VertexName> = to_visit.clone().into_iter().collect();
while let Some(v) = to_visit.pop() {
#[allow(clippy::never_loop)]
if let Some(parent) = this.parent_names(v).await?.into_iter().next() {
if visited.insert(parent.clone()) |
}
}
let hints = Hints::new_inherit_idmap_dag(set.hints());
let set = NameSet::from_iter(visited.into_iter().map(Ok), hints);
this.sort(&set).await
}
pub(crate) async fn heads(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
Ok(set.clone() - this.parents(set).await?)
}
pub(crate) async fn roots(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
Ok(set.clone() - this.children(set).await?)
}
pub(crate) async fn merges(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
let this = this.dag_snapshot()?;
Ok(set.filter(Box::new(move |v: &VertexName| {
let this = this.clone();
Box::pin(async move {
DagAlgorithm::parent_names(&this, v.clone())
.await
.map(|ps| ps.len() >= 2)
})
})))
}
pub(crate) async fn reachable_roots(
this: &(impl DagAlgorithm + ?Sized),
roots: NameSet,
heads: NameSet,
) -> Result<NameSet> {
let heads_ancestors = this.ancestors(heads.clone()).await?;
let roots = roots & heads_ancestors.clone(); // Filter out "bogus" roots.
let only = heads_ancestors - this.ancestors(roots.clone()).await?;
Ok(roots.clone() & (heads.clone() | this.parents(only).await?))
}
pub(crate) async fn heads_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
this.heads(this.ancestors(set).await?).await
}
pub(crate) async fn only(
this: &(impl DagAlgorithm + ?Sized),
reachable: NameSet,
unreachable: NameSet,
) -> Result<NameSet> {
let reachable = this.ancestors(reachable).await?;
let unreachable = this.ancestors(unreachable).await?;
Ok(reachable - unreachable)
}
pub(crate) async fn only_both(
this: &(impl DagAlgorithm + ?Sized),
reachable: NameSet,
unreachable: NameSet,
) -> Result<(NameSet, NameSet)> {
let reachable = this.ancestors(reachable).await?;
let unreachable = this.ancestors(unreachable).await?;
Ok((reachable - unreachable.clone(), unreachable))
}
pub(crate) async fn gca_one(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<Option<VertexName>> {
this.gca_all(set)
.await?
.iter()
.await?
.next()
.await
.transpose()
}
pub(crate) async fn gca_all(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
this.heads_ancestors(this.common_ancestors(set).await?)
.await
}
pub(crate) async fn common_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
let result = match set.count().await? {
0 => set,
1 => this.ancestors(set).await?,
_ => {
// Try to reduce the size of `set`.
// `common_ancestors(X)` = `common_ancestors(roots(X))`.
let set = this.roots(set).await?;
let mut iter = set.iter().await?;
let mut result = this
.ancestors(NameSet::from(iter.next().await.unwrap()?))
.await?;
while let Some(v) = iter.next().await {
result = result.intersection(&this.ancestors(NameSet::from(v?)).await?);
}
result
}
};
Ok(result)
}
pub(crate) async fn is_ancestor(
this: &(impl DagAlgorithm + ?Sized),
ancestor: VertexName,
descendant: VertexName,
) -> Result<bool> {
let mut to_visit = vec![descendant];
let mut visited: HashSet<_> = to_visit.clone().into_iter().collect();
while let Some(v) = to_visit.pop() {
if v == ancestor {
return Ok(true);
}
for parent in this.parent_names(v).await? {
if visited.insert(parent.clone()) {
to_visit.push(parent);
}
}
}
Ok(false)
}
#[tracing::instrument(skip(this), level=tracing::Level::DEBUG)]
pub(crate) async fn hint_subdag_for_insertion(
this: &(impl Parents + ?Sized),
scope: &NameSet,
heads: &[VertexName],
) -> Result<MemNameDag> {
let count = scope.count().await?;
tracing::trace!("hint_subdag_for_insertion: pending vertexes: {}", count);
// ScopedParents only contains parents within "scope".
struct ScopedParents<'a, P: Parents + ?Sized> {
parents: &'a P,
scope: &'a NameSet,
}
#[async_trait::async_trait]
impl<'a, P: Parents + ?Sized> Parents for ScopedParents<'a, P> {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
let parents: Vec<VertexName> = self.parents.parent_names(name).await?;
// Filter by scope. We don't need to provide a "correct" parents here.
// It is only used to optimize network fetches, not used to actually insert
// to the graph.
let mut filtered_parents = Vec::with_capacity(parents.len());
for v in parents {
if self.scope.contains(&v).await? {
filtered_parents.push(v)
}
}
Ok(filtered_parents)
}
async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> {
// No need to use such a hint (to avoid infinite recursion).
// Pending names should exist in the graph without using remote fetching.
Ok(MemNameDag::new())
}
}
// Insert vertexes in `scope` to `dag`.
let mut dag = MemNameDag::new();
// The MemNameDag should not be lazy.
assert!(!dag.is_vertex_lazy());
let scoped_parents = ScopedParents {
parents: this,
scope,
};
dag.add_heads(&scoped_parents, &heads.into()).await?;
Ok(dag)
}
| {
to_visit.push(parent);
} | conditional_block |
default_impl.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::collections::HashSet;
use std::future::Future;
use std::sync::Arc;
use futures::future::BoxFuture;
use futures::FutureExt;
use futures::StreamExt;
use futures::TryStreamExt;
use crate::namedag::MemNameDag;
use crate::nameset::hints::Hints;
use crate::ops::DagAddHeads;
use crate::ops::IdConvert;
use crate::ops::IdDagAlgorithm;
use crate::ops::Parents;
use crate::DagAlgorithm;
use crate::Id;
use crate::IdSet;
use crate::NameSet;
use crate::Result;
use crate::VertexName;
/// Re-create the graph so it looks better when rendered.
///
/// For example, the left-side graph will be rewritten to the right-side:
///
/// 1. Linearize.
///
/// ```plain,ignore
/// A A # Linearize is done by IdMap::assign_heads,
/// | | # as long as the heads provided are the heads
/// | C B # of the whole graph ("A", "C", not "B", "D").
/// | | |
/// B | -> | C
/// | | | |
/// | D | D
/// |/ |/
/// E E
/// ```
///
/// 2. Reorder branches (at different branching points) to reduce columns.
///
/// ```plain,ignore
/// D B
/// | | # Assuming the main branch is B-C-E.
/// B | | A # Branching point of the D branch is "C"
/// | | |/ # Branching point of the A branch is "C"
/// | | A -> C # The D branch should be moved to below
/// | |/ | # the A branch.
/// | | | D
/// |/| |/
/// C / E
/// |/
/// E
/// ```
///
/// 3. Reorder branches (at a same branching point) to reduce length of
/// edges.
///
/// ```plain,ignore
/// D A
/// | | # This is done by picking the longest
/// | A B # branch (A-B-C-E) as the "main branch"
/// | | | # and work on the remaining branches
/// | B -> C # recursively.
/// | | |
/// | C | D
/// |/ |/
/// E E
/// ```
///
/// `main_branch` optionally defines how to sort the heads. A head `x` will
/// be emitted first during iteration, if `ancestors(x) & main_branch`
/// contains larger vertexes. For example, if `main_branch` is `[C, D, E]`,
/// then `C` will be emitted first, and the returned DAG will have `all()`
/// output `[C, D, A, B, E]`. Practically, `main_branch` usually contains
/// "public" commits.
///
/// This function is expensive. Only run on small graphs.
///
/// This function is currently more optimized for "forking" cases. It is
/// not yet optimized for graphs with many merges.
pub(crate) async fn beautify(
this: &(impl DagAlgorithm + ?Sized),
main_branch: Option<NameSet>,
) -> Result<MemNameDag> {
// Find the "largest" branch.
async fn find_main_branch<F, O>(get_ancestors: &F, heads: &[VertexName]) -> Result<NameSet>
where
F: Fn(&VertexName) -> O,
F: Send,
O: Future<Output = Result<NameSet>>,
O: Send,
{
let mut best_branch = NameSet::empty();
let mut best_count = best_branch.count().await?;
for head in heads {
let branch = get_ancestors(head).await?;
let count = branch.count().await?;
if count > best_count {
best_count = count;
best_branch = branch;
}
}
Ok(best_branch)
}
// Sort heads recursively.
// Cannot use "async fn" due to rustc limitation on async recursion.
fn sort<'a: 't, 'b: 't, 't, F, O>(
get_ancestors: &'a F,
heads: &'b mut [VertexName],
main_branch: NameSet,
) -> BoxFuture<'t, Result<()>>
where
F: Fn(&VertexName) -> O,
F: Send + Sync,
O: Future<Output = Result<NameSet>>,
O: Send,
{
let fut = async move {
if heads.len() <= 1 {
return Ok(());
}
// Sort heads by "branching point" on the main branch.
let mut branching_points: HashMap<VertexName, usize> =
HashMap::with_capacity(heads.len());
for head in heads.iter() {
let count = (get_ancestors(head).await? & main_branch.clone())
.count()
.await?;
branching_points.insert(head.clone(), count);
}
heads.sort_by_key(|v| branching_points.get(v));
// For heads with a same branching point, sort them recursively
// using a different "main branch".
let mut start = 0;
let mut start_branching_point: Option<usize> = None;
for end in 0..=heads.len() {
let branching_point = heads
.get(end)
.and_then(|h| branching_points.get(&h).cloned());
if branching_point != start_branching_point {
if start + 1 < end {
let heads = &mut heads[start..end];
let main_branch = find_main_branch(get_ancestors, heads).await?;
// "boxed" is used to workaround async recursion.
sort(get_ancestors, heads, main_branch).boxed().await?;
}
start = end;
start_branching_point = branching_point;
}
}
Ok(())
};
Box::pin(fut)
}
let main_branch = main_branch.unwrap_or_else(NameSet::empty);
let heads = this
.heads_ancestors(this.all().await?)
.await?
.iter()
.await?;
let mut heads: Vec<_> = heads.try_collect().await?;
let get_ancestors = |head: &VertexName| this.ancestors(head.into());
// Stabilize output if the sort key conflicts.
heads.sort();
sort(&get_ancestors, &mut heads[..], main_branch).await?;
let mut dag = MemNameDag::new();
dag.add_heads(&this.dag_snapshot()?, &heads.into()).await?;
Ok(dag)
}
/// Convert `Set` to a `Parents` implementation that only returns vertexes in the set.
pub(crate) async fn set_to_parents(set: &NameSet) -> Result<Option<impl Parents>> {
let (id_set, id_map) = match set.to_id_set_and_id_map_in_o1() {
Some(v) => v,
None => return Ok(None),
};
let dag = match set.dag() {
None => return Ok(None),
Some(dag) => dag,
};
let id_dag = dag.id_dag_snapshot()?;
// Pre-resolve ids to vertexes. Reduce remote lookup round-trips.
let ids: Vec<Id> = id_set.iter_desc().collect();
id_map.vertex_name_batch(&ids).await?;
struct IdParents {
id_set: IdSet,
id_dag: Arc<dyn IdDagAlgorithm + Send + Sync>,
id_map: Arc<dyn IdConvert + Send + Sync>,
}
#[async_trait::async_trait]
impl Parents for IdParents {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
tracing::debug!(
target: "dag::idparents",
"resolving parents for {:?}", &name,
);
let id = self.id_map.vertex_id(name).await?;
let direct_parent_ids = self.id_dag.parent_ids(id)?;
let parent_ids = if direct_parent_ids.iter().all(|&id| self.id_set.contains(id)) {
// Fast path. No "leaked" parents.
direct_parent_ids
} else {
// Slower path.
// PERF: There might be room to optimize (ex. dedicated API like
// reachable_roots).
let parent_id_set = IdSet::from_spans(direct_parent_ids);
let ancestors = self.id_dag.ancestors(parent_id_set)?;
let heads = ancestors.intersection(&self.id_set);
let heads = self.id_dag.heads_ancestors(heads)?;
heads.iter_desc().collect()
};
let vertexes = self.id_map.vertex_name_batch(&parent_ids).await?;
let parents = vertexes.into_iter().collect::<Result<Vec<_>>>()?;
Ok(parents)
}
async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> {
// The `IdParents` is not intended to be inserted to other graphs.
tracing::warn!(
target: "dag::idparents",
"IdParents does not implement hint_subdag_for_insertion() for efficient insertion"
);
Ok(MemNameDag::new())
}
}
let parents = IdParents {
id_set,
id_dag,
id_map,
};
Ok(Some(parents))
}
pub(crate) async fn parents(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
let mut result: Vec<VertexName> = Vec::new();
let mut iter = set.iter().await?;
// PERF: This is not an efficient async implementation.
while let Some(vertex) = iter.next().await {
let parents = this.parent_names(vertex?).await?;
result.extend(parents);
}
Ok(NameSet::from_static_names(result))
}
pub(crate) async fn first_ancestor_nth(
this: &(impl DagAlgorithm + ?Sized),
name: VertexName,
n: u64,
) -> Result<Option<VertexName>> {
let mut vertex = name.clone();
for _ in 0..n {
let parents = this.parent_names(vertex).await?;
if parents.is_empty() {
return Ok(None);
}
vertex = parents[0].clone();
}
Ok(Some(vertex))
}
pub(crate) async fn first_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
let mut to_visit: Vec<VertexName> = {
let mut list = Vec::with_capacity(set.count().await?);
let mut iter = set.iter().await?;
while let Some(next) = iter.next().await {
let vertex = next?;
list.push(vertex);
}
list
};
let mut visited: HashSet<VertexName> = to_visit.clone().into_iter().collect();
while let Some(v) = to_visit.pop() {
#[allow(clippy::never_loop)]
if let Some(parent) = this.parent_names(v).await?.into_iter().next() {
if visited.insert(parent.clone()) {
to_visit.push(parent);
}
}
}
let hints = Hints::new_inherit_idmap_dag(set.hints());
let set = NameSet::from_iter(visited.into_iter().map(Ok), hints);
this.sort(&set).await
}
pub(crate) async fn heads(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
Ok(set.clone() - this.parents(set).await?)
}
pub(crate) async fn roots(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
Ok(set.clone() - this.children(set).await?)
}
pub(crate) async fn merges(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
let this = this.dag_snapshot()?;
Ok(set.filter(Box::new(move |v: &VertexName| {
let this = this.clone();
Box::pin(async move {
DagAlgorithm::parent_names(&this, v.clone())
.await
.map(|ps| ps.len() >= 2)
})
})))
}
pub(crate) async fn reachable_roots(
this: &(impl DagAlgorithm + ?Sized),
roots: NameSet,
heads: NameSet,
) -> Result<NameSet> {
let heads_ancestors = this.ancestors(heads.clone()).await?;
let roots = roots & heads_ancestors.clone(); // Filter out "bogus" roots.
let only = heads_ancestors - this.ancestors(roots.clone()).await?;
Ok(roots.clone() & (heads.clone() | this.parents(only).await?))
}
pub(crate) async fn heads_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
this.heads(this.ancestors(set).await?).await
}
pub(crate) async fn only(
this: &(impl DagAlgorithm + ?Sized),
reachable: NameSet,
unreachable: NameSet,
) -> Result<NameSet> {
let reachable = this.ancestors(reachable).await?;
let unreachable = this.ancestors(unreachable).await?;
Ok(reachable - unreachable)
}
pub(crate) async fn only_both(
this: &(impl DagAlgorithm + ?Sized),
reachable: NameSet,
unreachable: NameSet,
) -> Result<(NameSet, NameSet)> {
let reachable = this.ancestors(reachable).await?;
let unreachable = this.ancestors(unreachable).await?;
Ok((reachable - unreachable.clone(), unreachable))
}
pub(crate) async fn gca_one(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<Option<VertexName>> |
pub(crate) async fn gca_all(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
this.heads_ancestors(this.common_ancestors(set).await?)
.await
}
pub(crate) async fn common_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
let result = match set.count().await? {
0 => set,
1 => this.ancestors(set).await?,
_ => {
// Try to reduce the size of `set`.
// `common_ancestors(X)` = `common_ancestors(roots(X))`.
let set = this.roots(set).await?;
let mut iter = set.iter().await?;
let mut result = this
.ancestors(NameSet::from(iter.next().await.unwrap()?))
.await?;
while let Some(v) = iter.next().await {
result = result.intersection(&this.ancestors(NameSet::from(v?)).await?);
}
result
}
};
Ok(result)
}
pub(crate) async fn is_ancestor(
this: &(impl DagAlgorithm + ?Sized),
ancestor: VertexName,
descendant: VertexName,
) -> Result<bool> {
let mut to_visit = vec![descendant];
let mut visited: HashSet<_> = to_visit.clone().into_iter().collect();
while let Some(v) = to_visit.pop() {
if v == ancestor {
return Ok(true);
}
for parent in this.parent_names(v).await? {
if visited.insert(parent.clone()) {
to_visit.push(parent);
}
}
}
Ok(false)
}
#[tracing::instrument(skip(this), level=tracing::Level::DEBUG)]
pub(crate) async fn hint_subdag_for_insertion(
this: &(impl Parents + ?Sized),
scope: &NameSet,
heads: &[VertexName],
) -> Result<MemNameDag> {
let count = scope.count().await?;
tracing::trace!("hint_subdag_for_insertion: pending vertexes: {}", count);
// ScopedParents only contains parents within "scope".
struct ScopedParents<'a, P: Parents + ?Sized> {
parents: &'a P,
scope: &'a NameSet,
}
#[async_trait::async_trait]
impl<'a, P: Parents + ?Sized> Parents for ScopedParents<'a, P> {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
let parents: Vec<VertexName> = self.parents.parent_names(name).await?;
// Filter by scope. We don't need to provide a "correct" parents here.
// It is only used to optimize network fetches, not used to actually insert
// to the graph.
let mut filtered_parents = Vec::with_capacity(parents.len());
for v in parents {
if self.scope.contains(&v).await? {
filtered_parents.push(v)
}
}
Ok(filtered_parents)
}
async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> {
// No need to use such a hint (to avoid infinite recursion).
// Pending names should exist in the graph without using remote fetching.
Ok(MemNameDag::new())
}
}
// Insert vertexes in `scope` to `dag`.
let mut dag = MemNameDag::new();
// The MemNameDag should not be lazy.
assert!(!dag.is_vertex_lazy());
let scoped_parents = ScopedParents {
parents: this,
scope,
};
dag.add_heads(&scoped_parents, &heads.into()).await?;
Ok(dag)
}
| {
this.gca_all(set)
.await?
.iter()
.await?
.next()
.await
.transpose()
} | identifier_body |
default_impl.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::collections::HashSet;
use std::future::Future;
use std::sync::Arc;
use futures::future::BoxFuture;
use futures::FutureExt;
use futures::StreamExt;
use futures::TryStreamExt;
use crate::namedag::MemNameDag;
use crate::nameset::hints::Hints;
use crate::ops::DagAddHeads;
use crate::ops::IdConvert;
use crate::ops::IdDagAlgorithm;
use crate::ops::Parents;
use crate::DagAlgorithm;
use crate::Id;
use crate::IdSet;
use crate::NameSet;
use crate::Result;
use crate::VertexName;
/// Re-create the graph so it looks better when rendered.
///
/// For example, the left-side graph will be rewritten to the right-side:
///
/// 1. Linearize.
///
/// ```plain,ignore
/// A A # Linearize is done by IdMap::assign_heads,
/// | | # as long as the heads provided are the heads
/// | C B # of the whole graph ("A", "C", not "B", "D").
/// | | |
/// B | -> | C
/// | | | |
/// | D | D
/// |/ |/
/// E E
/// ```
///
/// 2. Reorder branches (at different branching points) to reduce columns.
///
/// ```plain,ignore
/// D B
/// | | # Assuming the main branch is B-C-E.
/// B | | A # Branching point of the D branch is "C"
/// | | |/ # Branching point of the A branch is "C"
/// | | A -> C # The D branch should be moved to below
/// | |/ | # the A branch.
/// | | | D
/// |/| |/
/// C / E
/// |/
/// E
/// ```
///
/// 3. Reorder branches (at a same branching point) to reduce length of
/// edges.
///
/// ```plain,ignore
/// D A
/// | | # This is done by picking the longest
/// | A B # branch (A-B-C-E) as the "main branch"
/// | | | # and work on the remaining branches
/// | B -> C # recursively.
/// | | |
/// | C | D
/// |/ |/
/// E E
/// ```
///
/// `main_branch` optionally defines how to sort the heads. A head `x` will
/// be emitted first during iteration, if `ancestors(x) & main_branch`
/// contains larger vertexes. For example, if `main_branch` is `[C, D, E]`,
/// then `C` will be emitted first, and the returned DAG will have `all()`
/// output `[C, D, A, B, E]`. Practically, `main_branch` usually contains
/// "public" commits.
///
/// This function is expensive. Only run on small graphs.
///
/// This function is currently more optimized for "forking" cases. It is
/// not yet optimized for graphs with many merges.
pub(crate) async fn beautify(
this: &(impl DagAlgorithm + ?Sized),
main_branch: Option<NameSet>,
) -> Result<MemNameDag> {
// Find the "largest" branch.
async fn find_main_branch<F, O>(get_ancestors: &F, heads: &[VertexName]) -> Result<NameSet>
where
F: Fn(&VertexName) -> O,
F: Send,
O: Future<Output = Result<NameSet>>,
O: Send,
{
let mut best_branch = NameSet::empty();
let mut best_count = best_branch.count().await?;
for head in heads {
let branch = get_ancestors(head).await?;
let count = branch.count().await?;
if count > best_count {
best_count = count;
best_branch = branch;
}
}
Ok(best_branch)
}
// Sort heads recursively.
// Cannot use "async fn" due to rustc limitation on async recursion.
fn sort<'a: 't, 'b: 't, 't, F, O>(
get_ancestors: &'a F,
heads: &'b mut [VertexName],
main_branch: NameSet,
) -> BoxFuture<'t, Result<()>>
where
F: Fn(&VertexName) -> O,
F: Send + Sync,
O: Future<Output = Result<NameSet>>,
O: Send,
{
let fut = async move {
if heads.len() <= 1 {
return Ok(());
}
// Sort heads by "branching point" on the main branch.
let mut branching_points: HashMap<VertexName, usize> =
HashMap::with_capacity(heads.len());
for head in heads.iter() {
let count = (get_ancestors(head).await? & main_branch.clone())
.count()
.await?;
branching_points.insert(head.clone(), count);
}
heads.sort_by_key(|v| branching_points.get(v));
// For heads with a same branching point, sort them recursively
// using a different "main branch".
let mut start = 0;
let mut start_branching_point: Option<usize> = None;
for end in 0..=heads.len() {
let branching_point = heads
.get(end)
.and_then(|h| branching_points.get(&h).cloned());
if branching_point != start_branching_point {
if start + 1 < end {
let heads = &mut heads[start..end];
let main_branch = find_main_branch(get_ancestors, heads).await?;
// "boxed" is used to workaround async recursion.
sort(get_ancestors, heads, main_branch).boxed().await?;
}
start = end;
start_branching_point = branching_point;
}
}
Ok(())
};
Box::pin(fut)
}
let main_branch = main_branch.unwrap_or_else(NameSet::empty);
let heads = this
.heads_ancestors(this.all().await?)
.await?
.iter()
.await?;
let mut heads: Vec<_> = heads.try_collect().await?;
let get_ancestors = |head: &VertexName| this.ancestors(head.into());
// Stabilize output if the sort key conflicts.
heads.sort();
sort(&get_ancestors, &mut heads[..], main_branch).await?;
let mut dag = MemNameDag::new();
dag.add_heads(&this.dag_snapshot()?, &heads.into()).await?;
Ok(dag)
}
/// Convert `Set` to a `Parents` implementation that only returns vertexes in the set.
pub(crate) async fn set_to_parents(set: &NameSet) -> Result<Option<impl Parents>> {
let (id_set, id_map) = match set.to_id_set_and_id_map_in_o1() {
Some(v) => v,
None => return Ok(None),
};
let dag = match set.dag() {
None => return Ok(None),
Some(dag) => dag,
};
let id_dag = dag.id_dag_snapshot()?;
// Pre-resolve ids to vertexes. Reduce remote lookup round-trips.
let ids: Vec<Id> = id_set.iter_desc().collect();
id_map.vertex_name_batch(&ids).await?;
struct IdParents {
id_set: IdSet,
id_dag: Arc<dyn IdDagAlgorithm + Send + Sync>,
id_map: Arc<dyn IdConvert + Send + Sync>,
}
#[async_trait::async_trait]
impl Parents for IdParents {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
tracing::debug!(
target: "dag::idparents",
"resolving parents for {:?}", &name,
);
let id = self.id_map.vertex_id(name).await?;
let direct_parent_ids = self.id_dag.parent_ids(id)?;
let parent_ids = if direct_parent_ids.iter().all(|&id| self.id_set.contains(id)) {
// Fast path. No "leaked" parents.
direct_parent_ids
} else {
// Slower path.
// PERF: There might be room to optimize (ex. dedicated API like
// reachable_roots).
let parent_id_set = IdSet::from_spans(direct_parent_ids);
let ancestors = self.id_dag.ancestors(parent_id_set)?;
let heads = ancestors.intersection(&self.id_set);
let heads = self.id_dag.heads_ancestors(heads)?;
heads.iter_desc().collect()
};
let vertexes = self.id_map.vertex_name_batch(&parent_ids).await?;
let parents = vertexes.into_iter().collect::<Result<Vec<_>>>()?;
Ok(parents)
}
async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> {
// The `IdParents` is not intended to be inserted to other graphs.
tracing::warn!(
target: "dag::idparents",
"IdParents does not implement hint_subdag_for_insertion() for efficient insertion"
);
Ok(MemNameDag::new())
}
}
let parents = IdParents {
id_set,
id_dag,
id_map,
};
Ok(Some(parents))
}
pub(crate) async fn parents(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
let mut result: Vec<VertexName> = Vec::new();
let mut iter = set.iter().await?;
// PERF: This is not an efficient async implementation.
while let Some(vertex) = iter.next().await {
let parents = this.parent_names(vertex?).await?;
result.extend(parents);
}
Ok(NameSet::from_static_names(result))
}
pub(crate) async fn first_ancestor_nth(
this: &(impl DagAlgorithm + ?Sized),
name: VertexName,
n: u64,
) -> Result<Option<VertexName>> {
let mut vertex = name.clone();
for _ in 0..n {
let parents = this.parent_names(vertex).await?;
if parents.is_empty() {
return Ok(None);
}
vertex = parents[0].clone();
}
Ok(Some(vertex))
}
pub(crate) async fn first_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
let mut to_visit: Vec<VertexName> = {
let mut list = Vec::with_capacity(set.count().await?);
let mut iter = set.iter().await?;
while let Some(next) = iter.next().await {
let vertex = next?;
list.push(vertex);
}
list
};
let mut visited: HashSet<VertexName> = to_visit.clone().into_iter().collect();
while let Some(v) = to_visit.pop() {
#[allow(clippy::never_loop)]
if let Some(parent) = this.parent_names(v).await?.into_iter().next() {
if visited.insert(parent.clone()) {
to_visit.push(parent);
}
}
}
let hints = Hints::new_inherit_idmap_dag(set.hints());
let set = NameSet::from_iter(visited.into_iter().map(Ok), hints);
this.sort(&set).await
}
pub(crate) async fn heads(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
Ok(set.clone() - this.parents(set).await?)
}
pub(crate) async fn roots(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
Ok(set.clone() - this.children(set).await?)
}
pub(crate) async fn merges(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
let this = this.dag_snapshot()?;
Ok(set.filter(Box::new(move |v: &VertexName| {
let this = this.clone();
Box::pin(async move {
DagAlgorithm::parent_names(&this, v.clone())
.await
.map(|ps| ps.len() >= 2)
})
})))
}
pub(crate) async fn reachable_roots(
this: &(impl DagAlgorithm + ?Sized),
roots: NameSet,
heads: NameSet,
) -> Result<NameSet> {
let heads_ancestors = this.ancestors(heads.clone()).await?;
let roots = roots & heads_ancestors.clone(); // Filter out "bogus" roots.
let only = heads_ancestors - this.ancestors(roots.clone()).await?;
Ok(roots.clone() & (heads.clone() | this.parents(only).await?))
}
pub(crate) async fn heads_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
this.heads(this.ancestors(set).await?).await
}
pub(crate) async fn only(
this: &(impl DagAlgorithm + ?Sized),
reachable: NameSet,
unreachable: NameSet,
) -> Result<NameSet> {
let reachable = this.ancestors(reachable).await?;
let unreachable = this.ancestors(unreachable).await?;
Ok(reachable - unreachable)
}
pub(crate) async fn only_both(
this: &(impl DagAlgorithm + ?Sized),
reachable: NameSet,
unreachable: NameSet,
) -> Result<(NameSet, NameSet)> {
let reachable = this.ancestors(reachable).await?;
let unreachable = this.ancestors(unreachable).await?;
Ok((reachable - unreachable.clone(), unreachable))
}
pub(crate) async fn gca_one(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<Option<VertexName>> {
this.gca_all(set)
.await?
.iter()
.await?
.next()
.await
.transpose()
}
pub(crate) async fn gca_all(this: &(impl DagAlgorithm + ?Sized), set: NameSet) -> Result<NameSet> {
this.heads_ancestors(this.common_ancestors(set).await?)
.await
}
pub(crate) async fn common_ancestors(
this: &(impl DagAlgorithm + ?Sized),
set: NameSet,
) -> Result<NameSet> {
let result = match set.count().await? {
0 => set,
1 => this.ancestors(set).await?,
_ => {
// Try to reduce the size of `set`.
// `common_ancestors(X)` = `common_ancestors(roots(X))`.
let set = this.roots(set).await?;
let mut iter = set.iter().await?;
let mut result = this
.ancestors(NameSet::from(iter.next().await.unwrap()?))
.await?;
while let Some(v) = iter.next().await {
result = result.intersection(&this.ancestors(NameSet::from(v?)).await?);
}
result
}
};
Ok(result)
}
pub(crate) async fn is_ancestor(
this: &(impl DagAlgorithm + ?Sized),
ancestor: VertexName,
descendant: VertexName,
) -> Result<bool> {
let mut to_visit = vec![descendant];
let mut visited: HashSet<_> = to_visit.clone().into_iter().collect();
while let Some(v) = to_visit.pop() {
if v == ancestor {
return Ok(true);
}
for parent in this.parent_names(v).await? {
if visited.insert(parent.clone()) {
to_visit.push(parent);
}
}
}
Ok(false)
}
#[tracing::instrument(skip(this), level=tracing::Level::DEBUG)]
pub(crate) async fn hint_subdag_for_insertion(
this: &(impl Parents + ?Sized),
scope: &NameSet,
heads: &[VertexName],
) -> Result<MemNameDag> {
let count = scope.count().await?;
tracing::trace!("hint_subdag_for_insertion: pending vertexes: {}", count);
// ScopedParents only contains parents within "scope".
struct ScopedParents<'a, P: Parents + ?Sized> {
parents: &'a P,
scope: &'a NameSet,
}
#[async_trait::async_trait]
impl<'a, P: Parents + ?Sized> Parents for ScopedParents<'a, P> {
async fn parent_names(&self, name: VertexName) -> Result<Vec<VertexName>> {
let parents: Vec<VertexName> = self.parents.parent_names(name).await?;
// Filter by scope. We don't need to provide a "correct" parents here.
// It is only used to optimize network fetches, not used to actually insert
// to the graph.
let mut filtered_parents = Vec::with_capacity(parents.len());
for v in parents {
if self.scope.contains(&v).await? {
filtered_parents.push(v) | }
async fn hint_subdag_for_insertion(&self, _heads: &[VertexName]) -> Result<MemNameDag> {
// No need to use such a hint (to avoid infinite recursion).
// Pending names should exist in the graph without using remote fetching.
Ok(MemNameDag::new())
}
}
// Insert vertexes in `scope` to `dag`.
let mut dag = MemNameDag::new();
// The MemNameDag should not be lazy.
assert!(!dag.is_vertex_lazy());
let scoped_parents = ScopedParents {
parents: this,
scope,
};
dag.add_heads(&scoped_parents, &heads.into()).await?;
Ok(dag)
} | }
}
Ok(filtered_parents) | random_line_split |
qr.js | $(function () {
$.widget("as24.qr", {
_create: function () {
var self = this;
$(self.element).find('[data-description="QR-Code Generation"]').find("p").hide();
$(self.element).find('[data-generate="qr-code"]').click(function () {
$(self.element).find('[data-description="QR-Code Generation"]').find("p").show();
var url = $(self.element).find('[name="urlQRCode"]').val();
var featureName = $(self.element).find('[name="name"]').val();
var featureEnabled = url + "?" + $.param({ "FeatureBee": '#' + featureName + "=true#" });
var featureDisabled = url + "?" + $.param({ "FeatureBee": '#' + featureName + "=false#" });
$(self.element).find('#qrcode_enable').empty();
$(self.element).find('#qrcode_enable').qrcode(featureEnabled);
$(self.element).find('#qrcode_disable').empty();
$(self.element).find('#qrcode_disable').qrcode(featureDisabled);
});
}
| });
}) | random_line_split | |
workspaceTimeoutWarn.js | const util = require('util');
const config = require('../lib/config');
const logger = require('../lib/logger');
const workspaceHelper = require('../lib/workspace');
const sqldb = require('../prairielib/lib/sql-db');
const sqlLoader = require('../prairielib/lib/sql-loader');
const sql = sqlLoader.loadSqlEquiv(__filename);
module.exports = {};
module.exports.runAsync = async () => {
const params = {
launched_timeout_sec: config.workspaceLaunchedTimeoutSec,
launched_timeout_warn_sec: config.workspaceLaunchedTimeoutWarnSec,
};
const result = await sqldb.queryAsync(sql.select_almost_launched_timeout_workspaces, params);
const workspaces = result.rows; | `WARNING: This workspace will stop in < ${time_to_timeout_min} min. Click "Reboot" to keep working.`
);
}
};
module.exports.run = util.callbackify(module.exports.runAsync); | for (const workspace of workspaces) {
logger.verbose(`workspaceTimeoutWarn: timeout warning for workspace_id = ${workspace.id}`);
const time_to_timeout_min = Math.ceil(workspace.time_to_timeout_sec / 60);
await workspaceHelper.updateMessage(
workspace.id, | random_line_split |
p1_no_assignee.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from libmozdata import utils as lmdutils
from auto_nag import utils
from auto_nag.bzcleaner import BzCleaner
from auto_nag.escalation import Escalation, NoActivityDays
from auto_nag.nag_me import Nag
from auto_nag.round_robin import RoundRobin
class P1NoAssignee(BzCleaner, Nag):
def __init__(self):
super(P1NoAssignee, self).__init__()
self.escalation = Escalation(
self.people,
data=utils.get_config(self.name(), "escalation"),
skiplist=utils.get_config("workflow", "supervisor_skiplist", []),
)
self.round_robin = RoundRobin.get_instance()
self.components_skiplist = utils.get_config("workflow", "components_skiplist")
def description(self):
return "P1 Bugs, no assignee and no activity for few days"
def nag_template(self):
return self.template()
def get_extra_for_template(self):
|
def get_extra_for_nag_template(self):
return self.get_extra_for_template()
def get_extra_for_needinfo_template(self):
return self.get_extra_for_template()
def ignore_meta(self):
return True
def has_last_comment_time(self):
return True
def has_product_component(self):
return True
def columns(self):
return ["component", "id", "summary", "last_comment"]
def handle_bug(self, bug, data):
# check if the product::component is in the list
if utils.check_product_component(self.components_skiplist, bug):
return None
return bug
def get_mail_to_auto_ni(self, bug):
# For now, disable the needinfo
return None
# Avoid to ni everyday...
if self.has_bot_set_ni(bug):
return None
mail, nick = self.round_robin.get(bug, self.date)
if mail and nick:
return {"mail": mail, "nickname": nick}
return None
def set_people_to_nag(self, bug, buginfo):
priority = "high"
if not self.filter_bug(priority):
return None
owners = self.round_robin.get(bug, self.date, only_one=False, has_nick=False)
real_owner = bug["triage_owner"]
self.add_triage_owner(owners, real_owner=real_owner)
if not self.add(owners, buginfo, priority=priority):
self.add_no_manager(buginfo["id"])
return bug
def get_bz_params(self, date):
self.ndays = NoActivityDays(self.name()).get(
(utils.get_next_release_date() - self.nag_date).days
)
self.date = lmdutils.get_date_ymd(date)
fields = ["triage_owner", "flags"]
params = {
"bug_type": "defect",
"include_fields": fields,
"resolution": "---",
"f1": "priority",
"o1": "equals",
"v1": "P1",
"f2": "days_elapsed",
"o2": "greaterthaneq",
"v2": self.ndays,
}
utils.get_empty_assignees(params)
return params
if __name__ == "__main__":
P1NoAssignee().run()
| return {"ndays": self.ndays} | identifier_body |
p1_no_assignee.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from libmozdata import utils as lmdutils
from auto_nag import utils
from auto_nag.bzcleaner import BzCleaner
from auto_nag.escalation import Escalation, NoActivityDays
from auto_nag.nag_me import Nag
from auto_nag.round_robin import RoundRobin
class P1NoAssignee(BzCleaner, Nag):
def __init__(self):
super(P1NoAssignee, self).__init__()
self.escalation = Escalation(
self.people,
data=utils.get_config(self.name(), "escalation"),
skiplist=utils.get_config("workflow", "supervisor_skiplist", []),
)
self.round_robin = RoundRobin.get_instance()
self.components_skiplist = utils.get_config("workflow", "components_skiplist")
def description(self):
return "P1 Bugs, no assignee and no activity for few days"
def nag_template(self):
return self.template()
def get_extra_for_template(self):
return {"ndays": self.ndays}
def get_extra_for_nag_template(self):
return self.get_extra_for_template()
def get_extra_for_needinfo_template(self):
return self.get_extra_for_template()
def ignore_meta(self):
return True
def has_last_comment_time(self):
return True
def has_product_component(self):
return True
def columns(self):
return ["component", "id", "summary", "last_comment"]
def handle_bug(self, bug, data):
# check if the product::component is in the list
if utils.check_product_component(self.components_skiplist, bug):
return None
return bug
def get_mail_to_auto_ni(self, bug):
# For now, disable the needinfo
return None
# Avoid to ni everyday...
if self.has_bot_set_ni(bug):
return None | return None
def set_people_to_nag(self, bug, buginfo):
priority = "high"
if not self.filter_bug(priority):
return None
owners = self.round_robin.get(bug, self.date, only_one=False, has_nick=False)
real_owner = bug["triage_owner"]
self.add_triage_owner(owners, real_owner=real_owner)
if not self.add(owners, buginfo, priority=priority):
self.add_no_manager(buginfo["id"])
return bug
def get_bz_params(self, date):
self.ndays = NoActivityDays(self.name()).get(
(utils.get_next_release_date() - self.nag_date).days
)
self.date = lmdutils.get_date_ymd(date)
fields = ["triage_owner", "flags"]
params = {
"bug_type": "defect",
"include_fields": fields,
"resolution": "---",
"f1": "priority",
"o1": "equals",
"v1": "P1",
"f2": "days_elapsed",
"o2": "greaterthaneq",
"v2": self.ndays,
}
utils.get_empty_assignees(params)
return params
if __name__ == "__main__":
P1NoAssignee().run() |
mail, nick = self.round_robin.get(bug, self.date)
if mail and nick:
return {"mail": mail, "nickname": nick}
| random_line_split |
p1_no_assignee.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from libmozdata import utils as lmdutils
from auto_nag import utils
from auto_nag.bzcleaner import BzCleaner
from auto_nag.escalation import Escalation, NoActivityDays
from auto_nag.nag_me import Nag
from auto_nag.round_robin import RoundRobin
class | (BzCleaner, Nag):
def __init__(self):
super(P1NoAssignee, self).__init__()
self.escalation = Escalation(
self.people,
data=utils.get_config(self.name(), "escalation"),
skiplist=utils.get_config("workflow", "supervisor_skiplist", []),
)
self.round_robin = RoundRobin.get_instance()
self.components_skiplist = utils.get_config("workflow", "components_skiplist")
def description(self):
return "P1 Bugs, no assignee and no activity for few days"
def nag_template(self):
return self.template()
def get_extra_for_template(self):
return {"ndays": self.ndays}
def get_extra_for_nag_template(self):
return self.get_extra_for_template()
def get_extra_for_needinfo_template(self):
return self.get_extra_for_template()
def ignore_meta(self):
return True
def has_last_comment_time(self):
return True
def has_product_component(self):
return True
def columns(self):
return ["component", "id", "summary", "last_comment"]
def handle_bug(self, bug, data):
# check if the product::component is in the list
if utils.check_product_component(self.components_skiplist, bug):
return None
return bug
def get_mail_to_auto_ni(self, bug):
# For now, disable the needinfo
return None
# Avoid to ni everyday...
if self.has_bot_set_ni(bug):
return None
mail, nick = self.round_robin.get(bug, self.date)
if mail and nick:
return {"mail": mail, "nickname": nick}
return None
def set_people_to_nag(self, bug, buginfo):
priority = "high"
if not self.filter_bug(priority):
return None
owners = self.round_robin.get(bug, self.date, only_one=False, has_nick=False)
real_owner = bug["triage_owner"]
self.add_triage_owner(owners, real_owner=real_owner)
if not self.add(owners, buginfo, priority=priority):
self.add_no_manager(buginfo["id"])
return bug
def get_bz_params(self, date):
self.ndays = NoActivityDays(self.name()).get(
(utils.get_next_release_date() - self.nag_date).days
)
self.date = lmdutils.get_date_ymd(date)
fields = ["triage_owner", "flags"]
params = {
"bug_type": "defect",
"include_fields": fields,
"resolution": "---",
"f1": "priority",
"o1": "equals",
"v1": "P1",
"f2": "days_elapsed",
"o2": "greaterthaneq",
"v2": self.ndays,
}
utils.get_empty_assignees(params)
return params
if __name__ == "__main__":
P1NoAssignee().run()
| P1NoAssignee | identifier_name |
p1_no_assignee.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from libmozdata import utils as lmdutils
from auto_nag import utils
from auto_nag.bzcleaner import BzCleaner
from auto_nag.escalation import Escalation, NoActivityDays
from auto_nag.nag_me import Nag
from auto_nag.round_robin import RoundRobin
class P1NoAssignee(BzCleaner, Nag):
def __init__(self):
super(P1NoAssignee, self).__init__()
self.escalation = Escalation(
self.people,
data=utils.get_config(self.name(), "escalation"),
skiplist=utils.get_config("workflow", "supervisor_skiplist", []),
)
self.round_robin = RoundRobin.get_instance()
self.components_skiplist = utils.get_config("workflow", "components_skiplist")
def description(self):
return "P1 Bugs, no assignee and no activity for few days"
def nag_template(self):
return self.template()
def get_extra_for_template(self):
return {"ndays": self.ndays}
def get_extra_for_nag_template(self):
return self.get_extra_for_template()
def get_extra_for_needinfo_template(self):
return self.get_extra_for_template()
def ignore_meta(self):
return True
def has_last_comment_time(self):
return True
def has_product_component(self):
return True
def columns(self):
return ["component", "id", "summary", "last_comment"]
def handle_bug(self, bug, data):
# check if the product::component is in the list
if utils.check_product_component(self.components_skiplist, bug):
return None
return bug
def get_mail_to_auto_ni(self, bug):
# For now, disable the needinfo
return None
# Avoid to ni everyday...
if self.has_bot_set_ni(bug):
return None
mail, nick = self.round_robin.get(bug, self.date)
if mail and nick:
|
return None
def set_people_to_nag(self, bug, buginfo):
priority = "high"
if not self.filter_bug(priority):
return None
owners = self.round_robin.get(bug, self.date, only_one=False, has_nick=False)
real_owner = bug["triage_owner"]
self.add_triage_owner(owners, real_owner=real_owner)
if not self.add(owners, buginfo, priority=priority):
self.add_no_manager(buginfo["id"])
return bug
def get_bz_params(self, date):
self.ndays = NoActivityDays(self.name()).get(
(utils.get_next_release_date() - self.nag_date).days
)
self.date = lmdutils.get_date_ymd(date)
fields = ["triage_owner", "flags"]
params = {
"bug_type": "defect",
"include_fields": fields,
"resolution": "---",
"f1": "priority",
"o1": "equals",
"v1": "P1",
"f2": "days_elapsed",
"o2": "greaterthaneq",
"v2": self.ndays,
}
utils.get_empty_assignees(params)
return params
if __name__ == "__main__":
P1NoAssignee().run()
| return {"mail": mail, "nickname": nick} | conditional_block |
SelectFilterPlugin.tsx | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/* eslint-disable no-param-reassign */
import {
AppSection,
DataMask,
ensureIsArray,
ExtraFormData,
GenericDataType,
JsonObject,
smartDateDetailedFormatter,
t,
tn,
} from '@superset-ui/core';
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Select } from 'src/components';
import debounce from 'lodash/debounce';
import { SLOW_DEBOUNCE } from 'src/constants';
import { useImmerReducer } from 'use-immer';
import { FormItemProps } from 'antd/lib/form';
import { PluginFilterSelectProps, SelectValue } from './types';
import { StyledFormItem, FilterPluginStyle, StatusMessage } from '../common';
import { getDataRecordFormatter, getSelectExtraFormData } from '../../utils';
type DataMaskAction =
| { type: 'ownState'; ownState: JsonObject }
| {
type: 'filterState';
__cache: JsonObject;
extraFormData: ExtraFormData;
filterState: { value: SelectValue; label?: string };
};
function reducer(
draft: DataMask & { __cache?: JsonObject },
action: DataMaskAction,
) {
switch (action.type) {
case 'ownState':
draft.ownState = {
...draft.ownState,
...action.ownState,
};
return draft;
case 'filterState':
draft.extraFormData = action.extraFormData;
// eslint-disable-next-line no-underscore-dangle
draft.__cache = action.__cache;
draft.filterState = { ...draft.filterState, ...action.filterState };
return draft;
default:
return draft;
}
}
export default function PluginFilterSelect(props: PluginFilterSelectProps) {
const {
coltypeMap,
data,
filterState,
formData,
height,
isRefreshing,
width,
setDataMask,
setFocusedFilter,
unsetFocusedFilter,
appSection,
} = props;
const {
enableEmptyFilter,
multiSelect,
showSearch,
inverseSelection,
inputRef,
defaultToFirstItem,
searchAllOptions,
} = formData;
const groupby = ensureIsArray<string>(formData.groupby);
const [col] = groupby;
const [initialColtypeMap] = useState(coltypeMap);
const [dataMask, dispatchDataMask] = useImmerReducer(reducer, {
extraFormData: {},
filterState,
});
const updateDataMask = useCallback(
(values: SelectValue) => {
const emptyFilter =
enableEmptyFilter && !inverseSelection && !values?.length;
const suffix =
inverseSelection && values?.length ? ` (${t('excluded')})` : '';
dispatchDataMask({
type: 'filterState',
__cache: filterState,
extraFormData: getSelectExtraFormData(
col,
values,
emptyFilter,
inverseSelection,
),
filterState: {
...filterState,
label: values?.length
? `${(values || []).join(', ')}${suffix}`
: undefined,
value:
appSection === AppSection.FILTER_CONFIG_MODAL && defaultToFirstItem
? undefined
: values,
},
});
},
[
appSection,
col,
defaultToFirstItem,
dispatchDataMask,
enableEmptyFilter,
inverseSelection,
JSON.stringify(filterState),
],
);
useEffect(() => {
updateDataMask(filterState.value);
}, [JSON.stringify(filterState.value)]);
const isDisabled =
appSection === AppSection.FILTER_CONFIG_MODAL && defaultToFirstItem;
const debouncedOwnStateFunc = useCallback(
debounce((val: string) => {
dispatchDataMask({
type: 'ownState',
ownState: {
coltypeMap: initialColtypeMap,
search: val,
},
});
}, SLOW_DEBOUNCE),
[],
);
const searchWrapper = (val: string) => {
if (searchAllOptions) {
debouncedOwnStateFunc(val);
}
};
const clearSuggestionSearch = () => {
if (searchAllOptions) {
dispatchDataMask({
type: 'ownState',
ownState: {
coltypeMap: initialColtypeMap,
search: null,
},
});
}
};
const handleBlur = () => {
clearSuggestionSearch();
unsetFocusedFilter();
};
const datatype: GenericDataType = coltypeMap[col];
const labelFormatter = useMemo(
() =>
getDataRecordFormatter({
timeFormatter: smartDateDetailedFormatter,
}),
[],
);
const handleChange = (value?: SelectValue | number | string) => {
const values = ensureIsArray(value);
if (values.length === 0) {
updateDataMask(null);
} else {
updateDataMask(values);
}
};
useEffect(() => {
if (defaultToFirstItem && filterState.value === undefined) {
// initialize to first value if set to default to first item
const firstItem: SelectValue = data[0]
? (groupby.map(col => data[0][col]) as string[])
: null;
// firstItem[0] !== undefined for a case when groupby changed but new data still not fetched
// TODO: still need repopulate default value in config modal when column changed
if (firstItem && firstItem[0] !== undefined) {
updateDataMask(firstItem);
}
} else if (isDisabled) | else {
// reset data mask based on filter state
updateDataMask(filterState.value);
}
}, [
col,
isDisabled,
defaultToFirstItem,
enableEmptyFilter,
inverseSelection,
updateDataMask,
data,
groupby,
JSON.stringify(filterState),
]);
useEffect(() => {
setDataMask(dataMask);
}, [JSON.stringify(dataMask)]);
const placeholderText =
data.length === 0
? t('No data')
: tn('%s option', '%s options', data.length, data.length);
const formItemData: FormItemProps = {};
if (filterState.validateMessage) {
formItemData.extra = (
<StatusMessage status={filterState.validateStatus}>
{filterState.validateMessage}
</StatusMessage>
);
}
const options = useMemo(() => {
const options: { label: string; value: string | number }[] = [];
data.forEach(row => {
const [value] = groupby.map(col => row[col]);
options.push({
label: labelFormatter(value, datatype),
value: typeof value === 'number' ? value : String(value),
});
});
return options;
}, [data, datatype, groupby, labelFormatter]);
return (
<FilterPluginStyle height={height} width={width}>
<StyledFormItem
validateStatus={filterState.validateStatus}
{...formItemData}
>
<Select
allowClear
allowNewOptions
// @ts-ignore
value={filterState.value || []}
disabled={isDisabled}
showSearch={showSearch}
mode={multiSelect ? 'multiple' : 'single'}
placeholder={placeholderText}
onSearch={searchWrapper}
onSelect={clearSuggestionSearch}
onBlur={handleBlur}
onMouseEnter={setFocusedFilter}
onMouseLeave={unsetFocusedFilter}
// @ts-ignore
onChange={handleChange}
ref={inputRef}
loading={isRefreshing}
maxTagCount={5}
invertSelection={inverseSelection}
options={options}
/>
</StyledFormItem>
</FilterPluginStyle>
);
}
| {
// empty selection if filter is disabled
updateDataMask(null);
} | conditional_block |
SelectFilterPlugin.tsx | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/* eslint-disable no-param-reassign */
import {
AppSection,
DataMask,
ensureIsArray,
ExtraFormData,
GenericDataType,
JsonObject,
smartDateDetailedFormatter,
t,
tn,
} from '@superset-ui/core';
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Select } from 'src/components';
import debounce from 'lodash/debounce';
import { SLOW_DEBOUNCE } from 'src/constants';
import { useImmerReducer } from 'use-immer';
import { FormItemProps } from 'antd/lib/form';
import { PluginFilterSelectProps, SelectValue } from './types';
import { StyledFormItem, FilterPluginStyle, StatusMessage } from '../common';
import { getDataRecordFormatter, getSelectExtraFormData } from '../../utils';
type DataMaskAction =
| { type: 'ownState'; ownState: JsonObject }
| {
type: 'filterState';
__cache: JsonObject;
extraFormData: ExtraFormData;
filterState: { value: SelectValue; label?: string };
};
function | (
draft: DataMask & { __cache?: JsonObject },
action: DataMaskAction,
) {
switch (action.type) {
case 'ownState':
draft.ownState = {
...draft.ownState,
...action.ownState,
};
return draft;
case 'filterState':
draft.extraFormData = action.extraFormData;
// eslint-disable-next-line no-underscore-dangle
draft.__cache = action.__cache;
draft.filterState = { ...draft.filterState, ...action.filterState };
return draft;
default:
return draft;
}
}
export default function PluginFilterSelect(props: PluginFilterSelectProps) {
const {
coltypeMap,
data,
filterState,
formData,
height,
isRefreshing,
width,
setDataMask,
setFocusedFilter,
unsetFocusedFilter,
appSection,
} = props;
const {
enableEmptyFilter,
multiSelect,
showSearch,
inverseSelection,
inputRef,
defaultToFirstItem,
searchAllOptions,
} = formData;
const groupby = ensureIsArray<string>(formData.groupby);
const [col] = groupby;
const [initialColtypeMap] = useState(coltypeMap);
const [dataMask, dispatchDataMask] = useImmerReducer(reducer, {
extraFormData: {},
filterState,
});
const updateDataMask = useCallback(
(values: SelectValue) => {
const emptyFilter =
enableEmptyFilter && !inverseSelection && !values?.length;
const suffix =
inverseSelection && values?.length ? ` (${t('excluded')})` : '';
dispatchDataMask({
type: 'filterState',
__cache: filterState,
extraFormData: getSelectExtraFormData(
col,
values,
emptyFilter,
inverseSelection,
),
filterState: {
...filterState,
label: values?.length
? `${(values || []).join(', ')}${suffix}`
: undefined,
value:
appSection === AppSection.FILTER_CONFIG_MODAL && defaultToFirstItem
? undefined
: values,
},
});
},
[
appSection,
col,
defaultToFirstItem,
dispatchDataMask,
enableEmptyFilter,
inverseSelection,
JSON.stringify(filterState),
],
);
useEffect(() => {
updateDataMask(filterState.value);
}, [JSON.stringify(filterState.value)]);
const isDisabled =
appSection === AppSection.FILTER_CONFIG_MODAL && defaultToFirstItem;
const debouncedOwnStateFunc = useCallback(
debounce((val: string) => {
dispatchDataMask({
type: 'ownState',
ownState: {
coltypeMap: initialColtypeMap,
search: val,
},
});
}, SLOW_DEBOUNCE),
[],
);
const searchWrapper = (val: string) => {
if (searchAllOptions) {
debouncedOwnStateFunc(val);
}
};
const clearSuggestionSearch = () => {
if (searchAllOptions) {
dispatchDataMask({
type: 'ownState',
ownState: {
coltypeMap: initialColtypeMap,
search: null,
},
});
}
};
const handleBlur = () => {
clearSuggestionSearch();
unsetFocusedFilter();
};
const datatype: GenericDataType = coltypeMap[col];
const labelFormatter = useMemo(
() =>
getDataRecordFormatter({
timeFormatter: smartDateDetailedFormatter,
}),
[],
);
const handleChange = (value?: SelectValue | number | string) => {
const values = ensureIsArray(value);
if (values.length === 0) {
updateDataMask(null);
} else {
updateDataMask(values);
}
};
useEffect(() => {
if (defaultToFirstItem && filterState.value === undefined) {
// initialize to first value if set to default to first item
const firstItem: SelectValue = data[0]
? (groupby.map(col => data[0][col]) as string[])
: null;
// firstItem[0] !== undefined for a case when groupby changed but new data still not fetched
// TODO: still need repopulate default value in config modal when column changed
if (firstItem && firstItem[0] !== undefined) {
updateDataMask(firstItem);
}
} else if (isDisabled) {
// empty selection if filter is disabled
updateDataMask(null);
} else {
// reset data mask based on filter state
updateDataMask(filterState.value);
}
}, [
col,
isDisabled,
defaultToFirstItem,
enableEmptyFilter,
inverseSelection,
updateDataMask,
data,
groupby,
JSON.stringify(filterState),
]);
useEffect(() => {
setDataMask(dataMask);
}, [JSON.stringify(dataMask)]);
const placeholderText =
data.length === 0
? t('No data')
: tn('%s option', '%s options', data.length, data.length);
const formItemData: FormItemProps = {};
if (filterState.validateMessage) {
formItemData.extra = (
<StatusMessage status={filterState.validateStatus}>
{filterState.validateMessage}
</StatusMessage>
);
}
const options = useMemo(() => {
const options: { label: string; value: string | number }[] = [];
data.forEach(row => {
const [value] = groupby.map(col => row[col]);
options.push({
label: labelFormatter(value, datatype),
value: typeof value === 'number' ? value : String(value),
});
});
return options;
}, [data, datatype, groupby, labelFormatter]);
return (
<FilterPluginStyle height={height} width={width}>
<StyledFormItem
validateStatus={filterState.validateStatus}
{...formItemData}
>
<Select
allowClear
allowNewOptions
// @ts-ignore
value={filterState.value || []}
disabled={isDisabled}
showSearch={showSearch}
mode={multiSelect ? 'multiple' : 'single'}
placeholder={placeholderText}
onSearch={searchWrapper}
onSelect={clearSuggestionSearch}
onBlur={handleBlur}
onMouseEnter={setFocusedFilter}
onMouseLeave={unsetFocusedFilter}
// @ts-ignore
onChange={handleChange}
ref={inputRef}
loading={isRefreshing}
maxTagCount={5}
invertSelection={inverseSelection}
options={options}
/>
</StyledFormItem>
</FilterPluginStyle>
);
}
| reducer | identifier_name |
SelectFilterPlugin.tsx | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/* eslint-disable no-param-reassign */
import {
AppSection,
DataMask,
ensureIsArray,
ExtraFormData,
GenericDataType,
JsonObject,
smartDateDetailedFormatter,
t,
tn,
} from '@superset-ui/core';
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Select } from 'src/components';
import debounce from 'lodash/debounce';
import { SLOW_DEBOUNCE } from 'src/constants';
import { useImmerReducer } from 'use-immer';
import { FormItemProps } from 'antd/lib/form';
import { PluginFilterSelectProps, SelectValue } from './types';
import { StyledFormItem, FilterPluginStyle, StatusMessage } from '../common';
import { getDataRecordFormatter, getSelectExtraFormData } from '../../utils';
type DataMaskAction =
| { type: 'ownState'; ownState: JsonObject }
| {
type: 'filterState';
__cache: JsonObject;
extraFormData: ExtraFormData;
filterState: { value: SelectValue; label?: string };
};
function reducer(
draft: DataMask & { __cache?: JsonObject },
action: DataMaskAction,
) {
switch (action.type) {
case 'ownState':
draft.ownState = {
...draft.ownState,
...action.ownState,
};
return draft;
case 'filterState':
draft.extraFormData = action.extraFormData;
// eslint-disable-next-line no-underscore-dangle
draft.__cache = action.__cache;
draft.filterState = { ...draft.filterState, ...action.filterState };
return draft;
default:
return draft;
}
}
export default function PluginFilterSelect(props: PluginFilterSelectProps) {
const {
coltypeMap,
data,
filterState,
formData,
height,
isRefreshing,
width,
setDataMask,
setFocusedFilter,
unsetFocusedFilter,
appSection,
} = props;
const {
enableEmptyFilter,
multiSelect,
showSearch,
inverseSelection,
inputRef,
defaultToFirstItem,
searchAllOptions,
} = formData;
const groupby = ensureIsArray<string>(formData.groupby);
const [col] = groupby;
const [initialColtypeMap] = useState(coltypeMap);
const [dataMask, dispatchDataMask] = useImmerReducer(reducer, {
extraFormData: {},
filterState,
});
const updateDataMask = useCallback(
(values: SelectValue) => {
const emptyFilter =
enableEmptyFilter && !inverseSelection && !values?.length;
const suffix =
inverseSelection && values?.length ? ` (${t('excluded')})` : '';
dispatchDataMask({
type: 'filterState',
__cache: filterState,
extraFormData: getSelectExtraFormData(
col,
values,
emptyFilter,
inverseSelection,
),
filterState: {
...filterState,
label: values?.length
? `${(values || []).join(', ')}${suffix}`
: undefined,
value:
appSection === AppSection.FILTER_CONFIG_MODAL && defaultToFirstItem
? undefined
: values,
},
});
},
[
appSection,
col,
defaultToFirstItem,
dispatchDataMask,
enableEmptyFilter,
inverseSelection,
JSON.stringify(filterState),
],
);
useEffect(() => {
updateDataMask(filterState.value);
}, [JSON.stringify(filterState.value)]);
const isDisabled =
appSection === AppSection.FILTER_CONFIG_MODAL && defaultToFirstItem;
| debounce((val: string) => {
dispatchDataMask({
type: 'ownState',
ownState: {
coltypeMap: initialColtypeMap,
search: val,
},
});
}, SLOW_DEBOUNCE),
[],
);
const searchWrapper = (val: string) => {
if (searchAllOptions) {
debouncedOwnStateFunc(val);
}
};
const clearSuggestionSearch = () => {
if (searchAllOptions) {
dispatchDataMask({
type: 'ownState',
ownState: {
coltypeMap: initialColtypeMap,
search: null,
},
});
}
};
const handleBlur = () => {
clearSuggestionSearch();
unsetFocusedFilter();
};
const datatype: GenericDataType = coltypeMap[col];
const labelFormatter = useMemo(
() =>
getDataRecordFormatter({
timeFormatter: smartDateDetailedFormatter,
}),
[],
);
const handleChange = (value?: SelectValue | number | string) => {
const values = ensureIsArray(value);
if (values.length === 0) {
updateDataMask(null);
} else {
updateDataMask(values);
}
};
useEffect(() => {
if (defaultToFirstItem && filterState.value === undefined) {
// initialize to first value if set to default to first item
const firstItem: SelectValue = data[0]
? (groupby.map(col => data[0][col]) as string[])
: null;
// firstItem[0] !== undefined for a case when groupby changed but new data still not fetched
// TODO: still need repopulate default value in config modal when column changed
if (firstItem && firstItem[0] !== undefined) {
updateDataMask(firstItem);
}
} else if (isDisabled) {
// empty selection if filter is disabled
updateDataMask(null);
} else {
// reset data mask based on filter state
updateDataMask(filterState.value);
}
}, [
col,
isDisabled,
defaultToFirstItem,
enableEmptyFilter,
inverseSelection,
updateDataMask,
data,
groupby,
JSON.stringify(filterState),
]);
useEffect(() => {
setDataMask(dataMask);
}, [JSON.stringify(dataMask)]);
const placeholderText =
data.length === 0
? t('No data')
: tn('%s option', '%s options', data.length, data.length);
const formItemData: FormItemProps = {};
if (filterState.validateMessage) {
formItemData.extra = (
<StatusMessage status={filterState.validateStatus}>
{filterState.validateMessage}
</StatusMessage>
);
}
const options = useMemo(() => {
const options: { label: string; value: string | number }[] = [];
data.forEach(row => {
const [value] = groupby.map(col => row[col]);
options.push({
label: labelFormatter(value, datatype),
value: typeof value === 'number' ? value : String(value),
});
});
return options;
}, [data, datatype, groupby, labelFormatter]);
return (
<FilterPluginStyle height={height} width={width}>
<StyledFormItem
validateStatus={filterState.validateStatus}
{...formItemData}
>
<Select
allowClear
allowNewOptions
// @ts-ignore
value={filterState.value || []}
disabled={isDisabled}
showSearch={showSearch}
mode={multiSelect ? 'multiple' : 'single'}
placeholder={placeholderText}
onSearch={searchWrapper}
onSelect={clearSuggestionSearch}
onBlur={handleBlur}
onMouseEnter={setFocusedFilter}
onMouseLeave={unsetFocusedFilter}
// @ts-ignore
onChange={handleChange}
ref={inputRef}
loading={isRefreshing}
maxTagCount={5}
invertSelection={inverseSelection}
options={options}
/>
</StyledFormItem>
</FilterPluginStyle>
);
} | const debouncedOwnStateFunc = useCallback( | random_line_split |
SelectFilterPlugin.tsx | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/* eslint-disable no-param-reassign */
import {
AppSection,
DataMask,
ensureIsArray,
ExtraFormData,
GenericDataType,
JsonObject,
smartDateDetailedFormatter,
t,
tn,
} from '@superset-ui/core';
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Select } from 'src/components';
import debounce from 'lodash/debounce';
import { SLOW_DEBOUNCE } from 'src/constants';
import { useImmerReducer } from 'use-immer';
import { FormItemProps } from 'antd/lib/form';
import { PluginFilterSelectProps, SelectValue } from './types';
import { StyledFormItem, FilterPluginStyle, StatusMessage } from '../common';
import { getDataRecordFormatter, getSelectExtraFormData } from '../../utils';
type DataMaskAction =
| { type: 'ownState'; ownState: JsonObject }
| {
type: 'filterState';
__cache: JsonObject;
extraFormData: ExtraFormData;
filterState: { value: SelectValue; label?: string };
};
function reducer(
draft: DataMask & { __cache?: JsonObject },
action: DataMaskAction,
) {
switch (action.type) {
case 'ownState':
draft.ownState = {
...draft.ownState,
...action.ownState,
};
return draft;
case 'filterState':
draft.extraFormData = action.extraFormData;
// eslint-disable-next-line no-underscore-dangle
draft.__cache = action.__cache;
draft.filterState = { ...draft.filterState, ...action.filterState };
return draft;
default:
return draft;
}
}
export default function PluginFilterSelect(props: PluginFilterSelectProps) | {
const {
coltypeMap,
data,
filterState,
formData,
height,
isRefreshing,
width,
setDataMask,
setFocusedFilter,
unsetFocusedFilter,
appSection,
} = props;
const {
enableEmptyFilter,
multiSelect,
showSearch,
inverseSelection,
inputRef,
defaultToFirstItem,
searchAllOptions,
} = formData;
const groupby = ensureIsArray<string>(formData.groupby);
const [col] = groupby;
const [initialColtypeMap] = useState(coltypeMap);
const [dataMask, dispatchDataMask] = useImmerReducer(reducer, {
extraFormData: {},
filterState,
});
const updateDataMask = useCallback(
(values: SelectValue) => {
const emptyFilter =
enableEmptyFilter && !inverseSelection && !values?.length;
const suffix =
inverseSelection && values?.length ? ` (${t('excluded')})` : '';
dispatchDataMask({
type: 'filterState',
__cache: filterState,
extraFormData: getSelectExtraFormData(
col,
values,
emptyFilter,
inverseSelection,
),
filterState: {
...filterState,
label: values?.length
? `${(values || []).join(', ')}${suffix}`
: undefined,
value:
appSection === AppSection.FILTER_CONFIG_MODAL && defaultToFirstItem
? undefined
: values,
},
});
},
[
appSection,
col,
defaultToFirstItem,
dispatchDataMask,
enableEmptyFilter,
inverseSelection,
JSON.stringify(filterState),
],
);
useEffect(() => {
updateDataMask(filterState.value);
}, [JSON.stringify(filterState.value)]);
const isDisabled =
appSection === AppSection.FILTER_CONFIG_MODAL && defaultToFirstItem;
const debouncedOwnStateFunc = useCallback(
debounce((val: string) => {
dispatchDataMask({
type: 'ownState',
ownState: {
coltypeMap: initialColtypeMap,
search: val,
},
});
}, SLOW_DEBOUNCE),
[],
);
const searchWrapper = (val: string) => {
if (searchAllOptions) {
debouncedOwnStateFunc(val);
}
};
const clearSuggestionSearch = () => {
if (searchAllOptions) {
dispatchDataMask({
type: 'ownState',
ownState: {
coltypeMap: initialColtypeMap,
search: null,
},
});
}
};
const handleBlur = () => {
clearSuggestionSearch();
unsetFocusedFilter();
};
const datatype: GenericDataType = coltypeMap[col];
const labelFormatter = useMemo(
() =>
getDataRecordFormatter({
timeFormatter: smartDateDetailedFormatter,
}),
[],
);
const handleChange = (value?: SelectValue | number | string) => {
const values = ensureIsArray(value);
if (values.length === 0) {
updateDataMask(null);
} else {
updateDataMask(values);
}
};
useEffect(() => {
if (defaultToFirstItem && filterState.value === undefined) {
// initialize to first value if set to default to first item
const firstItem: SelectValue = data[0]
? (groupby.map(col => data[0][col]) as string[])
: null;
// firstItem[0] !== undefined for a case when groupby changed but new data still not fetched
// TODO: still need repopulate default value in config modal when column changed
if (firstItem && firstItem[0] !== undefined) {
updateDataMask(firstItem);
}
} else if (isDisabled) {
// empty selection if filter is disabled
updateDataMask(null);
} else {
// reset data mask based on filter state
updateDataMask(filterState.value);
}
}, [
col,
isDisabled,
defaultToFirstItem,
enableEmptyFilter,
inverseSelection,
updateDataMask,
data,
groupby,
JSON.stringify(filterState),
]);
useEffect(() => {
setDataMask(dataMask);
}, [JSON.stringify(dataMask)]);
const placeholderText =
data.length === 0
? t('No data')
: tn('%s option', '%s options', data.length, data.length);
const formItemData: FormItemProps = {};
if (filterState.validateMessage) {
formItemData.extra = (
<StatusMessage status={filterState.validateStatus}>
{filterState.validateMessage}
</StatusMessage>
);
}
const options = useMemo(() => {
const options: { label: string; value: string | number }[] = [];
data.forEach(row => {
const [value] = groupby.map(col => row[col]);
options.push({
label: labelFormatter(value, datatype),
value: typeof value === 'number' ? value : String(value),
});
});
return options;
}, [data, datatype, groupby, labelFormatter]);
return (
<FilterPluginStyle height={height} width={width}>
<StyledFormItem
validateStatus={filterState.validateStatus}
{...formItemData}
>
<Select
allowClear
allowNewOptions
// @ts-ignore
value={filterState.value || []}
disabled={isDisabled}
showSearch={showSearch}
mode={multiSelect ? 'multiple' : 'single'}
placeholder={placeholderText}
onSearch={searchWrapper}
onSelect={clearSuggestionSearch}
onBlur={handleBlur}
onMouseEnter={setFocusedFilter}
onMouseLeave={unsetFocusedFilter}
// @ts-ignore
onChange={handleChange}
ref={inputRef}
loading={isRefreshing}
maxTagCount={5}
invertSelection={inverseSelection}
options={options}
/>
</StyledFormItem>
</FilterPluginStyle>
);
} | identifier_body | |
OutputStream.py | # Copyright (c) 2012. Los Alamos National Security, LLC.
# This material was produced under U.S. Government contract DE-AC52-06NA25396
# for Los Alamos National Laboratory (LANL), which is operated by Los Alamos
# National Security, LLC for the U.S. Department of Energy. The U.S. Government
# has rights to use, reproduce, and distribute this software.
# NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY,
# EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.
# If software is modified to produce derivative works, such modified software should
# be clearly marked, so as not to confuse it with the version available from LANL.
# Additionally, this library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License v 2.1 as published by the
# Free Software Foundation. Accordingly, this library is distributed in the hope that
# it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt for more details.
import sys
from cStringIO import StringIO
import core
# Define output streams
class OutputStream:
def | (self):
self.output_str = StringIO()
# define output stream writer method
# sim_obj should be derived from either PyEntity or PyService
def write(self,sim_obj,record_type,*message):
for token in message:
self.output_str.write(str(token));
self.output_str.write(" ");
core.output(sim_obj,record_type,self.output_str.getvalue())
self.output_str.truncate(0)
# create output stream
output = OutputStream()
| __init__ | identifier_name |
OutputStream.py | # Copyright (c) 2012. Los Alamos National Security, LLC.
# This material was produced under U.S. Government contract DE-AC52-06NA25396
# for Los Alamos National Laboratory (LANL), which is operated by Los Alamos
# National Security, LLC for the U.S. Department of Energy. The U.S. Government
# has rights to use, reproduce, and distribute this software.
# NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY,
# EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.
# If software is modified to produce derivative works, such modified software should
# be clearly marked, so as not to confuse it with the version available from LANL.
# Additionally, this library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License v 2.1 as published by the
# Free Software Foundation. Accordingly, this library is distributed in the hope that
# it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt for more details.
import sys
from cStringIO import StringIO
import core
# Define output streams
class OutputStream:
def __init__(self):
self.output_str = StringIO()
# define output stream writer method
# sim_obj should be derived from either PyEntity or PyService
def write(self,sim_obj,record_type,*message):
for token in message:
|
core.output(sim_obj,record_type,self.output_str.getvalue())
self.output_str.truncate(0)
# create output stream
output = OutputStream()
| self.output_str.write(str(token));
self.output_str.write(" "); | conditional_block |
OutputStream.py | # Copyright (c) 2012. Los Alamos National Security, LLC.
# This material was produced under U.S. Government contract DE-AC52-06NA25396
# for Los Alamos National Laboratory (LANL), which is operated by Los Alamos
# National Security, LLC for the U.S. Department of Energy. The U.S. Government
# has rights to use, reproduce, and distribute this software.
# NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY,
# EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.
# If software is modified to produce derivative works, such modified software should
# be clearly marked, so as not to confuse it with the version available from LANL.
# Additionally, this library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License v 2.1 as published by the
# Free Software Foundation. Accordingly, this library is distributed in the hope that
# it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt for more details.
import sys
from cStringIO import StringIO
import core
# Define output streams
class OutputStream:
def __init__(self):
self.output_str = StringIO()
# define output stream writer method
# sim_obj should be derived from either PyEntity or PyService
def write(self,sim_obj,record_type,*message):
|
# create output stream
output = OutputStream()
| for token in message:
self.output_str.write(str(token));
self.output_str.write(" ");
core.output(sim_obj,record_type,self.output_str.getvalue())
self.output_str.truncate(0) | identifier_body |
OutputStream.py | # Copyright (c) 2012. Los Alamos National Security, LLC.
# This material was produced under U.S. Government contract DE-AC52-06NA25396
# for Los Alamos National Laboratory (LANL), which is operated by Los Alamos
# National Security, LLC for the U.S. Department of Energy. The U.S. Government
# has rights to use, reproduce, and distribute this software.
# NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY,
# EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.
# If software is modified to produce derivative works, such modified software should
# be clearly marked, so as not to confuse it with the version available from LANL.
# Additionally, this library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License v 2.1 as published by the
# Free Software Foundation. Accordingly, this library is distributed in the hope that
# it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt for more details.
import sys
from cStringIO import StringIO
import core
# Define output streams
class OutputStream:
def __init__(self):
self.output_str = StringIO()
# define output stream writer method
# sim_obj should be derived from either PyEntity or PyService
def write(self,sim_obj,record_type,*message):
for token in message:
self.output_str.write(str(token));
self.output_str.write(" ");
core.output(sim_obj,record_type,self.output_str.getvalue())
self.output_str.truncate(0)
| # create output stream
output = OutputStream() | random_line_split | |
NodeList-manipulate.js | /*
Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojo.NodeList-manipulate"]){
dojo._hasResource["dojo.NodeList-manipulate"]=true;
dojo.provide("dojo.NodeList-manipulate");
(function(){
function _1(_2){
var _3="",ch=_2.childNodes;
for(var i=0,n;n=ch[i];i++){
if(n.nodeType!=8){
if(n.nodeType==1){
_3+=_1(n);
}else{
_3+=n.nodeValue;
}
}
}
return _3;
};
function _4(_5){
while(_5.childNodes[0]&&_5.childNodes[0].nodeType==1){
_5=_5.childNodes[0];
}
return _5;
};
function _6(_7,_8){
if(typeof _7=="string"){
_7=dojo._toDom(_7,(_8&&_8.ownerDocument));
if(_7.nodeType==11){
_7=_7.childNodes[0];
}
}else{
if(_7.nodeType==1&&_7.parentNode){
_7=_7.cloneNode(false);
}
}
return _7;
};
dojo.extend(dojo.NodeList,{_placeMultiple:function(_9,_a){
var _b=typeof _9=="string"||_9.nodeType?dojo.query(_9):_9;
var _c=[]; | var _e=this.length;
for(var j=_e-1,_f;_f=this[j];j--){
if(i>0){
_f=this._cloneNode(_f);
_c.unshift(_f);
}
if(j==_e-1){
dojo.place(_f,_d,_a);
}else{
_d.parentNode.insertBefore(_f,_d);
}
_d=_f;
}
}
if(_c.length){
_c.unshift(0);
_c.unshift(this.length-1);
Array.prototype.splice.apply(this,_c);
}
return this;
},innerHTML:function(_10){
if(arguments.length){
return this.addContent(_10,"only");
}else{
return this[0].innerHTML;
}
},text:function(_11){
if(arguments.length){
for(var i=0,_12;_12=this[i];i++){
if(_12.nodeType==1){
dojo.empty(_12);
_12.appendChild(_12.ownerDocument.createTextNode(_11));
}
}
return this;
}else{
var _13="";
for(i=0;_12=this[i];i++){
_13+=_1(_12);
}
return _13;
}
},val:function(_14){
if(arguments.length){
var _15=dojo.isArray(_14);
for(var _16=0,_17;_17=this[_16];_16++){
var _18=_17.nodeName.toUpperCase();
var _19=_17.type;
var _1a=_15?_14[_16]:_14;
if(_18=="SELECT"){
var _1b=_17.options;
for(var i=0;i<_1b.length;i++){
var opt=_1b[i];
if(_17.multiple){
opt.selected=(dojo.indexOf(_14,opt.value)!=-1);
}else{
opt.selected=(opt.value==_1a);
}
}
}else{
if(_19=="checkbox"||_19=="radio"){
_17.checked=(_17.value==_1a);
}else{
_17.value=_1a;
}
}
}
return this;
}else{
_17=this[0];
if(!_17||_17.nodeType!=1){
return undefined;
}
_14=_17.value||"";
if(_17.nodeName.toUpperCase()=="SELECT"&&_17.multiple){
_14=[];
_1b=_17.options;
for(i=0;i<_1b.length;i++){
opt=_1b[i];
if(opt.selected){
_14.push(opt.value);
}
}
if(!_14.length){
_14=null;
}
}
return _14;
}
},append:function(_1c){
return this.addContent(_1c,"last");
},appendTo:function(_1d){
return this._placeMultiple(_1d,"last");
},prepend:function(_1e){
return this.addContent(_1e,"first");
},prependTo:function(_1f){
return this._placeMultiple(_1f,"first");
},after:function(_20){
return this.addContent(_20,"after");
},insertAfter:function(_21){
return this._placeMultiple(_21,"after");
},before:function(_22){
return this.addContent(_22,"before");
},insertBefore:function(_23){
return this._placeMultiple(_23,"before");
},remove:dojo.NodeList.prototype.orphan,wrap:function(_24){
if(this[0]){
_24=_6(_24,this[0]);
for(var i=0,_25;_25=this[i];i++){
var _26=this._cloneNode(_24);
if(_25.parentNode){
_25.parentNode.replaceChild(_26,_25);
}
var _27=_4(_26);
_27.appendChild(_25);
}
}
return this;
},wrapAll:function(_28){
if(this[0]){
_28=_6(_28,this[0]);
this[0].parentNode.replaceChild(_28,this[0]);
var _29=_4(_28);
for(var i=0,_2a;_2a=this[i];i++){
_29.appendChild(_2a);
}
}
return this;
},wrapInner:function(_2b){
if(this[0]){
_2b=_6(_2b,this[0]);
for(var i=0;i<this.length;i++){
var _2c=this._cloneNode(_2b);
this._wrap(dojo._toArray(this[i].childNodes),null,this._NodeListCtor).wrapAll(_2c);
}
}
return this;
},replaceWith:function(_2d){
_2d=this._normalize(_2d,this[0]);
for(var i=0,_2e;_2e=this[i];i++){
this._place(_2d,_2e,"before",i>0);
_2e.parentNode.removeChild(_2e);
}
return this;
},replaceAll:function(_2f){
var nl=dojo.query(_2f);
var _30=this._normalize(this,this[0]);
for(var i=0,_31;_31=nl[i];i++){
this._place(_30,_31,"before",i>0);
_31.parentNode.removeChild(_31);
}
return this;
},clone:function(){
var ary=[];
for(var i=0;i<this.length;i++){
ary.push(this._cloneNode(this[i]));
}
return this._wrap(ary,this,this._NodeListCtor);
}});
if(!dojo.NodeList.prototype.html){
dojo.NodeList.prototype.html=dojo.NodeList.prototype.innerHTML;
}
})();
} | for(var i=0;i<_b.length;i++){
var _d=_b[i]; | random_line_split |
NodeList-manipulate.js | /*
Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojo.NodeList-manipulate"]){
dojo._hasResource["dojo.NodeList-manipulate"]=true;
dojo.provide("dojo.NodeList-manipulate");
(function(){
function | (_2){
var _3="",ch=_2.childNodes;
for(var i=0,n;n=ch[i];i++){
if(n.nodeType!=8){
if(n.nodeType==1){
_3+=_1(n);
}else{
_3+=n.nodeValue;
}
}
}
return _3;
};
function _4(_5){
while(_5.childNodes[0]&&_5.childNodes[0].nodeType==1){
_5=_5.childNodes[0];
}
return _5;
};
function _6(_7,_8){
if(typeof _7=="string"){
_7=dojo._toDom(_7,(_8&&_8.ownerDocument));
if(_7.nodeType==11){
_7=_7.childNodes[0];
}
}else{
if(_7.nodeType==1&&_7.parentNode){
_7=_7.cloneNode(false);
}
}
return _7;
};
dojo.extend(dojo.NodeList,{_placeMultiple:function(_9,_a){
var _b=typeof _9=="string"||_9.nodeType?dojo.query(_9):_9;
var _c=[];
for(var i=0;i<_b.length;i++){
var _d=_b[i];
var _e=this.length;
for(var j=_e-1,_f;_f=this[j];j--){
if(i>0){
_f=this._cloneNode(_f);
_c.unshift(_f);
}
if(j==_e-1){
dojo.place(_f,_d,_a);
}else{
_d.parentNode.insertBefore(_f,_d);
}
_d=_f;
}
}
if(_c.length){
_c.unshift(0);
_c.unshift(this.length-1);
Array.prototype.splice.apply(this,_c);
}
return this;
},innerHTML:function(_10){
if(arguments.length){
return this.addContent(_10,"only");
}else{
return this[0].innerHTML;
}
},text:function(_11){
if(arguments.length){
for(var i=0,_12;_12=this[i];i++){
if(_12.nodeType==1){
dojo.empty(_12);
_12.appendChild(_12.ownerDocument.createTextNode(_11));
}
}
return this;
}else{
var _13="";
for(i=0;_12=this[i];i++){
_13+=_1(_12);
}
return _13;
}
},val:function(_14){
if(arguments.length){
var _15=dojo.isArray(_14);
for(var _16=0,_17;_17=this[_16];_16++){
var _18=_17.nodeName.toUpperCase();
var _19=_17.type;
var _1a=_15?_14[_16]:_14;
if(_18=="SELECT"){
var _1b=_17.options;
for(var i=0;i<_1b.length;i++){
var opt=_1b[i];
if(_17.multiple){
opt.selected=(dojo.indexOf(_14,opt.value)!=-1);
}else{
opt.selected=(opt.value==_1a);
}
}
}else{
if(_19=="checkbox"||_19=="radio"){
_17.checked=(_17.value==_1a);
}else{
_17.value=_1a;
}
}
}
return this;
}else{
_17=this[0];
if(!_17||_17.nodeType!=1){
return undefined;
}
_14=_17.value||"";
if(_17.nodeName.toUpperCase()=="SELECT"&&_17.multiple){
_14=[];
_1b=_17.options;
for(i=0;i<_1b.length;i++){
opt=_1b[i];
if(opt.selected){
_14.push(opt.value);
}
}
if(!_14.length){
_14=null;
}
}
return _14;
}
},append:function(_1c){
return this.addContent(_1c,"last");
},appendTo:function(_1d){
return this._placeMultiple(_1d,"last");
},prepend:function(_1e){
return this.addContent(_1e,"first");
},prependTo:function(_1f){
return this._placeMultiple(_1f,"first");
},after:function(_20){
return this.addContent(_20,"after");
},insertAfter:function(_21){
return this._placeMultiple(_21,"after");
},before:function(_22){
return this.addContent(_22,"before");
},insertBefore:function(_23){
return this._placeMultiple(_23,"before");
},remove:dojo.NodeList.prototype.orphan,wrap:function(_24){
if(this[0]){
_24=_6(_24,this[0]);
for(var i=0,_25;_25=this[i];i++){
var _26=this._cloneNode(_24);
if(_25.parentNode){
_25.parentNode.replaceChild(_26,_25);
}
var _27=_4(_26);
_27.appendChild(_25);
}
}
return this;
},wrapAll:function(_28){
if(this[0]){
_28=_6(_28,this[0]);
this[0].parentNode.replaceChild(_28,this[0]);
var _29=_4(_28);
for(var i=0,_2a;_2a=this[i];i++){
_29.appendChild(_2a);
}
}
return this;
},wrapInner:function(_2b){
if(this[0]){
_2b=_6(_2b,this[0]);
for(var i=0;i<this.length;i++){
var _2c=this._cloneNode(_2b);
this._wrap(dojo._toArray(this[i].childNodes),null,this._NodeListCtor).wrapAll(_2c);
}
}
return this;
},replaceWith:function(_2d){
_2d=this._normalize(_2d,this[0]);
for(var i=0,_2e;_2e=this[i];i++){
this._place(_2d,_2e,"before",i>0);
_2e.parentNode.removeChild(_2e);
}
return this;
},replaceAll:function(_2f){
var nl=dojo.query(_2f);
var _30=this._normalize(this,this[0]);
for(var i=0,_31;_31=nl[i];i++){
this._place(_30,_31,"before",i>0);
_31.parentNode.removeChild(_31);
}
return this;
},clone:function(){
var ary=[];
for(var i=0;i<this.length;i++){
ary.push(this._cloneNode(this[i]));
}
return this._wrap(ary,this,this._NodeListCtor);
}});
if(!dojo.NodeList.prototype.html){
dojo.NodeList.prototype.html=dojo.NodeList.prototype.innerHTML;
}
})();
}
| _1 | identifier_name |
NodeList-manipulate.js | /*
Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojo.NodeList-manipulate"]){
dojo._hasResource["dojo.NodeList-manipulate"]=true;
dojo.provide("dojo.NodeList-manipulate");
(function(){
function _1(_2){
var _3="",ch=_2.childNodes;
for(var i=0,n;n=ch[i];i++){
if(n.nodeType!=8){
if(n.nodeType==1){
_3+=_1(n);
}else{
_3+=n.nodeValue;
}
}
}
return _3;
};
function _4(_5){
while(_5.childNodes[0]&&_5.childNodes[0].nodeType==1){
_5=_5.childNodes[0];
}
return _5;
};
function _6(_7,_8) | ;
dojo.extend(dojo.NodeList,{_placeMultiple:function(_9,_a){
var _b=typeof _9=="string"||_9.nodeType?dojo.query(_9):_9;
var _c=[];
for(var i=0;i<_b.length;i++){
var _d=_b[i];
var _e=this.length;
for(var j=_e-1,_f;_f=this[j];j--){
if(i>0){
_f=this._cloneNode(_f);
_c.unshift(_f);
}
if(j==_e-1){
dojo.place(_f,_d,_a);
}else{
_d.parentNode.insertBefore(_f,_d);
}
_d=_f;
}
}
if(_c.length){
_c.unshift(0);
_c.unshift(this.length-1);
Array.prototype.splice.apply(this,_c);
}
return this;
},innerHTML:function(_10){
if(arguments.length){
return this.addContent(_10,"only");
}else{
return this[0].innerHTML;
}
},text:function(_11){
if(arguments.length){
for(var i=0,_12;_12=this[i];i++){
if(_12.nodeType==1){
dojo.empty(_12);
_12.appendChild(_12.ownerDocument.createTextNode(_11));
}
}
return this;
}else{
var _13="";
for(i=0;_12=this[i];i++){
_13+=_1(_12);
}
return _13;
}
},val:function(_14){
if(arguments.length){
var _15=dojo.isArray(_14);
for(var _16=0,_17;_17=this[_16];_16++){
var _18=_17.nodeName.toUpperCase();
var _19=_17.type;
var _1a=_15?_14[_16]:_14;
if(_18=="SELECT"){
var _1b=_17.options;
for(var i=0;i<_1b.length;i++){
var opt=_1b[i];
if(_17.multiple){
opt.selected=(dojo.indexOf(_14,opt.value)!=-1);
}else{
opt.selected=(opt.value==_1a);
}
}
}else{
if(_19=="checkbox"||_19=="radio"){
_17.checked=(_17.value==_1a);
}else{
_17.value=_1a;
}
}
}
return this;
}else{
_17=this[0];
if(!_17||_17.nodeType!=1){
return undefined;
}
_14=_17.value||"";
if(_17.nodeName.toUpperCase()=="SELECT"&&_17.multiple){
_14=[];
_1b=_17.options;
for(i=0;i<_1b.length;i++){
opt=_1b[i];
if(opt.selected){
_14.push(opt.value);
}
}
if(!_14.length){
_14=null;
}
}
return _14;
}
},append:function(_1c){
return this.addContent(_1c,"last");
},appendTo:function(_1d){
return this._placeMultiple(_1d,"last");
},prepend:function(_1e){
return this.addContent(_1e,"first");
},prependTo:function(_1f){
return this._placeMultiple(_1f,"first");
},after:function(_20){
return this.addContent(_20,"after");
},insertAfter:function(_21){
return this._placeMultiple(_21,"after");
},before:function(_22){
return this.addContent(_22,"before");
},insertBefore:function(_23){
return this._placeMultiple(_23,"before");
},remove:dojo.NodeList.prototype.orphan,wrap:function(_24){
if(this[0]){
_24=_6(_24,this[0]);
for(var i=0,_25;_25=this[i];i++){
var _26=this._cloneNode(_24);
if(_25.parentNode){
_25.parentNode.replaceChild(_26,_25);
}
var _27=_4(_26);
_27.appendChild(_25);
}
}
return this;
},wrapAll:function(_28){
if(this[0]){
_28=_6(_28,this[0]);
this[0].parentNode.replaceChild(_28,this[0]);
var _29=_4(_28);
for(var i=0,_2a;_2a=this[i];i++){
_29.appendChild(_2a);
}
}
return this;
},wrapInner:function(_2b){
if(this[0]){
_2b=_6(_2b,this[0]);
for(var i=0;i<this.length;i++){
var _2c=this._cloneNode(_2b);
this._wrap(dojo._toArray(this[i].childNodes),null,this._NodeListCtor).wrapAll(_2c);
}
}
return this;
},replaceWith:function(_2d){
_2d=this._normalize(_2d,this[0]);
for(var i=0,_2e;_2e=this[i];i++){
this._place(_2d,_2e,"before",i>0);
_2e.parentNode.removeChild(_2e);
}
return this;
},replaceAll:function(_2f){
var nl=dojo.query(_2f);
var _30=this._normalize(this,this[0]);
for(var i=0,_31;_31=nl[i];i++){
this._place(_30,_31,"before",i>0);
_31.parentNode.removeChild(_31);
}
return this;
},clone:function(){
var ary=[];
for(var i=0;i<this.length;i++){
ary.push(this._cloneNode(this[i]));
}
return this._wrap(ary,this,this._NodeListCtor);
}});
if(!dojo.NodeList.prototype.html){
dojo.NodeList.prototype.html=dojo.NodeList.prototype.innerHTML;
}
})();
}
| {
if(typeof _7=="string"){
_7=dojo._toDom(_7,(_8&&_8.ownerDocument));
if(_7.nodeType==11){
_7=_7.childNodes[0];
}
}else{
if(_7.nodeType==1&&_7.parentNode){
_7=_7.cloneNode(false);
}
}
return _7;
} | identifier_body |
NodeList-manipulate.js | /*
Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojo.NodeList-manipulate"]){
dojo._hasResource["dojo.NodeList-manipulate"]=true;
dojo.provide("dojo.NodeList-manipulate");
(function(){
function _1(_2){
var _3="",ch=_2.childNodes;
for(var i=0,n;n=ch[i];i++){
if(n.nodeType!=8){
if(n.nodeType==1){
_3+=_1(n);
}else{
_3+=n.nodeValue;
}
}
}
return _3;
};
function _4(_5){
while(_5.childNodes[0]&&_5.childNodes[0].nodeType==1){
_5=_5.childNodes[0];
}
return _5;
};
function _6(_7,_8){
if(typeof _7=="string"){
_7=dojo._toDom(_7,(_8&&_8.ownerDocument));
if(_7.nodeType==11){
_7=_7.childNodes[0];
}
}else{
if(_7.nodeType==1&&_7.parentNode){
_7=_7.cloneNode(false);
}
}
return _7;
};
dojo.extend(dojo.NodeList,{_placeMultiple:function(_9,_a){
var _b=typeof _9=="string"||_9.nodeType?dojo.query(_9):_9;
var _c=[];
for(var i=0;i<_b.length;i++){
var _d=_b[i];
var _e=this.length;
for(var j=_e-1,_f;_f=this[j];j--){
if(i>0){
_f=this._cloneNode(_f);
_c.unshift(_f);
}
if(j==_e-1){
dojo.place(_f,_d,_a);
}else{
_d.parentNode.insertBefore(_f,_d);
}
_d=_f;
}
}
if(_c.length){
_c.unshift(0);
_c.unshift(this.length-1);
Array.prototype.splice.apply(this,_c);
}
return this;
},innerHTML:function(_10){
if(arguments.length){
return this.addContent(_10,"only");
}else{
return this[0].innerHTML;
}
},text:function(_11){
if(arguments.length){
for(var i=0,_12;_12=this[i];i++){
if(_12.nodeType==1){
dojo.empty(_12);
_12.appendChild(_12.ownerDocument.createTextNode(_11));
}
}
return this;
}else{
var _13="";
for(i=0;_12=this[i];i++){
_13+=_1(_12);
}
return _13;
}
},val:function(_14){
if(arguments.length){
var _15=dojo.isArray(_14);
for(var _16=0,_17;_17=this[_16];_16++){
var _18=_17.nodeName.toUpperCase();
var _19=_17.type;
var _1a=_15?_14[_16]:_14;
if(_18=="SELECT"){
var _1b=_17.options;
for(var i=0;i<_1b.length;i++){
var opt=_1b[i];
if(_17.multiple){
opt.selected=(dojo.indexOf(_14,opt.value)!=-1);
}else{
opt.selected=(opt.value==_1a);
}
}
}else{
if(_19=="checkbox"||_19=="radio"){
_17.checked=(_17.value==_1a);
}else{
_17.value=_1a;
}
}
}
return this;
}else{
_17=this[0];
if(!_17||_17.nodeType!=1) |
_14=_17.value||"";
if(_17.nodeName.toUpperCase()=="SELECT"&&_17.multiple){
_14=[];
_1b=_17.options;
for(i=0;i<_1b.length;i++){
opt=_1b[i];
if(opt.selected){
_14.push(opt.value);
}
}
if(!_14.length){
_14=null;
}
}
return _14;
}
},append:function(_1c){
return this.addContent(_1c,"last");
},appendTo:function(_1d){
return this._placeMultiple(_1d,"last");
},prepend:function(_1e){
return this.addContent(_1e,"first");
},prependTo:function(_1f){
return this._placeMultiple(_1f,"first");
},after:function(_20){
return this.addContent(_20,"after");
},insertAfter:function(_21){
return this._placeMultiple(_21,"after");
},before:function(_22){
return this.addContent(_22,"before");
},insertBefore:function(_23){
return this._placeMultiple(_23,"before");
},remove:dojo.NodeList.prototype.orphan,wrap:function(_24){
if(this[0]){
_24=_6(_24,this[0]);
for(var i=0,_25;_25=this[i];i++){
var _26=this._cloneNode(_24);
if(_25.parentNode){
_25.parentNode.replaceChild(_26,_25);
}
var _27=_4(_26);
_27.appendChild(_25);
}
}
return this;
},wrapAll:function(_28){
if(this[0]){
_28=_6(_28,this[0]);
this[0].parentNode.replaceChild(_28,this[0]);
var _29=_4(_28);
for(var i=0,_2a;_2a=this[i];i++){
_29.appendChild(_2a);
}
}
return this;
},wrapInner:function(_2b){
if(this[0]){
_2b=_6(_2b,this[0]);
for(var i=0;i<this.length;i++){
var _2c=this._cloneNode(_2b);
this._wrap(dojo._toArray(this[i].childNodes),null,this._NodeListCtor).wrapAll(_2c);
}
}
return this;
},replaceWith:function(_2d){
_2d=this._normalize(_2d,this[0]);
for(var i=0,_2e;_2e=this[i];i++){
this._place(_2d,_2e,"before",i>0);
_2e.parentNode.removeChild(_2e);
}
return this;
},replaceAll:function(_2f){
var nl=dojo.query(_2f);
var _30=this._normalize(this,this[0]);
for(var i=0,_31;_31=nl[i];i++){
this._place(_30,_31,"before",i>0);
_31.parentNode.removeChild(_31);
}
return this;
},clone:function(){
var ary=[];
for(var i=0;i<this.length;i++){
ary.push(this._cloneNode(this[i]));
}
return this._wrap(ary,this,this._NodeListCtor);
}});
if(!dojo.NodeList.prototype.html){
dojo.NodeList.prototype.html=dojo.NodeList.prototype.innerHTML;
}
})();
}
| {
return undefined;
} | conditional_block |
main.browser.ts | /*
* Providers provided by Angular
*/
import {bootstrap} from 'angular2/platform/browser';
/*
* App Component
* our top level component that holds all of our components
*/
import {DIRECTIVES, PIPES, PROVIDERS} from './platform/browser';
import {ENV_PROVIDERS} from './platform/environment';
import {provideStore} from '@ngrx/store';
import {App} from './app';
import {MDL} from './app';
import {counter} from './app/counter/reducer';
/*
* Bootstrap our Angular app with a top level component `App` and inject
* our Services and Providers into Angular's dependency injection
*/
export function main() {
return bootstrap(App, [
...ENV_PROVIDERS,
...PROVIDERS,
...DIRECTIVES,
...PIPES,
...provideStore({counter}),
...[MDL]
])
.catch(err => console.error(err));
}
/*
* Vendors
* For vendors for example jQuery, Lodash, angular2-jwt just import them anywhere in your app
* You can also import them in vendors to ensure that they are bundled in one file
* Also see custom-typings.d.ts as you also need to do `typings install x` where `x` is your module
*/ | */
function bootstrapDomReady() {
// bootstrap after document is ready
return document.addEventListener('DOMContentLoaded', main);
}
if ('development' === ENV) {
// activate hot module reload
if (HMR) {
if (document.readyState === 'complete') {
main();
} else {
bootstrapDomReady();
}
module.hot.accept();
} else {
bootstrapDomReady();
}
} else {
bootstrapDomReady();
} |
/*
* Hot Module Reload
* experimental version by @gdi2290 | random_line_split |
main.browser.ts | /*
* Providers provided by Angular
*/
import {bootstrap} from 'angular2/platform/browser';
/*
* App Component
* our top level component that holds all of our components
*/
import {DIRECTIVES, PIPES, PROVIDERS} from './platform/browser';
import {ENV_PROVIDERS} from './platform/environment';
import {provideStore} from '@ngrx/store';
import {App} from './app';
import {MDL} from './app';
import {counter} from './app/counter/reducer';
/*
* Bootstrap our Angular app with a top level component `App` and inject
* our Services and Providers into Angular's dependency injection
*/
export function | () {
return bootstrap(App, [
...ENV_PROVIDERS,
...PROVIDERS,
...DIRECTIVES,
...PIPES,
...provideStore({counter}),
...[MDL]
])
.catch(err => console.error(err));
}
/*
* Vendors
* For vendors for example jQuery, Lodash, angular2-jwt just import them anywhere in your app
* You can also import them in vendors to ensure that they are bundled in one file
* Also see custom-typings.d.ts as you also need to do `typings install x` where `x` is your module
*/
/*
* Hot Module Reload
* experimental version by @gdi2290
*/
function bootstrapDomReady() {
// bootstrap after document is ready
return document.addEventListener('DOMContentLoaded', main);
}
if ('development' === ENV) {
// activate hot module reload
if (HMR) {
if (document.readyState === 'complete') {
main();
} else {
bootstrapDomReady();
}
module.hot.accept();
} else {
bootstrapDomReady();
}
} else {
bootstrapDomReady();
}
| main | identifier_name |
main.browser.ts | /*
* Providers provided by Angular
*/
import {bootstrap} from 'angular2/platform/browser';
/*
* App Component
* our top level component that holds all of our components
*/
import {DIRECTIVES, PIPES, PROVIDERS} from './platform/browser';
import {ENV_PROVIDERS} from './platform/environment';
import {provideStore} from '@ngrx/store';
import {App} from './app';
import {MDL} from './app';
import {counter} from './app/counter/reducer';
/*
* Bootstrap our Angular app with a top level component `App` and inject
* our Services and Providers into Angular's dependency injection
*/
export function main() {
return bootstrap(App, [
...ENV_PROVIDERS,
...PROVIDERS,
...DIRECTIVES,
...PIPES,
...provideStore({counter}),
...[MDL]
])
.catch(err => console.error(err));
}
/*
* Vendors
* For vendors for example jQuery, Lodash, angular2-jwt just import them anywhere in your app
* You can also import them in vendors to ensure that they are bundled in one file
* Also see custom-typings.d.ts as you also need to do `typings install x` where `x` is your module
*/
/*
* Hot Module Reload
* experimental version by @gdi2290
*/
function bootstrapDomReady() {
// bootstrap after document is ready
return document.addEventListener('DOMContentLoaded', main);
}
if ('development' === ENV) {
// activate hot module reload
if (HMR) | else {
bootstrapDomReady();
}
} else {
bootstrapDomReady();
}
| {
if (document.readyState === 'complete') {
main();
} else {
bootstrapDomReady();
}
module.hot.accept();
} | conditional_block |
main.browser.ts | /*
* Providers provided by Angular
*/
import {bootstrap} from 'angular2/platform/browser';
/*
* App Component
* our top level component that holds all of our components
*/
import {DIRECTIVES, PIPES, PROVIDERS} from './platform/browser';
import {ENV_PROVIDERS} from './platform/environment';
import {provideStore} from '@ngrx/store';
import {App} from './app';
import {MDL} from './app';
import {counter} from './app/counter/reducer';
/*
* Bootstrap our Angular app with a top level component `App` and inject
* our Services and Providers into Angular's dependency injection
*/
export function main() {
return bootstrap(App, [
...ENV_PROVIDERS,
...PROVIDERS,
...DIRECTIVES,
...PIPES,
...provideStore({counter}),
...[MDL]
])
.catch(err => console.error(err));
}
/*
* Vendors
* For vendors for example jQuery, Lodash, angular2-jwt just import them anywhere in your app
* You can also import them in vendors to ensure that they are bundled in one file
* Also see custom-typings.d.ts as you also need to do `typings install x` where `x` is your module
*/
/*
* Hot Module Reload
* experimental version by @gdi2290
*/
function bootstrapDomReady() |
if ('development' === ENV) {
// activate hot module reload
if (HMR) {
if (document.readyState === 'complete') {
main();
} else {
bootstrapDomReady();
}
module.hot.accept();
} else {
bootstrapDomReady();
}
} else {
bootstrapDomReady();
}
| {
// bootstrap after document is ready
return document.addEventListener('DOMContentLoaded', main);
} | identifier_body |
parser.py | #!/usr/bin/env python3
# This file is a part of Templ
# Copyright (C) 2012 Zachary Dziura
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import yaml
| import htmltag
class Parser:
"""Parses .tmpl file to be outputted as an html file. """
def __init__(self, config_file = 'templ.conf'):
self.config_file = config_file
self.tree = None
self.rules = {}
self._load_config()
def _load_config(self):
"""Loads the configuration settings from the config_file."""
with open(self.config_file, 'r') as config:
self.rules = yaml.load(config)
def parse(self, pray_file):
"""Parse the input file and output a syntax tree.
Parameters:
pray_file - The name of the pray file to be parsed.
"""
# Begin parsing the file
with open(pray_file, 'r') as input_file:
syntax_tree = Tree()
lines = []
# Read the entire file as a list of lines
for line in input_file:
line = line.strip('\n')
# First, expand any variables found in the line
regex = re.compile(r'\$\w+')
matches = regex.findall(line)
if len(matches) > 0:
for match in matches:
replace = match.strip('$')
line = line.replace(match, self.rules[replace])
print(line)
class NodeNotFoundError(Exception):
"""Error to be thrown when node is not found in tree."""
def __init__(self, name):
self.name = name
def __str__(self):
return repr(self.name)
class Tree:
"""A parser syntax tree.
The syntax tree is nothing more than an encapsulated dictionary. When
adding nodes to the tree, the node's name parameter is used as the tree's
key, while the node's dictionary of elements are used as the saved value.
"""
def __init__(self):
self.root_node = None
def add_node(self, node):
"""Add a node to the tree.
Parameters:
Node - The node to be added to the tree.
Returns:
Void
"""
self.nodes[node.name] = node.elements
def remove_node(self, node_name):
"""Remove the first node of a given name from the tree.
If the node does not exist in the tree, return a NodeNotFoundError.
Parameters:
Node_Name - The name of the node to be removed from the tree.
Returns:
Void
"""
if node_name in self.nodes:
del self.nodes[node.name]
else:
raise NodeNotFoundError(node_name)
def remove_nodes(self, node_name):
"""Remove all nodes of a given name from the tree.
If no nodes exist in the tree, return a NodeNotFoundError.
Parameters:
Node_Name - The name of the notes to be removed from the tree.
"""
class Node:
"""Element found within parser syntax tree.
Nodes encapsulate 3 values: a name, a list of containing elements, and a
list of child elements.
"""
def __init__(self, name, attributes = {}, children = []):
self.name = name
self.attributes = attributes
self.children = children | random_line_split | |
parser.py | #!/usr/bin/env python3
# This file is a part of Templ
# Copyright (C) 2012 Zachary Dziura
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import yaml
import htmltag
class Parser:
"""Parses .tmpl file to be outputted as an html file. """
def __init__(self, config_file = 'templ.conf'):
self.config_file = config_file
self.tree = None
self.rules = {}
self._load_config()
def _load_config(self):
"""Loads the configuration settings from the config_file."""
with open(self.config_file, 'r') as config:
self.rules = yaml.load(config)
def parse(self, pray_file):
"""Parse the input file and output a syntax tree.
Parameters:
pray_file - The name of the pray file to be parsed.
"""
# Begin parsing the file
with open(pray_file, 'r') as input_file:
syntax_tree = Tree()
lines = []
# Read the entire file as a list of lines
for line in input_file:
line = line.strip('\n')
# First, expand any variables found in the line
regex = re.compile(r'\$\w+')
matches = regex.findall(line)
if len(matches) > 0:
for match in matches:
replace = match.strip('$')
line = line.replace(match, self.rules[replace])
print(line)
class NodeNotFoundError(Exception):
"""Error to be thrown when node is not found in tree."""
def __init__(self, name):
self.name = name
def __str__(self):
return repr(self.name)
class Tree:
"""A parser syntax tree.
The syntax tree is nothing more than an encapsulated dictionary. When
adding nodes to the tree, the node's name parameter is used as the tree's
key, while the node's dictionary of elements are used as the saved value.
"""
def __init__(self):
self.root_node = None
def add_node(self, node):
"""Add a node to the tree.
Parameters:
Node - The node to be added to the tree.
Returns:
Void
"""
self.nodes[node.name] = node.elements
def remove_node(self, node_name):
"""Remove the first node of a given name from the tree.
If the node does not exist in the tree, return a NodeNotFoundError.
Parameters:
Node_Name - The name of the node to be removed from the tree.
Returns:
Void
"""
if node_name in self.nodes:
del self.nodes[node.name]
else:
raise NodeNotFoundError(node_name)
def remove_nodes(self, node_name):
"""Remove all nodes of a given name from the tree.
If no nodes exist in the tree, return a NodeNotFoundError.
Parameters:
Node_Name - The name of the notes to be removed from the tree.
"""
class Node:
"""Element found within parser syntax tree.
Nodes encapsulate 3 values: a name, a list of containing elements, and a
list of child elements.
"""
def | (self, name, attributes = {}, children = []):
self.name = name
self.attributes = attributes
self.children = children
| __init__ | identifier_name |
parser.py | #!/usr/bin/env python3
# This file is a part of Templ
# Copyright (C) 2012 Zachary Dziura
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import yaml
import htmltag
class Parser:
"""Parses .tmpl file to be outputted as an html file. """
def __init__(self, config_file = 'templ.conf'):
self.config_file = config_file
self.tree = None
self.rules = {}
self._load_config()
def _load_config(self):
"""Loads the configuration settings from the config_file."""
with open(self.config_file, 'r') as config:
self.rules = yaml.load(config)
def parse(self, pray_file):
"""Parse the input file and output a syntax tree.
Parameters:
pray_file - The name of the pray file to be parsed.
"""
# Begin parsing the file
with open(pray_file, 'r') as input_file:
syntax_tree = Tree()
lines = []
# Read the entire file as a list of lines
for line in input_file:
line = line.strip('\n')
# First, expand any variables found in the line
regex = re.compile(r'\$\w+')
matches = regex.findall(line)
if len(matches) > 0:
for match in matches:
replace = match.strip('$')
line = line.replace(match, self.rules[replace])
print(line)
class NodeNotFoundError(Exception):
"""Error to be thrown when node is not found in tree."""
def __init__(self, name):
self.name = name
def __str__(self):
return repr(self.name)
class Tree:
"""A parser syntax tree.
The syntax tree is nothing more than an encapsulated dictionary. When
adding nodes to the tree, the node's name parameter is used as the tree's
key, while the node's dictionary of elements are used as the saved value.
"""
def __init__(self):
self.root_node = None
def add_node(self, node):
"""Add a node to the tree.
Parameters:
Node - The node to be added to the tree.
Returns:
Void
"""
self.nodes[node.name] = node.elements
def remove_node(self, node_name):
"""Remove the first node of a given name from the tree.
If the node does not exist in the tree, return a NodeNotFoundError.
Parameters:
Node_Name - The name of the node to be removed from the tree.
Returns:
Void
"""
if node_name in self.nodes:
|
else:
raise NodeNotFoundError(node_name)
def remove_nodes(self, node_name):
"""Remove all nodes of a given name from the tree.
If no nodes exist in the tree, return a NodeNotFoundError.
Parameters:
Node_Name - The name of the notes to be removed from the tree.
"""
class Node:
"""Element found within parser syntax tree.
Nodes encapsulate 3 values: a name, a list of containing elements, and a
list of child elements.
"""
def __init__(self, name, attributes = {}, children = []):
self.name = name
self.attributes = attributes
self.children = children
| del self.nodes[node.name] | conditional_block |
parser.py | #!/usr/bin/env python3
# This file is a part of Templ
# Copyright (C) 2012 Zachary Dziura
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import yaml
import htmltag
class Parser:
|
class NodeNotFoundError(Exception):
"""Error to be thrown when node is not found in tree."""
def __init__(self, name):
self.name = name
def __str__(self):
return repr(self.name)
class Tree:
"""A parser syntax tree.
The syntax tree is nothing more than an encapsulated dictionary. When
adding nodes to the tree, the node's name parameter is used as the tree's
key, while the node's dictionary of elements are used as the saved value.
"""
def __init__(self):
self.root_node = None
def add_node(self, node):
"""Add a node to the tree.
Parameters:
Node - The node to be added to the tree.
Returns:
Void
"""
self.nodes[node.name] = node.elements
def remove_node(self, node_name):
"""Remove the first node of a given name from the tree.
If the node does not exist in the tree, return a NodeNotFoundError.
Parameters:
Node_Name - The name of the node to be removed from the tree.
Returns:
Void
"""
if node_name in self.nodes:
del self.nodes[node.name]
else:
raise NodeNotFoundError(node_name)
def remove_nodes(self, node_name):
"""Remove all nodes of a given name from the tree.
If no nodes exist in the tree, return a NodeNotFoundError.
Parameters:
Node_Name - The name of the notes to be removed from the tree.
"""
class Node:
"""Element found within parser syntax tree.
Nodes encapsulate 3 values: a name, a list of containing elements, and a
list of child elements.
"""
def __init__(self, name, attributes = {}, children = []):
self.name = name
self.attributes = attributes
self.children = children
| """Parses .tmpl file to be outputted as an html file. """
def __init__(self, config_file = 'templ.conf'):
self.config_file = config_file
self.tree = None
self.rules = {}
self._load_config()
def _load_config(self):
"""Loads the configuration settings from the config_file."""
with open(self.config_file, 'r') as config:
self.rules = yaml.load(config)
def parse(self, pray_file):
"""Parse the input file and output a syntax tree.
Parameters:
pray_file - The name of the pray file to be parsed.
"""
# Begin parsing the file
with open(pray_file, 'r') as input_file:
syntax_tree = Tree()
lines = []
# Read the entire file as a list of lines
for line in input_file:
line = line.strip('\n')
# First, expand any variables found in the line
regex = re.compile(r'\$\w+')
matches = regex.findall(line)
if len(matches) > 0:
for match in matches:
replace = match.strip('$')
line = line.replace(match, self.rules[replace])
print(line) | identifier_body |
mouse.rs |
//! Back-end agnostic mouse buttons.
use num::{ FromPrimitive, ToPrimitive };
/// Represent a mouse button.
#[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq,
Eq, Ord, PartialOrd, Hash, Debug)]
pub enum MouseButton {
/// Unknown mouse button.
Unknown,
/// Left mouse button.
Left,
/// Right mouse button.
Right,
/// Middle mouse button.
Middle,
/// Extra mouse button number 1.
X1,
/// Extra mouse button number 2.
X2,
/// Mouse button number 6.
Button6,
/// Mouse button number 7.
Button7,
/// Mouse button number 8.
Button8,
}
impl FromPrimitive for MouseButton {
fn from_u64(n: u64) -> Option<MouseButton> {
match n {
0 => Some(MouseButton::Unknown),
1 => Some(MouseButton::Left),
2 => Some(MouseButton::Right),
3 => Some(MouseButton::Middle),
4 => Some(MouseButton::X1),
5 => Some(MouseButton::X2),
6 => Some(MouseButton::Button6),
7 => Some(MouseButton::Button7),
8 => Some(MouseButton::Button8),
_ => Some(MouseButton::Unknown),
}
}
#[inline(always)]
fn from_i64(n: i64) -> Option<MouseButton> {
FromPrimitive::from_u64(n as u64)
}
#[inline(always)]
fn from_isize(n: isize) -> Option<MouseButton> |
}
impl ToPrimitive for MouseButton {
fn to_u64(&self) -> Option<u64> {
match self {
&MouseButton::Unknown => Some(0),
&MouseButton::Left => Some(1),
&MouseButton::Right => Some(2),
&MouseButton::Middle => Some(3),
&MouseButton::X1 => Some(4),
&MouseButton::X2 => Some(5),
&MouseButton::Button6 => Some(6),
&MouseButton::Button7 => Some(7),
&MouseButton::Button8 => Some(8),
}
}
#[inline(always)]
fn to_i64(&self) -> Option<i64> {
self.to_u64().map(|x| x as i64)
}
#[inline(always)]
fn to_isize(&self) -> Option<isize> {
self.to_u64().map(|x| x as isize)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mouse_button_primitives() {
use num::{ FromPrimitive, ToPrimitive };
for i in 0u64..9 {
let button: MouseButton = FromPrimitive::from_u64(i).unwrap();
let j = ToPrimitive::to_u64(&button).unwrap();
assert_eq!(i, j);
}
}
}
| {
FromPrimitive::from_u64(n as u64)
} | identifier_body |
mouse.rs | //! Back-end agnostic mouse buttons.
use num::{ FromPrimitive, ToPrimitive }; | #[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq,
Eq, Ord, PartialOrd, Hash, Debug)]
pub enum MouseButton {
/// Unknown mouse button.
Unknown,
/// Left mouse button.
Left,
/// Right mouse button.
Right,
/// Middle mouse button.
Middle,
/// Extra mouse button number 1.
X1,
/// Extra mouse button number 2.
X2,
/// Mouse button number 6.
Button6,
/// Mouse button number 7.
Button7,
/// Mouse button number 8.
Button8,
}
impl FromPrimitive for MouseButton {
fn from_u64(n: u64) -> Option<MouseButton> {
match n {
0 => Some(MouseButton::Unknown),
1 => Some(MouseButton::Left),
2 => Some(MouseButton::Right),
3 => Some(MouseButton::Middle),
4 => Some(MouseButton::X1),
5 => Some(MouseButton::X2),
6 => Some(MouseButton::Button6),
7 => Some(MouseButton::Button7),
8 => Some(MouseButton::Button8),
_ => Some(MouseButton::Unknown),
}
}
#[inline(always)]
fn from_i64(n: i64) -> Option<MouseButton> {
FromPrimitive::from_u64(n as u64)
}
#[inline(always)]
fn from_isize(n: isize) -> Option<MouseButton> {
FromPrimitive::from_u64(n as u64)
}
}
impl ToPrimitive for MouseButton {
fn to_u64(&self) -> Option<u64> {
match self {
&MouseButton::Unknown => Some(0),
&MouseButton::Left => Some(1),
&MouseButton::Right => Some(2),
&MouseButton::Middle => Some(3),
&MouseButton::X1 => Some(4),
&MouseButton::X2 => Some(5),
&MouseButton::Button6 => Some(6),
&MouseButton::Button7 => Some(7),
&MouseButton::Button8 => Some(8),
}
}
#[inline(always)]
fn to_i64(&self) -> Option<i64> {
self.to_u64().map(|x| x as i64)
}
#[inline(always)]
fn to_isize(&self) -> Option<isize> {
self.to_u64().map(|x| x as isize)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mouse_button_primitives() {
use num::{ FromPrimitive, ToPrimitive };
for i in 0u64..9 {
let button: MouseButton = FromPrimitive::from_u64(i).unwrap();
let j = ToPrimitive::to_u64(&button).unwrap();
assert_eq!(i, j);
}
}
} |
/// Represent a mouse button. | random_line_split |
mouse.rs |
//! Back-end agnostic mouse buttons.
use num::{ FromPrimitive, ToPrimitive };
/// Represent a mouse button.
#[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq,
Eq, Ord, PartialOrd, Hash, Debug)]
pub enum MouseButton {
/// Unknown mouse button.
Unknown,
/// Left mouse button.
Left,
/// Right mouse button.
Right,
/// Middle mouse button.
Middle,
/// Extra mouse button number 1.
X1,
/// Extra mouse button number 2.
X2,
/// Mouse button number 6.
Button6,
/// Mouse button number 7.
Button7,
/// Mouse button number 8.
Button8,
}
impl FromPrimitive for MouseButton {
fn from_u64(n: u64) -> Option<MouseButton> {
match n {
0 => Some(MouseButton::Unknown),
1 => Some(MouseButton::Left),
2 => Some(MouseButton::Right),
3 => Some(MouseButton::Middle),
4 => Some(MouseButton::X1),
5 => Some(MouseButton::X2),
6 => Some(MouseButton::Button6),
7 => Some(MouseButton::Button7),
8 => Some(MouseButton::Button8),
_ => Some(MouseButton::Unknown),
}
}
#[inline(always)]
fn from_i64(n: i64) -> Option<MouseButton> {
FromPrimitive::from_u64(n as u64)
}
#[inline(always)]
fn from_isize(n: isize) -> Option<MouseButton> {
FromPrimitive::from_u64(n as u64)
}
}
impl ToPrimitive for MouseButton {
fn | (&self) -> Option<u64> {
match self {
&MouseButton::Unknown => Some(0),
&MouseButton::Left => Some(1),
&MouseButton::Right => Some(2),
&MouseButton::Middle => Some(3),
&MouseButton::X1 => Some(4),
&MouseButton::X2 => Some(5),
&MouseButton::Button6 => Some(6),
&MouseButton::Button7 => Some(7),
&MouseButton::Button8 => Some(8),
}
}
#[inline(always)]
fn to_i64(&self) -> Option<i64> {
self.to_u64().map(|x| x as i64)
}
#[inline(always)]
fn to_isize(&self) -> Option<isize> {
self.to_u64().map(|x| x as isize)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mouse_button_primitives() {
use num::{ FromPrimitive, ToPrimitive };
for i in 0u64..9 {
let button: MouseButton = FromPrimitive::from_u64(i).unwrap();
let j = ToPrimitive::to_u64(&button).unwrap();
assert_eq!(i, j);
}
}
}
| to_u64 | identifier_name |
log.rs | /* Copyright (C) 2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use super::modbus::ModbusTransaction;
use crate::jsonbuilder::{JsonBuilder, JsonError};
use sawp_modbus::{Data, Message, Read, Write};
#[no_mangle]
pub extern "C" fn rs_modbus_to_json(tx: &mut ModbusTransaction, js: &mut JsonBuilder) -> bool {
log(tx, js).is_ok()
}
/// populate a json object with transactional information, for logging
fn | (tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.open_object("modbus")?;
js.set_uint("id", tx.id)?;
if let Some(req) = &tx.request {
js.open_object("request")?;
log_message(&req, js)?;
js.close()?;
}
if let Some(resp) = &tx.response {
js.open_object("response")?;
log_message(&resp, js)?;
js.close()?;
}
js.close()?;
Ok(())
}
fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.set_uint("transaction_id", msg.transaction_id.into())?;
js.set_uint("protocol_id", msg.protocol_id.into())?;
js.set_uint("unit_id", msg.unit_id.into())?;
js.set_uint("function_raw", msg.function.raw.into())?;
js.set_string("function_code", &msg.function.code.to_string())?;
js.set_string("access_type", &msg.access_type.to_string())?;
js.set_string("category", &msg.category.to_string())?;
js.set_string("error_flags", &msg.error_flags.to_string())?;
match &msg.data {
Data::Exception(exc) => {
js.open_object("exception")?;
js.set_uint("raw", exc.raw.into())?;
js.set_string("code", &exc.code.to_string())?;
js.close()?;
}
Data::Diagnostic { func, data } => {
js.open_object("diagnostic")?;
js.set_uint("raw", func.raw.into())?;
js.set_string("code", &func.code.to_string())?;
js.set_string_from_bytes("data", &data)?;
js.close()?;
}
Data::MEI { mei_type, data } => {
js.open_object("mei")?;
js.set_uint("raw", mei_type.raw.into())?;
js.set_string("code", &mei_type.code.to_string())?;
js.set_string_from_bytes("data", &data)?;
js.close()?;
}
Data::Read(read) => {
js.open_object("read")?;
log_read(read, js)?;
js.close()?;
}
Data::Write(write) => {
js.open_object("write")?;
log_write(write, js)?;
js.close()?;
}
Data::ReadWrite { read, write } => {
js.open_object("read")?;
log_read(read, js)?;
js.close()?;
js.open_object("write")?;
log_write(write, js)?;
js.close()?;
}
Data::ByteVec(data) => {
js.set_string_from_bytes("data", &data)?;
}
Data::Empty => {}
}
Ok(())
}
fn log_read(read: &Read, js: &mut JsonBuilder) -> Result<(), JsonError> {
match read {
Read::Request { address, quantity } => {
js.set_uint("address", (*address).into())?;
js.set_uint("quantity", (*quantity).into())?;
}
Read::Response(data) => {
js.set_string_from_bytes("data", &data)?;
}
}
Ok(())
}
fn log_write(write: &Write, js: &mut JsonBuilder) -> Result<(), JsonError> {
match write {
Write::MultReq {
address,
quantity,
data,
} => {
js.set_uint("address", (*address).into())?;
js.set_uint("quantity", (*quantity).into())?;
js.set_string_from_bytes("data", &data)?;
}
Write::Mask {
address,
and_mask,
or_mask,
} => {
js.set_uint("address", (*address).into())?;
js.set_uint("and_mask", (*and_mask).into())?;
js.set_uint("or_mask", (*or_mask).into())?;
}
Write::Other { address, data } => {
js.set_uint("address", (*address).into())?;
js.set_uint("data", (*data).into())?;
}
}
Ok(())
}
| log | identifier_name |
log.rs | /* Copyright (C) 2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use super::modbus::ModbusTransaction;
use crate::jsonbuilder::{JsonBuilder, JsonError};
use sawp_modbus::{Data, Message, Read, Write};
#[no_mangle]
pub extern "C" fn rs_modbus_to_json(tx: &mut ModbusTransaction, js: &mut JsonBuilder) -> bool {
log(tx, js).is_ok()
}
/// populate a json object with transactional information, for logging
fn log(tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.open_object("modbus")?;
js.set_uint("id", tx.id)?;
if let Some(req) = &tx.request {
js.open_object("request")?;
log_message(&req, js)?;
js.close()?;
}
| }
js.close()?;
Ok(())
}
fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.set_uint("transaction_id", msg.transaction_id.into())?;
js.set_uint("protocol_id", msg.protocol_id.into())?;
js.set_uint("unit_id", msg.unit_id.into())?;
js.set_uint("function_raw", msg.function.raw.into())?;
js.set_string("function_code", &msg.function.code.to_string())?;
js.set_string("access_type", &msg.access_type.to_string())?;
js.set_string("category", &msg.category.to_string())?;
js.set_string("error_flags", &msg.error_flags.to_string())?;
match &msg.data {
Data::Exception(exc) => {
js.open_object("exception")?;
js.set_uint("raw", exc.raw.into())?;
js.set_string("code", &exc.code.to_string())?;
js.close()?;
}
Data::Diagnostic { func, data } => {
js.open_object("diagnostic")?;
js.set_uint("raw", func.raw.into())?;
js.set_string("code", &func.code.to_string())?;
js.set_string_from_bytes("data", &data)?;
js.close()?;
}
Data::MEI { mei_type, data } => {
js.open_object("mei")?;
js.set_uint("raw", mei_type.raw.into())?;
js.set_string("code", &mei_type.code.to_string())?;
js.set_string_from_bytes("data", &data)?;
js.close()?;
}
Data::Read(read) => {
js.open_object("read")?;
log_read(read, js)?;
js.close()?;
}
Data::Write(write) => {
js.open_object("write")?;
log_write(write, js)?;
js.close()?;
}
Data::ReadWrite { read, write } => {
js.open_object("read")?;
log_read(read, js)?;
js.close()?;
js.open_object("write")?;
log_write(write, js)?;
js.close()?;
}
Data::ByteVec(data) => {
js.set_string_from_bytes("data", &data)?;
}
Data::Empty => {}
}
Ok(())
}
fn log_read(read: &Read, js: &mut JsonBuilder) -> Result<(), JsonError> {
match read {
Read::Request { address, quantity } => {
js.set_uint("address", (*address).into())?;
js.set_uint("quantity", (*quantity).into())?;
}
Read::Response(data) => {
js.set_string_from_bytes("data", &data)?;
}
}
Ok(())
}
fn log_write(write: &Write, js: &mut JsonBuilder) -> Result<(), JsonError> {
match write {
Write::MultReq {
address,
quantity,
data,
} => {
js.set_uint("address", (*address).into())?;
js.set_uint("quantity", (*quantity).into())?;
js.set_string_from_bytes("data", &data)?;
}
Write::Mask {
address,
and_mask,
or_mask,
} => {
js.set_uint("address", (*address).into())?;
js.set_uint("and_mask", (*and_mask).into())?;
js.set_uint("or_mask", (*or_mask).into())?;
}
Write::Other { address, data } => {
js.set_uint("address", (*address).into())?;
js.set_uint("data", (*data).into())?;
}
}
Ok(())
} | if let Some(resp) = &tx.response {
js.open_object("response")?;
log_message(&resp, js)?;
js.close()?; | random_line_split |
log.rs | /* Copyright (C) 2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use super::modbus::ModbusTransaction;
use crate::jsonbuilder::{JsonBuilder, JsonError};
use sawp_modbus::{Data, Message, Read, Write};
#[no_mangle]
pub extern "C" fn rs_modbus_to_json(tx: &mut ModbusTransaction, js: &mut JsonBuilder) -> bool |
/// populate a json object with transactional information, for logging
fn log(tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.open_object("modbus")?;
js.set_uint("id", tx.id)?;
if let Some(req) = &tx.request {
js.open_object("request")?;
log_message(&req, js)?;
js.close()?;
}
if let Some(resp) = &tx.response {
js.open_object("response")?;
log_message(&resp, js)?;
js.close()?;
}
js.close()?;
Ok(())
}
fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.set_uint("transaction_id", msg.transaction_id.into())?;
js.set_uint("protocol_id", msg.protocol_id.into())?;
js.set_uint("unit_id", msg.unit_id.into())?;
js.set_uint("function_raw", msg.function.raw.into())?;
js.set_string("function_code", &msg.function.code.to_string())?;
js.set_string("access_type", &msg.access_type.to_string())?;
js.set_string("category", &msg.category.to_string())?;
js.set_string("error_flags", &msg.error_flags.to_string())?;
match &msg.data {
Data::Exception(exc) => {
js.open_object("exception")?;
js.set_uint("raw", exc.raw.into())?;
js.set_string("code", &exc.code.to_string())?;
js.close()?;
}
Data::Diagnostic { func, data } => {
js.open_object("diagnostic")?;
js.set_uint("raw", func.raw.into())?;
js.set_string("code", &func.code.to_string())?;
js.set_string_from_bytes("data", &data)?;
js.close()?;
}
Data::MEI { mei_type, data } => {
js.open_object("mei")?;
js.set_uint("raw", mei_type.raw.into())?;
js.set_string("code", &mei_type.code.to_string())?;
js.set_string_from_bytes("data", &data)?;
js.close()?;
}
Data::Read(read) => {
js.open_object("read")?;
log_read(read, js)?;
js.close()?;
}
Data::Write(write) => {
js.open_object("write")?;
log_write(write, js)?;
js.close()?;
}
Data::ReadWrite { read, write } => {
js.open_object("read")?;
log_read(read, js)?;
js.close()?;
js.open_object("write")?;
log_write(write, js)?;
js.close()?;
}
Data::ByteVec(data) => {
js.set_string_from_bytes("data", &data)?;
}
Data::Empty => {}
}
Ok(())
}
fn log_read(read: &Read, js: &mut JsonBuilder) -> Result<(), JsonError> {
match read {
Read::Request { address, quantity } => {
js.set_uint("address", (*address).into())?;
js.set_uint("quantity", (*quantity).into())?;
}
Read::Response(data) => {
js.set_string_from_bytes("data", &data)?;
}
}
Ok(())
}
fn log_write(write: &Write, js: &mut JsonBuilder) -> Result<(), JsonError> {
match write {
Write::MultReq {
address,
quantity,
data,
} => {
js.set_uint("address", (*address).into())?;
js.set_uint("quantity", (*quantity).into())?;
js.set_string_from_bytes("data", &data)?;
}
Write::Mask {
address,
and_mask,
or_mask,
} => {
js.set_uint("address", (*address).into())?;
js.set_uint("and_mask", (*and_mask).into())?;
js.set_uint("or_mask", (*or_mask).into())?;
}
Write::Other { address, data } => {
js.set_uint("address", (*address).into())?;
js.set_uint("data", (*data).into())?;
}
}
Ok(())
}
| {
log(tx, js).is_ok()
} | identifier_body |
PanelAddColumnButton.ts | import {SearchBox} from 'lineupjs';
import {ISearchOption} from './ISearchOption';
import {IPanelButton, PanelButton, IPanelButtonOptions} from './PanelButton';
import {I18nextManager} from '../../i18n';
export interface IPanelAddColumnButtonOptions extends Pick<IPanelButtonOptions, 'btnClass'> {
// nothing to add
}
/**
* Div HTMLElement that contains a button and a SearchBox.
* The SearchBox is hidden by default and can be toggled by the button.
*/
export class PanelAddColumnButton implements IPanelButton {
readonly node: HTMLElement;
/**
*
* @param parent The parent HTML DOM element
* @param search LineUp SearchBox instance
*/
| (parent: HTMLElement, private readonly search: SearchBox<ISearchOption>, options?: IPanelAddColumnButtonOptions) {
this.node = parent.ownerDocument.createElement('div');
this.node.classList.add('lu-adder');
this.node.addEventListener('mouseleave', () => {
this.node.classList.remove('once');
});
const button = new PanelButton(this.node, Object.assign(options, {
title: I18nextManager.getInstance().i18n.t('tdp:core.lineup.LineupPanelActions.addColumnButton'),
faIcon: 'fas fa-plus',
onClick: () => {
this.node.classList.add('once');
(<HTMLElement>this.search.node.querySelector('input'))!.focus();
this.search.focus();
}
}));
this.node.appendChild(button.node);
this.node.appendChild(this.search.node);
}
}
| constructor | identifier_name |
PanelAddColumnButton.ts | import {SearchBox} from 'lineupjs';
import {ISearchOption} from './ISearchOption';
import {IPanelButton, PanelButton, IPanelButtonOptions} from './PanelButton';
import {I18nextManager} from '../../i18n';
export interface IPanelAddColumnButtonOptions extends Pick<IPanelButtonOptions, 'btnClass'> {
// nothing to add
}
/**
* Div HTMLElement that contains a button and a SearchBox.
* The SearchBox is hidden by default and can be toggled by the button.
*/
export class PanelAddColumnButton implements IPanelButton {
readonly node: HTMLElement;
/**
*
* @param parent The parent HTML DOM element
* @param search LineUp SearchBox instance
*/
constructor(parent: HTMLElement, private readonly search: SearchBox<ISearchOption>, options?: IPanelAddColumnButtonOptions) { | });
const button = new PanelButton(this.node, Object.assign(options, {
title: I18nextManager.getInstance().i18n.t('tdp:core.lineup.LineupPanelActions.addColumnButton'),
faIcon: 'fas fa-plus',
onClick: () => {
this.node.classList.add('once');
(<HTMLElement>this.search.node.querySelector('input'))!.focus();
this.search.focus();
}
}));
this.node.appendChild(button.node);
this.node.appendChild(this.search.node);
}
} | this.node = parent.ownerDocument.createElement('div');
this.node.classList.add('lu-adder');
this.node.addEventListener('mouseleave', () => {
this.node.classList.remove('once'); | random_line_split |
PanelAddColumnButton.ts | import {SearchBox} from 'lineupjs';
import {ISearchOption} from './ISearchOption';
import {IPanelButton, PanelButton, IPanelButtonOptions} from './PanelButton';
import {I18nextManager} from '../../i18n';
export interface IPanelAddColumnButtonOptions extends Pick<IPanelButtonOptions, 'btnClass'> {
// nothing to add
}
/**
* Div HTMLElement that contains a button and a SearchBox.
* The SearchBox is hidden by default and can be toggled by the button.
*/
export class PanelAddColumnButton implements IPanelButton {
readonly node: HTMLElement;
/**
*
* @param parent The parent HTML DOM element
* @param search LineUp SearchBox instance
*/
constructor(parent: HTMLElement, private readonly search: SearchBox<ISearchOption>, options?: IPanelAddColumnButtonOptions) |
}
| {
this.node = parent.ownerDocument.createElement('div');
this.node.classList.add('lu-adder');
this.node.addEventListener('mouseleave', () => {
this.node.classList.remove('once');
});
const button = new PanelButton(this.node, Object.assign(options, {
title: I18nextManager.getInstance().i18n.t('tdp:core.lineup.LineupPanelActions.addColumnButton'),
faIcon: 'fas fa-plus',
onClick: () => {
this.node.classList.add('once');
(<HTMLElement>this.search.node.querySelector('input'))!.focus();
this.search.focus();
}
}));
this.node.appendChild(button.node);
this.node.appendChild(this.search.node);
} | identifier_body |
ui_infopanel.py | import wx
import functions
infoItems=[ ("active time", functions.FormatTime),
("active workers", None),
("active tasks", None),
("tasks done", None),
("pending urls", None),
("unique urls found", None),
("bytes read", functions.FormatByte),
("processing speed", functions.FormatByteSpeed),
("current processing speed", functions.FormatByteSpeed),
("work time", functions.FormatTime),
("errors", None),
("invalid data", None),
("http 1xx", None),
("http 2xx", None),
("http 3xx", None),
("http 4xx", None),
("http 5xx",None)]
class InfoPanel(wx.Panel):
def __init__(self, parent):
|
def Update(self, info):
for key, f in infoItems:
if f:
val=f(info[key])
else:
val=str(info[key])
if self.text[key].GetLabel()!=val:
self.text[key].SetLabel(val)
self.Layout()
| wx.Panel.__init__(self, parent)
self.sizer=wx.GridSizer(rows=len(infoItems), cols=2)
self.text={}
for key, f in infoItems:
self.text[key+"_TITLE"]=wx.StaticText(self, label=key+":")
self.text[key]=wx.StaticText(self)
self.text[key].SetMaxSize((-1, 20))
self.text[key+"_TITLE"].SetMaxSize((-1, 20))
self.sizer.Add(self.text[key+"_TITLE"], 1, wx.EXPAND)
self.sizer.Add(self.text[key], 1, wx.EXPAND)
self.sizer.SetVGap(1)
self.SetAutoLayout(True)
self.SetSizer(self.sizer)
self.Layout() | identifier_body |
ui_infopanel.py | import wx
import functions
infoItems=[ ("active time", functions.FormatTime),
("active workers", None),
("active tasks", None),
("tasks done", None),
("pending urls", None),
("unique urls found", None),
("bytes read", functions.FormatByte),
("processing speed", functions.FormatByteSpeed),
("current processing speed", functions.FormatByteSpeed),
("work time", functions.FormatTime),
("errors", None),
("invalid data", None),
("http 1xx", None),
("http 2xx", None),
("http 3xx", None),
("http 4xx", None),
("http 5xx",None)]
class InfoPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.sizer=wx.GridSizer(rows=len(infoItems), cols=2)
self.text={}
for key, f in infoItems:
self.text[key+"_TITLE"]=wx.StaticText(self, label=key+":")
self.text[key]=wx.StaticText(self)
self.text[key].SetMaxSize((-1, 20))
self.text[key+"_TITLE"].SetMaxSize((-1, 20))
self.sizer.Add(self.text[key+"_TITLE"], 1, wx.EXPAND)
self.sizer.Add(self.text[key], 1, wx.EXPAND)
self.sizer.SetVGap(1)
self.SetAutoLayout(True)
self.SetSizer(self.sizer)
self.Layout()
def Update(self, info):
for key, f in infoItems:
if f:
val=f(info[key])
else:
|
if self.text[key].GetLabel()!=val:
self.text[key].SetLabel(val)
self.Layout()
| val=str(info[key]) | conditional_block |
ui_infopanel.py | import wx
import functions
infoItems=[ ("active time", functions.FormatTime),
("active workers", None),
("active tasks", None),
("tasks done", None),
("pending urls", None),
("unique urls found", None),
("bytes read", functions.FormatByte),
("processing speed", functions.FormatByteSpeed),
("current processing speed", functions.FormatByteSpeed),
("work time", functions.FormatTime),
("errors", None),
("invalid data", None),
("http 1xx", None),
("http 2xx", None),
("http 3xx", None),
("http 4xx", None), | ("http 5xx",None)]
class InfoPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.sizer=wx.GridSizer(rows=len(infoItems), cols=2)
self.text={}
for key, f in infoItems:
self.text[key+"_TITLE"]=wx.StaticText(self, label=key+":")
self.text[key]=wx.StaticText(self)
self.text[key].SetMaxSize((-1, 20))
self.text[key+"_TITLE"].SetMaxSize((-1, 20))
self.sizer.Add(self.text[key+"_TITLE"], 1, wx.EXPAND)
self.sizer.Add(self.text[key], 1, wx.EXPAND)
self.sizer.SetVGap(1)
self.SetAutoLayout(True)
self.SetSizer(self.sizer)
self.Layout()
def Update(self, info):
for key, f in infoItems:
if f:
val=f(info[key])
else:
val=str(info[key])
if self.text[key].GetLabel()!=val:
self.text[key].SetLabel(val)
self.Layout() | random_line_split | |
ui_infopanel.py | import wx
import functions
infoItems=[ ("active time", functions.FormatTime),
("active workers", None),
("active tasks", None),
("tasks done", None),
("pending urls", None),
("unique urls found", None),
("bytes read", functions.FormatByte),
("processing speed", functions.FormatByteSpeed),
("current processing speed", functions.FormatByteSpeed),
("work time", functions.FormatTime),
("errors", None),
("invalid data", None),
("http 1xx", None),
("http 2xx", None),
("http 3xx", None),
("http 4xx", None),
("http 5xx",None)]
class InfoPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.sizer=wx.GridSizer(rows=len(infoItems), cols=2)
self.text={}
for key, f in infoItems:
self.text[key+"_TITLE"]=wx.StaticText(self, label=key+":")
self.text[key]=wx.StaticText(self)
self.text[key].SetMaxSize((-1, 20))
self.text[key+"_TITLE"].SetMaxSize((-1, 20))
self.sizer.Add(self.text[key+"_TITLE"], 1, wx.EXPAND)
self.sizer.Add(self.text[key], 1, wx.EXPAND)
self.sizer.SetVGap(1)
self.SetAutoLayout(True)
self.SetSizer(self.sizer)
self.Layout()
def | (self, info):
for key, f in infoItems:
if f:
val=f(info[key])
else:
val=str(info[key])
if self.text[key].GetLabel()!=val:
self.text[key].SetLabel(val)
self.Layout()
| Update | identifier_name |
Handler.js | "use strict";
var _ = require("lodash");
var Base = require("./Base");
var User = require("./User");
var UpdateMixin = require("./UpdateMixin");
/**
* Ticket handler model for the client
*
* @namespace models.client
* @class Handler
* @extends models.client.Base
* @uses models.client.UpdateMixin
*/
var Handler = Base.extend({
defaults: function() {
return {
type: "handlers",
createdAt: new Date().toString()
};
},
relationsMap: function() {
return {
handler: User
};
},
url: function() {
if (this.isNew()) return this.parent.url() + "/handlers";
return _.result(this.parent, "url") + "/handlers/" + this.get("handledById");
},
/**
* Return the handler user object | return this.rel("handler");
},
});
_.extend(Handler.prototype, UpdateMixin);
module.exports = Handler; | *
* @method getUser
* @return {models.client.User}
*/
getUser: function(){ | random_line_split |
quiz_error.rs | extern crate diesel;
use self::diesel::result::Error as DatabaseError;
use std::error;
use std::fmt;
use std::convert::From;
#[derive(Debug)]
pub enum QuizError {
DatabaseError(DatabaseError),
JokerUnavailable,
GameAlreadyFinished,
NoGameInProgress,
GameStillInProgress,
StateError,
OutOfResources,
}
impl fmt::Display for QuizError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
QuizError::DatabaseError(ref err) => write!(f, "Database error: {}", err),
QuizError::JokerUnavailable => write!(f, "Joker error: Tried to use unavailable Joker"),
QuizError::GameAlreadyFinished => {
write!(f,
"Game already finished error: Tried to interact with a game that has already been finished")
}
QuizError::NoGameInProgress => {
write!(f,
"No game in progress error: Tried to play without starting a game first")
}
QuizError::GameStillInProgress => {
write!(f,
"Game still in progress error: Tried to start game while old one was not finished yet")
}
QuizError::StateError => {
write!(f,
"State error: Found game in a corrupt state, e.g. no available categories")
}
QuizError::OutOfResources => {
write!(f, "Out of resources error: Answered all possible questions")
}
}
}
}
impl error::Error for QuizError {
fn description(&self) -> &str {
match *self {
QuizError::DatabaseError(ref err) => err.description(),
QuizError::JokerUnavailable => "Joker unavailable error",
QuizError::GameAlreadyFinished => "Game already finished error",
QuizError::GameStillInProgress => "Game still in progress error",
QuizError::NoGameInProgress => "No game in progress error",
QuizError::StateError => "State error",
QuizError::OutOfResources => "Out of resources error",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
QuizError::DatabaseError(ref err) => Some(err),
_ => None,
}
}
}
impl From<DatabaseError> for QuizError {
fn | (err: DatabaseError) -> Self {
QuizError::DatabaseError(err)
}
}
| from | identifier_name |
quiz_error.rs | extern crate diesel;
use self::diesel::result::Error as DatabaseError;
use std::error;
use std::fmt;
use std::convert::From;
#[derive(Debug)]
pub enum QuizError {
DatabaseError(DatabaseError),
JokerUnavailable,
GameAlreadyFinished,
NoGameInProgress,
GameStillInProgress,
StateError,
OutOfResources,
}
impl fmt::Display for QuizError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
QuizError::DatabaseError(ref err) => write!(f, "Database error: {}", err),
QuizError::JokerUnavailable => write!(f, "Joker error: Tried to use unavailable Joker"),
QuizError::GameAlreadyFinished => { | write!(f,
"Game already finished error: Tried to interact with a game that has already been finished")
}
QuizError::NoGameInProgress => {
write!(f,
"No game in progress error: Tried to play without starting a game first")
}
QuizError::GameStillInProgress => {
write!(f,
"Game still in progress error: Tried to start game while old one was not finished yet")
}
QuizError::StateError => {
write!(f,
"State error: Found game in a corrupt state, e.g. no available categories")
}
QuizError::OutOfResources => {
write!(f, "Out of resources error: Answered all possible questions")
}
}
}
}
impl error::Error for QuizError {
fn description(&self) -> &str {
match *self {
QuizError::DatabaseError(ref err) => err.description(),
QuizError::JokerUnavailable => "Joker unavailable error",
QuizError::GameAlreadyFinished => "Game already finished error",
QuizError::GameStillInProgress => "Game still in progress error",
QuizError::NoGameInProgress => "No game in progress error",
QuizError::StateError => "State error",
QuizError::OutOfResources => "Out of resources error",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
QuizError::DatabaseError(ref err) => Some(err),
_ => None,
}
}
}
impl From<DatabaseError> for QuizError {
fn from(err: DatabaseError) -> Self {
QuizError::DatabaseError(err)
}
} | random_line_split | |
quiz_error.rs | extern crate diesel;
use self::diesel::result::Error as DatabaseError;
use std::error;
use std::fmt;
use std::convert::From;
#[derive(Debug)]
pub enum QuizError {
DatabaseError(DatabaseError),
JokerUnavailable,
GameAlreadyFinished,
NoGameInProgress,
GameStillInProgress,
StateError,
OutOfResources,
}
impl fmt::Display for QuizError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
impl error::Error for QuizError {
fn description(&self) -> &str {
match *self {
QuizError::DatabaseError(ref err) => err.description(),
QuizError::JokerUnavailable => "Joker unavailable error",
QuizError::GameAlreadyFinished => "Game already finished error",
QuizError::GameStillInProgress => "Game still in progress error",
QuizError::NoGameInProgress => "No game in progress error",
QuizError::StateError => "State error",
QuizError::OutOfResources => "Out of resources error",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
QuizError::DatabaseError(ref err) => Some(err),
_ => None,
}
}
}
impl From<DatabaseError> for QuizError {
fn from(err: DatabaseError) -> Self {
QuizError::DatabaseError(err)
}
}
| {
match *self {
QuizError::DatabaseError(ref err) => write!(f, "Database error: {}", err),
QuizError::JokerUnavailable => write!(f, "Joker error: Tried to use unavailable Joker"),
QuizError::GameAlreadyFinished => {
write!(f,
"Game already finished error: Tried to interact with a game that has already been finished")
}
QuizError::NoGameInProgress => {
write!(f,
"No game in progress error: Tried to play without starting a game first")
}
QuizError::GameStillInProgress => {
write!(f,
"Game still in progress error: Tried to start game while old one was not finished yet")
}
QuizError::StateError => {
write!(f,
"State error: Found game in a corrupt state, e.g. no available categories")
}
QuizError::OutOfResources => {
write!(f, "Out of resources error: Answered all possible questions")
}
}
} | identifier_body |
getBuildingId.py | import boto3
from decEncoder import *
from DynamoTable import *
def | (event, context):
"""Dynamo resource"""
buildingTable = DynamoTable('Buildings')
return getBuildingId(event, buildingTable)
"""Lambda handler function for /buildings/{buildingId} API call
Returns building with the buildingId specified in the path
or 'Building not found' error if buildingId not found by query search
"""
def getBuildingId(event, buildingTable):
"""If buildingId specified, assign it to variable,
use get_item to find it in building table
put it in JSON format and return
"""
if event.get('pathParameters'):
buildingIdVal = event.get('pathParameters').get('buildingId')
response = buildingTable.get(buildingId=buildingIdVal)
if response.get('Item'):
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(response.get('Item'), cls=DecimalEncoder)
}
else:
"""Error if not found"""
return {
'statusCode': 404,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Building not found'})
}
else:
"""No path parameters"""
return {
'statusCode': 400,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Path not found'})
}
| handler | identifier_name |
getBuildingId.py | import boto3
from decEncoder import *
from DynamoTable import *
def handler(event, context):
|
"""Lambda handler function for /buildings/{buildingId} API call
Returns building with the buildingId specified in the path
or 'Building not found' error if buildingId not found by query search
"""
def getBuildingId(event, buildingTable):
"""If buildingId specified, assign it to variable,
use get_item to find it in building table
put it in JSON format and return
"""
if event.get('pathParameters'):
buildingIdVal = event.get('pathParameters').get('buildingId')
response = buildingTable.get(buildingId=buildingIdVal)
if response.get('Item'):
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(response.get('Item'), cls=DecimalEncoder)
}
else:
"""Error if not found"""
return {
'statusCode': 404,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Building not found'})
}
else:
"""No path parameters"""
return {
'statusCode': 400,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Path not found'})
}
| """Dynamo resource"""
buildingTable = DynamoTable('Buildings')
return getBuildingId(event, buildingTable) | identifier_body |
getBuildingId.py | import boto3
from decEncoder import *
from DynamoTable import *
def handler(event, context):
"""Dynamo resource"""
buildingTable = DynamoTable('Buildings')
return getBuildingId(event, buildingTable)
"""Lambda handler function for /buildings/{buildingId} API call
Returns building with the buildingId specified in the path
or 'Building not found' error if buildingId not found by query search
"""
def getBuildingId(event, buildingTable):
"""If buildingId specified, assign it to variable,
use get_item to find it in building table
put it in JSON format and return
"""
if event.get('pathParameters'):
buildingIdVal = event.get('pathParameters').get('buildingId')
response = buildingTable.get(buildingId=buildingIdVal)
if response.get('Item'):
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(response.get('Item'), cls=DecimalEncoder)
}
else:
|
else:
"""No path parameters"""
return {
'statusCode': 400,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Path not found'})
}
| """Error if not found"""
return {
'statusCode': 404,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Building not found'})
} | conditional_block |
getBuildingId.py | import boto3
from decEncoder import *
from DynamoTable import *
def handler(event, context): |
"""Lambda handler function for /buildings/{buildingId} API call
Returns building with the buildingId specified in the path
or 'Building not found' error if buildingId not found by query search
"""
def getBuildingId(event, buildingTable):
"""If buildingId specified, assign it to variable,
use get_item to find it in building table
put it in JSON format and return
"""
if event.get('pathParameters'):
buildingIdVal = event.get('pathParameters').get('buildingId')
response = buildingTable.get(buildingId=buildingIdVal)
if response.get('Item'):
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(response.get('Item'), cls=DecimalEncoder)
}
else:
"""Error if not found"""
return {
'statusCode': 404,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Building not found'})
}
else:
"""No path parameters"""
return {
'statusCode': 400,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': 'Path not found'})
} | """Dynamo resource"""
buildingTable = DynamoTable('Buildings')
return getBuildingId(event, buildingTable) | random_line_split |
debugger-step-in-ignore-injected-script.js | // 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.
(async function() {
TestRunner.addResult(`Tests that stepInto doesn't pause in InjectedScriptSource.\n`);
await TestRunner.loadLegacyModule('sources'); await TestRunner.loadTestModule('sources_test_runner');
await TestRunner.showPanel('sources');
await TestRunner.evaluateInPagePromise(`
function testFunction()
{
debugger;
console.log(123);
return 239; // stack result should point here
}
`);
SourcesTestRunner.startDebuggerTestPromise(/* quiet */ true)
.then(() => SourcesTestRunner.runTestFunctionAndWaitUntilPausedPromise())
.then(() => stepIntoPromise())
.then(() => stepIntoPromise())
.then((callFrames) => SourcesTestRunner.captureStackTrace(callFrames))
.then(() => SourcesTestRunner.completeDebuggerTest());
function | () {
var cb;
var p = new Promise(fullfill => cb = fullfill);
SourcesTestRunner.stepInto();
SourcesTestRunner.waitUntilResumed(() => SourcesTestRunner.waitUntilPaused(cb));
return p;
}
})();
| stepIntoPromise | identifier_name |
debugger-step-in-ignore-injected-script.js | // 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.
(async function() {
TestRunner.addResult(`Tests that stepInto doesn't pause in InjectedScriptSource.\n`);
await TestRunner.loadLegacyModule('sources'); await TestRunner.loadTestModule('sources_test_runner');
await TestRunner.showPanel('sources');
await TestRunner.evaluateInPagePromise(`
function testFunction()
{
debugger;
console.log(123);
return 239; // stack result should point here
}
`);
SourcesTestRunner.startDebuggerTestPromise(/* quiet */ true)
.then(() => SourcesTestRunner.runTestFunctionAndWaitUntilPausedPromise())
.then(() => stepIntoPromise())
.then(() => stepIntoPromise())
.then((callFrames) => SourcesTestRunner.captureStackTrace(callFrames))
.then(() => SourcesTestRunner.completeDebuggerTest());
function stepIntoPromise() {
var cb;
var p = new Promise(fullfill => cb = fullfill);
SourcesTestRunner.stepInto();
SourcesTestRunner.waitUntilResumed(() => SourcesTestRunner.waitUntilPaused(cb));
return p; | })(); | } | random_line_split |
debugger-step-in-ignore-injected-script.js | // 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.
(async function() {
TestRunner.addResult(`Tests that stepInto doesn't pause in InjectedScriptSource.\n`);
await TestRunner.loadLegacyModule('sources'); await TestRunner.loadTestModule('sources_test_runner');
await TestRunner.showPanel('sources');
await TestRunner.evaluateInPagePromise(`
function testFunction()
{
debugger;
console.log(123);
return 239; // stack result should point here
}
`);
SourcesTestRunner.startDebuggerTestPromise(/* quiet */ true)
.then(() => SourcesTestRunner.runTestFunctionAndWaitUntilPausedPromise())
.then(() => stepIntoPromise())
.then(() => stepIntoPromise())
.then((callFrames) => SourcesTestRunner.captureStackTrace(callFrames))
.then(() => SourcesTestRunner.completeDebuggerTest());
function stepIntoPromise() |
})();
| {
var cb;
var p = new Promise(fullfill => cb = fullfill);
SourcesTestRunner.stepInto();
SourcesTestRunner.waitUntilResumed(() => SourcesTestRunner.waitUntilPaused(cb));
return p;
} | identifier_body |
capabilities.py | # -*- Mode: Python; coding: iso-8859-1 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Stoqdrivers
# Copyright (C) 2005 Async Open Source <http://www.async.com.br>
# All rights reserved
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
# Author(s): Henrique Romano <henrique@async.com.br>
#
"""
Driver Capability management.
"""
from numbers import Real
from typing import Optional
from stoqdrivers.exceptions import CapabilityError
class Capability:
| """ This class is used to represent a driver capability, offering methods
to validate a value with base in the capability limits.
"""
def __init__(self, min_len: Optional[int]=None, max_len: Optional[int]=None,
max_size: Optional[Real]=None, min_size: Optional[Real]=None,
digits: Optional[int]=None, decimals: Optional[Real]=None):
""" Creates a new driver capability. A driver capability can be
represented basically by the max length of a string, the max digits
number of a value or its minimum/maximum size. With an instance of
Capability you can check if a value is acceptable by the driver
through the check_value method. The Capability arguments are:
@param min_len: The minimum length of a string
@type min_len: int
@param max_len: The max length of a string
@type max_len: int
@param max_size The maximum size for a value
@type max_size: number
@param min_size: The minimum size for a value
@type min_size: number
@param digits: The number of digits that a number can have
@type digits: int
@param decimals: If the max value for the capability is a float,
this parameter specifies the max precision
that the number can have.
@type decimals: number
Note that 'max_len' can't be used together with 'min_size', 'max_size'
and 'digits', in the same way that 'max_size' and 'min_size' can't be
used with 'digits'. The values defined for these parameters are used
also to verify the value type in the 'check_value' method.
"""
if max_len is not None and (max_size is not None
and min_size is not None
and digits is not None
and decimals):
raise ValueError("max_len cannot be used together with max_size, "
"min_size, digits or decimals")
if digits is not None:
if max_size is not None:
raise ValueError("digits can't be used with max_size")
if decimals:
decimal_part = 1 - (1 / 10.0 ** decimals)
else:
decimal_part = 0
self.max_size = ((10.0 ** digits) - 1) + decimal_part
self.min_len = min_len
self.max_len = max_len
self.min_size = min_size or 0
self.max_size = max_size
self.digits = digits
self.decimals = decimals
def check_value(self, value):
if self.max_len:
if not isinstance(value, str):
raise CapabilityError("the value must be a string")
if len(value) > (self.max_len or float('inf')):
raise CapabilityError("the value can't be greater than %d "
"characters" % self.max_len)
elif len(value) < (self.min_len or float('-inf')):
raise CapabilityError("the value can't be less than %d "
"characters" % self.min_len)
return
elif not (self.max_size and self.min_size):
return
if not isinstance(value, (float, int)):
raise CapabilityError("the value must be float, integer or long")
if value > (self.max_size or float('inf')):
raise CapabilityError("the value can't be greater than %r"
% self.max_size)
elif value < (self.min_size or float('-inf')):
raise CapabilityError("the value can't be less than %r"
% self.min_size) | identifier_body | |
capabilities.py | # -*- Mode: Python; coding: iso-8859-1 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Stoqdrivers
# Copyright (C) 2005 Async Open Source <http://www.async.com.br>
# All rights reserved
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
# Author(s): Henrique Romano <henrique@async.com.br>
#
"""
Driver Capability management.
"""
from numbers import Real
from typing import Optional
from stoqdrivers.exceptions import CapabilityError
class Capability:
""" This class is used to represent a driver capability, offering methods
to validate a value with base in the capability limits.
"""
def __init__(self, min_len: Optional[int]=None, max_len: Optional[int]=None,
max_size: Optional[Real]=None, min_size: Optional[Real]=None,
digits: Optional[int]=None, decimals: Optional[Real]=None):
""" Creates a new driver capability. A driver capability can be
represented basically by the max length of a string, the max digits
number of a value or its minimum/maximum size. With an instance of
Capability you can check if a value is acceptable by the driver
through the check_value method. The Capability arguments are: |
@param min_len: The minimum length of a string
@type min_len: int
@param max_len: The max length of a string
@type max_len: int
@param max_size The maximum size for a value
@type max_size: number
@param min_size: The minimum size for a value
@type min_size: number
@param digits: The number of digits that a number can have
@type digits: int
@param decimals: If the max value for the capability is a float,
this parameter specifies the max precision
that the number can have.
@type decimals: number
Note that 'max_len' can't be used together with 'min_size', 'max_size'
and 'digits', in the same way that 'max_size' and 'min_size' can't be
used with 'digits'. The values defined for these parameters are used
also to verify the value type in the 'check_value' method.
"""
if max_len is not None and (max_size is not None
and min_size is not None
and digits is not None
and decimals):
raise ValueError("max_len cannot be used together with max_size, "
"min_size, digits or decimals")
if digits is not None:
if max_size is not None:
raise ValueError("digits can't be used with max_size")
if decimals:
decimal_part = 1 - (1 / 10.0 ** decimals)
else:
decimal_part = 0
self.max_size = ((10.0 ** digits) - 1) + decimal_part
self.min_len = min_len
self.max_len = max_len
self.min_size = min_size or 0
self.max_size = max_size
self.digits = digits
self.decimals = decimals
def check_value(self, value):
if self.max_len:
if not isinstance(value, str):
raise CapabilityError("the value must be a string")
if len(value) > (self.max_len or float('inf')):
raise CapabilityError("the value can't be greater than %d "
"characters" % self.max_len)
elif len(value) < (self.min_len or float('-inf')):
raise CapabilityError("the value can't be less than %d "
"characters" % self.min_len)
return
elif not (self.max_size and self.min_size):
return
if not isinstance(value, (float, int)):
raise CapabilityError("the value must be float, integer or long")
if value > (self.max_size or float('inf')):
raise CapabilityError("the value can't be greater than %r"
% self.max_size)
elif value < (self.min_size or float('-inf')):
raise CapabilityError("the value can't be less than %r"
% self.min_size) | random_line_split | |
capabilities.py | # -*- Mode: Python; coding: iso-8859-1 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Stoqdrivers
# Copyright (C) 2005 Async Open Source <http://www.async.com.br>
# All rights reserved
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
# Author(s): Henrique Romano <henrique@async.com.br>
#
"""
Driver Capability management.
"""
from numbers import Real
from typing import Optional
from stoqdrivers.exceptions import CapabilityError
class Capability:
""" This class is used to represent a driver capability, offering methods
to validate a value with base in the capability limits.
"""
def | (self, min_len: Optional[int]=None, max_len: Optional[int]=None,
max_size: Optional[Real]=None, min_size: Optional[Real]=None,
digits: Optional[int]=None, decimals: Optional[Real]=None):
""" Creates a new driver capability. A driver capability can be
represented basically by the max length of a string, the max digits
number of a value or its minimum/maximum size. With an instance of
Capability you can check if a value is acceptable by the driver
through the check_value method. The Capability arguments are:
@param min_len: The minimum length of a string
@type min_len: int
@param max_len: The max length of a string
@type max_len: int
@param max_size The maximum size for a value
@type max_size: number
@param min_size: The minimum size for a value
@type min_size: number
@param digits: The number of digits that a number can have
@type digits: int
@param decimals: If the max value for the capability is a float,
this parameter specifies the max precision
that the number can have.
@type decimals: number
Note that 'max_len' can't be used together with 'min_size', 'max_size'
and 'digits', in the same way that 'max_size' and 'min_size' can't be
used with 'digits'. The values defined for these parameters are used
also to verify the value type in the 'check_value' method.
"""
if max_len is not None and (max_size is not None
and min_size is not None
and digits is not None
and decimals):
raise ValueError("max_len cannot be used together with max_size, "
"min_size, digits or decimals")
if digits is not None:
if max_size is not None:
raise ValueError("digits can't be used with max_size")
if decimals:
decimal_part = 1 - (1 / 10.0 ** decimals)
else:
decimal_part = 0
self.max_size = ((10.0 ** digits) - 1) + decimal_part
self.min_len = min_len
self.max_len = max_len
self.min_size = min_size or 0
self.max_size = max_size
self.digits = digits
self.decimals = decimals
def check_value(self, value):
if self.max_len:
if not isinstance(value, str):
raise CapabilityError("the value must be a string")
if len(value) > (self.max_len or float('inf')):
raise CapabilityError("the value can't be greater than %d "
"characters" % self.max_len)
elif len(value) < (self.min_len or float('-inf')):
raise CapabilityError("the value can't be less than %d "
"characters" % self.min_len)
return
elif not (self.max_size and self.min_size):
return
if not isinstance(value, (float, int)):
raise CapabilityError("the value must be float, integer or long")
if value > (self.max_size or float('inf')):
raise CapabilityError("the value can't be greater than %r"
% self.max_size)
elif value < (self.min_size or float('-inf')):
raise CapabilityError("the value can't be less than %r"
% self.min_size)
| __init__ | identifier_name |
capabilities.py | # -*- Mode: Python; coding: iso-8859-1 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Stoqdrivers
# Copyright (C) 2005 Async Open Source <http://www.async.com.br>
# All rights reserved
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
# Author(s): Henrique Romano <henrique@async.com.br>
#
"""
Driver Capability management.
"""
from numbers import Real
from typing import Optional
from stoqdrivers.exceptions import CapabilityError
class Capability:
""" This class is used to represent a driver capability, offering methods
to validate a value with base in the capability limits.
"""
def __init__(self, min_len: Optional[int]=None, max_len: Optional[int]=None,
max_size: Optional[Real]=None, min_size: Optional[Real]=None,
digits: Optional[int]=None, decimals: Optional[Real]=None):
""" Creates a new driver capability. A driver capability can be
represented basically by the max length of a string, the max digits
number of a value or its minimum/maximum size. With an instance of
Capability you can check if a value is acceptable by the driver
through the check_value method. The Capability arguments are:
@param min_len: The minimum length of a string
@type min_len: int
@param max_len: The max length of a string
@type max_len: int
@param max_size The maximum size for a value
@type max_size: number
@param min_size: The minimum size for a value
@type min_size: number
@param digits: The number of digits that a number can have
@type digits: int
@param decimals: If the max value for the capability is a float,
this parameter specifies the max precision
that the number can have.
@type decimals: number
Note that 'max_len' can't be used together with 'min_size', 'max_size'
and 'digits', in the same way that 'max_size' and 'min_size' can't be
used with 'digits'. The values defined for these parameters are used
also to verify the value type in the 'check_value' method.
"""
if max_len is not None and (max_size is not None
and min_size is not None
and digits is not None
and decimals):
raise ValueError("max_len cannot be used together with max_size, "
"min_size, digits or decimals")
if digits is not None:
if max_size is not None:
raise ValueError("digits can't be used with max_size")
if decimals:
decimal_part = 1 - (1 / 10.0 ** decimals)
else:
decimal_part = 0
self.max_size = ((10.0 ** digits) - 1) + decimal_part
self.min_len = min_len
self.max_len = max_len
self.min_size = min_size or 0
self.max_size = max_size
self.digits = digits
self.decimals = decimals
def check_value(self, value):
if self.max_len:
if not isinstance(value, str):
raise CapabilityError("the value must be a string")
if len(value) > (self.max_len or float('inf')):
raise CapabilityError("the value can't be greater than %d "
"characters" % self.max_len)
elif len(value) < (self.min_len or float('-inf')):
raise CapabilityError("the value can't be less than %d "
"characters" % self.min_len)
return
elif not (self.max_size and self.min_size):
return
if not isinstance(value, (float, int)):
raise CapabilityError("the value must be float, integer or long")
if value > (self.max_size or float('inf')):
|
elif value < (self.min_size or float('-inf')):
raise CapabilityError("the value can't be less than %r"
% self.min_size)
| raise CapabilityError("the value can't be greater than %r"
% self.max_size) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.