file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
39k
| suffix
large_stringlengths 0
36.1k
| middle
large_stringlengths 0
29.4k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
test_project_duplicate_subtask.py | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProjectDuplicateSubtask(TransactionCase):
def setUp(self):
super().setUp()
self.project1 = self.env["project.project"].create({"name": "Project 1"})
self.task1 = self.env["project.task"].create(
{"name": "name1", "project_id": self.project1.id}
)
self.subtask1 = self.env["project.task"].create(
{"name": "2", "project_id": self.project1.id, "parent_id": self.task1.id}
)
self.subtask2 = self.env["project.task"].create(
{"name": "3", "project_id": self.project1.id, "parent_id": self.task1.id}
)
def | (self):
self.task1.action_duplicate_subtasks()
new_task = self.env["project.task"].search(
[("name", "ilike", self.task1.name), ("name", "ilike", "copy")]
)
self.assertEqual(
len(new_task.child_ids), 2, "Two subtasks should have been created"
)
| test_check_subtasks | identifier_name |
test_project_duplicate_subtask.py | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProjectDuplicateSubtask(TransactionCase):
def setUp(self):
|
def test_check_subtasks(self):
self.task1.action_duplicate_subtasks()
new_task = self.env["project.task"].search(
[("name", "ilike", self.task1.name), ("name", "ilike", "copy")]
)
self.assertEqual(
len(new_task.child_ids), 2, "Two subtasks should have been created"
)
| super().setUp()
self.project1 = self.env["project.project"].create({"name": "Project 1"})
self.task1 = self.env["project.task"].create(
{"name": "name1", "project_id": self.project1.id}
)
self.subtask1 = self.env["project.task"].create(
{"name": "2", "project_id": self.project1.id, "parent_id": self.task1.id}
)
self.subtask2 = self.env["project.task"].create(
{"name": "3", "project_id": self.project1.id, "parent_id": self.task1.id}
) | identifier_body |
test_project_duplicate_subtask.py | # Copyright (C) 2021 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProjectDuplicateSubtask(TransactionCase):
def setUp(self):
super().setUp()
| {"name": "name1", "project_id": self.project1.id}
)
self.subtask1 = self.env["project.task"].create(
{"name": "2", "project_id": self.project1.id, "parent_id": self.task1.id}
)
self.subtask2 = self.env["project.task"].create(
{"name": "3", "project_id": self.project1.id, "parent_id": self.task1.id}
)
def test_check_subtasks(self):
self.task1.action_duplicate_subtasks()
new_task = self.env["project.task"].search(
[("name", "ilike", self.task1.name), ("name", "ilike", "copy")]
)
self.assertEqual(
len(new_task.child_ids), 2, "Two subtasks should have been created"
) | self.project1 = self.env["project.project"].create({"name": "Project 1"})
self.task1 = self.env["project.task"].create( | 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, [email protected], 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 *
class | (AutotoolsPackage):
"""The ViennaRNA Package consists of a C code library and several
stand-alone programs for the prediction and comparison of RNA secondary
structures.
"""
homepage = "https://www.tbi.univie.ac.at/RNA/"
url = "https://www.tbi.univie.ac.at/RNA/download/sourcecode/2_4_x/ViennaRNA-2.4.3.tar.gz"
version('2.4.3', '41be2fd36a5323a35ed50debfc7bd118')
version('2.3.5', '4542120adae9b7abb605e2304c2a1326')
variant('sse', default=True, description='Enable SSE in order to substantially speed up execution')
variant('perl', default=True, description='Build ViennaRNA with Perl interface')
variant('python', default=True, description='Build ViennaRNA with Python interface')
depends_on('perl', type=('build', 'run'))
depends_on('python', type=('build', 'run'))
depends_on('libsvm')
depends_on('gsl')
def url_for_version(self, version):
url = 'https://www.tbi.univie.ac.at/RNA/download/sourcecode/{0}_x/ViennaRNA-{1}.tar.gz'
return url.format(version.up_to(2).underscored, version)
def configure_args(self):
args = self.enable_or_disable('sse')
args += self.with_or_without('python')
args += self.with_or_without('perl')
if self.spec.satisfies('@2.4.3:'):
args.append('--without-swig')
if 'python@3:' in self.spec:
args.append('--with-python3')
return args
| Viennarna | 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, [email protected], 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. | # 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 *
class Viennarna(AutotoolsPackage):
"""The ViennaRNA Package consists of a C code library and several
stand-alone programs for the prediction and comparison of RNA secondary
structures.
"""
homepage = "https://www.tbi.univie.ac.at/RNA/"
url = "https://www.tbi.univie.ac.at/RNA/download/sourcecode/2_4_x/ViennaRNA-2.4.3.tar.gz"
version('2.4.3', '41be2fd36a5323a35ed50debfc7bd118')
version('2.3.5', '4542120adae9b7abb605e2304c2a1326')
variant('sse', default=True, description='Enable SSE in order to substantially speed up execution')
variant('perl', default=True, description='Build ViennaRNA with Perl interface')
variant('python', default=True, description='Build ViennaRNA with Python interface')
depends_on('perl', type=('build', 'run'))
depends_on('python', type=('build', 'run'))
depends_on('libsvm')
depends_on('gsl')
def url_for_version(self, version):
url = 'https://www.tbi.univie.ac.at/RNA/download/sourcecode/{0}_x/ViennaRNA-{1}.tar.gz'
return url.format(version.up_to(2).underscored, version)
def configure_args(self):
args = self.enable_or_disable('sse')
args += self.with_or_without('python')
args += self.with_or_without('perl')
if self.spec.satisfies('@2.4.3:'):
args.append('--without-swig')
if 'python@3:' in self.spec:
args.append('--with-python3')
return args | #
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF | 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, [email protected], 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 *
class Viennarna(AutotoolsPackage):
"""The ViennaRNA Package consists of a C code library and several
stand-alone programs for the prediction and comparison of RNA secondary
structures.
"""
homepage = "https://www.tbi.univie.ac.at/RNA/"
url = "https://www.tbi.univie.ac.at/RNA/download/sourcecode/2_4_x/ViennaRNA-2.4.3.tar.gz"
version('2.4.3', '41be2fd36a5323a35ed50debfc7bd118')
version('2.3.5', '4542120adae9b7abb605e2304c2a1326')
variant('sse', default=True, description='Enable SSE in order to substantially speed up execution')
variant('perl', default=True, description='Build ViennaRNA with Perl interface')
variant('python', default=True, description='Build ViennaRNA with Python interface')
depends_on('perl', type=('build', 'run'))
depends_on('python', type=('build', 'run'))
depends_on('libsvm')
depends_on('gsl')
def url_for_version(self, version):
|
def configure_args(self):
args = self.enable_or_disable('sse')
args += self.with_or_without('python')
args += self.with_or_without('perl')
if self.spec.satisfies('@2.4.3:'):
args.append('--without-swig')
if 'python@3:' in self.spec:
args.append('--with-python3')
return args
| url = 'https://www.tbi.univie.ac.at/RNA/download/sourcecode/{0}_x/ViennaRNA-{1}.tar.gz'
return url.format(version.up_to(2).underscored, version) | identifier_body |
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, [email protected], 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 *
class Viennarna(AutotoolsPackage):
"""The ViennaRNA Package consists of a C code library and several
stand-alone programs for the prediction and comparison of RNA secondary
structures.
"""
homepage = "https://www.tbi.univie.ac.at/RNA/"
url = "https://www.tbi.univie.ac.at/RNA/download/sourcecode/2_4_x/ViennaRNA-2.4.3.tar.gz"
version('2.4.3', '41be2fd36a5323a35ed50debfc7bd118')
version('2.3.5', '4542120adae9b7abb605e2304c2a1326')
variant('sse', default=True, description='Enable SSE in order to substantially speed up execution')
variant('perl', default=True, description='Build ViennaRNA with Perl interface')
variant('python', default=True, description='Build ViennaRNA with Python interface')
depends_on('perl', type=('build', 'run'))
depends_on('python', type=('build', 'run'))
depends_on('libsvm')
depends_on('gsl')
def url_for_version(self, version):
url = 'https://www.tbi.univie.ac.at/RNA/download/sourcecode/{0}_x/ViennaRNA-{1}.tar.gz'
return url.format(version.up_to(2).underscored, version)
def configure_args(self):
args = self.enable_or_disable('sse')
args += self.with_or_without('python')
args += self.with_or_without('perl')
if self.spec.satisfies('@2.4.3:'):
|
if 'python@3:' in self.spec:
args.append('--with-python3')
return args
| args.append('--without-swig') | conditional_block |
test_cluster.py | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):
def handle_cb(self, req, **kwargs):
if kwargs.get('codes'):
cl = [200, 201] + kwargs.get('codes')
self.assertTrue(req.code in cl)
else:
self.assertTrue(req.code in (200, 201, ))
self.stop()
def test_health(self):
c = ClusterClient()
c.cluster_health(callback=self.handle_cb)
self.wait()
def test_pending_tasks(self):
c = ClusterClient()
c.cluster_pending_tasks(callback=self.handle_cb)
self.wait()
def test_state(self):
c = ClusterClient()
c.cluster_state(callback=self.handle_cb)
self.wait()
def test_stats(self):
c = ClusterClient()
c.cluster_stats(callback=self.handle_cb)
self.wait()
def test_reroute(self):
c = ClusterClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]} | {
"commands" : [ {
"move" :
{
"index" : "test", "shard" : 0,
"from_node" : "node1", "to_node" : "node2"
}
},
{
"allocate" : {
"index" : "test", "shard" : 1, "node" : "node3"
}
}
]
}
"""
c.cluster_reroute(body, callback=h_cb)
self.wait()
def test_get_settings(self):
c = ClusterClient()
c.cluster_get_settings(callback=self.handle_cb)
self.wait()
def test_put_settings(self):
c = ClusterClient()
body = """
{
"persistent" : {
"discovery.zen.minimum_master_nodes" : 1
}
}
"""
c.cluster_put_settings(body, callback=self.handle_cb)
self.wait() | )
body = """ | random_line_split |
test_cluster.py | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):
def handle_cb(self, req, **kwargs):
if kwargs.get('codes'):
cl = [200, 201] + kwargs.get('codes')
self.assertTrue(req.code in cl)
else:
self.assertTrue(req.code in (200, 201, ))
self.stop()
def test_health(self):
c = ClusterClient()
c.cluster_health(callback=self.handle_cb)
self.wait()
def test_pending_tasks(self):
c = ClusterClient()
c.cluster_pending_tasks(callback=self.handle_cb)
self.wait()
def test_state(self):
c = ClusterClient()
c.cluster_state(callback=self.handle_cb)
self.wait()
def test_stats(self):
c = ClusterClient()
c.cluster_stats(callback=self.handle_cb)
self.wait()
def test_reroute(self):
c = ClusterClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
body = """
{
"commands" : [ {
"move" :
{
"index" : "test", "shard" : 0,
"from_node" : "node1", "to_node" : "node2"
}
},
{
"allocate" : {
"index" : "test", "shard" : 1, "node" : "node3"
}
}
]
}
"""
c.cluster_reroute(body, callback=h_cb)
self.wait()
def test_get_settings(self):
|
def test_put_settings(self):
c = ClusterClient()
body = """
{
"persistent" : {
"discovery.zen.minimum_master_nodes" : 1
}
}
"""
c.cluster_put_settings(body, callback=self.handle_cb)
self.wait()
| c = ClusterClient()
c.cluster_get_settings(callback=self.handle_cb)
self.wait() | identifier_body |
test_cluster.py | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):
def handle_cb(self, req, **kwargs):
if kwargs.get('codes'):
cl = [200, 201] + kwargs.get('codes')
self.assertTrue(req.code in cl)
else:
|
self.stop()
def test_health(self):
c = ClusterClient()
c.cluster_health(callback=self.handle_cb)
self.wait()
def test_pending_tasks(self):
c = ClusterClient()
c.cluster_pending_tasks(callback=self.handle_cb)
self.wait()
def test_state(self):
c = ClusterClient()
c.cluster_state(callback=self.handle_cb)
self.wait()
def test_stats(self):
c = ClusterClient()
c.cluster_stats(callback=self.handle_cb)
self.wait()
def test_reroute(self):
c = ClusterClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
body = """
{
"commands" : [ {
"move" :
{
"index" : "test", "shard" : 0,
"from_node" : "node1", "to_node" : "node2"
}
},
{
"allocate" : {
"index" : "test", "shard" : 1, "node" : "node3"
}
}
]
}
"""
c.cluster_reroute(body, callback=h_cb)
self.wait()
def test_get_settings(self):
c = ClusterClient()
c.cluster_get_settings(callback=self.handle_cb)
self.wait()
def test_put_settings(self):
c = ClusterClient()
body = """
{
"persistent" : {
"discovery.zen.minimum_master_nodes" : 1
}
}
"""
c.cluster_put_settings(body, callback=self.handle_cb)
self.wait()
| self.assertTrue(req.code in (200, 201, )) | conditional_block |
test_cluster.py | import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):
def handle_cb(self, req, **kwargs):
if kwargs.get('codes'):
cl = [200, 201] + kwargs.get('codes')
self.assertTrue(req.code in cl)
else:
self.assertTrue(req.code in (200, 201, ))
self.stop()
def test_health(self):
c = ClusterClient()
c.cluster_health(callback=self.handle_cb)
self.wait()
def test_pending_tasks(self):
c = ClusterClient()
c.cluster_pending_tasks(callback=self.handle_cb)
self.wait()
def test_state(self):
c = ClusterClient()
c.cluster_state(callback=self.handle_cb)
self.wait()
def test_stats(self):
c = ClusterClient()
c.cluster_stats(callback=self.handle_cb)
self.wait()
def | (self):
c = ClusterClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
body = """
{
"commands" : [ {
"move" :
{
"index" : "test", "shard" : 0,
"from_node" : "node1", "to_node" : "node2"
}
},
{
"allocate" : {
"index" : "test", "shard" : 1, "node" : "node3"
}
}
]
}
"""
c.cluster_reroute(body, callback=h_cb)
self.wait()
def test_get_settings(self):
c = ClusterClient()
c.cluster_get_settings(callback=self.handle_cb)
self.wait()
def test_put_settings(self):
c = ClusterClient()
body = """
{
"persistent" : {
"discovery.zen.minimum_master_nodes" : 1
}
}
"""
c.cluster_put_settings(body, callback=self.handle_cb)
self.wait()
| test_reroute | identifier_name |
weka.py | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <[email protected]>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfile, os, os.path, subprocess, re
from api import *
from nltk.probability import *
from nltk.internals import java, config_java
"""
Classifiers that make use of the external 'Weka' package.
"""
_weka_classpath = None
_weka_search = ['.',
'/usr/share/weka',
'/usr/local/share/weka',
'/usr/lib/weka',
'/usr/local/lib/weka',]
def config_weka(classpath=None):
global _weka_classpath
# Make sure java's configured first.
config_java()
if classpath is not None:
_weka_classpath = classpath
if _weka_classpath is None:
searchpath = _weka_search
if 'WEKAHOME' in os.environ:
searchpath.insert(0, os.environ['WEKAHOME'])
for path in searchpath:
if os.path.exists(os.path.join(path, 'weka.jar')):
_weka_classpath = os.path.join(path, 'weka.jar')
print '[Found Weka: %s]' % _weka_classpath
if _weka_classpath is None:
raise LookupError('Unable to find weka.jar! Use config_weka() '
'or set the WEKAHOME environment variable. '
'For more information about Weka, please see '
'http://www.cs.waikato.ac.nz/ml/weka/')
class WekaClassifier(ClassifierI):
def __init__(self, formatter, model_filename):
self._formatter = formatter
self._model = model_filename
def batch_prob_classify(self, featuresets):
return self._batch_classify(featuresets, ['-p', '0', '-distribution'])
def batch_classify(self, featuresets):
return self._batch_classify(featuresets, ['-p', '0'])
def _batch_classify(self, featuresets, options):
# Make sure we can find java & weka.
config_weka()
temp_dir = tempfile.mkdtemp()
try:
# Write the test data file.
test_filename = os.path.join(temp_dir, 'test.arff')
self._formatter.write(test_filename, featuresets)
# Call weka to classify the data.
cmd = ['weka.classifiers.bayes.NaiveBayes',
'-l', self._model, '-T', test_filename] + options
(stdout, stderr) = java(cmd, classpath=_weka_classpath,
stdout=subprocess.PIPE)
# Parse weka's output.
return self.parse_weka_output(stdout.split('\n'))
finally:
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir)
def parse_weka_distribution(self, s):
probs = [float(v) for v in re.split('[*,]+', s) if v.strip()]
probs = dict(zip(self._formatter.labels(), probs))
return DictionaryProbDist(probs)
def parse_weka_output(self, lines):
if lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'prediction']:
return [line.split()[2].split(':')[1]
for line in lines[1:] if line.strip()]
elif lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'distribution']:
return [self.parse_weka_distribution(line.split()[-1])
for line in lines[1:] if line.strip()]
else:
for line in lines[:10]: print line
raise ValueError('Unhandled output format -- your version '
'of weka may not be supported.\n'
' Header: %s' % lines[0])
@staticmethod
def | (model_filename, featuresets, quiet=True):
# Make sure we can find java & weka.
config_weka()
# Build an ARFF formatter.
formatter = ARFF_Formatter.from_train(featuresets)
temp_dir = tempfile.mkdtemp()
try:
# Write the training data file.
train_filename = os.path.join(temp_dir, 'train.arff')
formatter.write(train_filename, featuresets)
# Train the weka model.
cmd = ['weka.classifiers.bayes.NaiveBayes',
'-d', model_filename, '-t', train_filename]
if quiet: stdout = subprocess.PIPE
else: stdout = None
java(cmd, classpath=_weka_classpath, stdout=stdout)
# Return the new classifier.
return WekaClassifier(formatter, model_filename)
finally:
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir)
class ARFF_Formatter:
"""
Converts featuresets and labeled featuresets to ARFF-formatted
strings, appropriate for input into Weka.
"""
def __init__(self, labels, features):
"""
@param labels: A list of all labels that can be generated.
@param features: A list of feature specifications, where
each feature specification is a tuple (fname, ftype);
and ftype is an ARFF type string such as NUMERIC or
STRING.
"""
self._labels = labels
self._features = features
def format(self, tokens):
return self.header_section() + self.data_section(tokens)
def labels(self):
return list(self._labels)
def write(self, filename, tokens):
f = open(filename, 'w')
f.write(self.format(tokens))
f.close()
@staticmethod
def from_train(tokens):
# Find the set of all attested labels.
labels = set(label for (tok,label) in tokens)
# Determine the types of all features.
features = {}
for tok, label in tokens:
for (fname, fval) in tok.items():
if issubclass(type(fval), bool):
ftype = '{True, False}'
elif issubclass(type(fval), (int, float, long, bool)):
ftype = 'NUMERIC'
elif issubclass(type(fval), basestring):
ftype = 'STRING'
elif fval is None:
continue # can't tell the type.
else:
raise ValueError('Unsupported value type %r' % ftype)
if features.get(fname, ftype) != ftype:
raise ValueError('Inconsistent type for %s' % fname)
features[fname] = ftype
features = sorted(features.items())
return ARFF_Formatter(labels, features)
def header_section(self):
# Header comment.
s = ('% Weka ARFF file\n' +
'% Generated automatically by NLTK\n' +
'%% %s\n\n' % time.ctime())
# Relation name
s += '@RELATION rel\n\n'
# Input attribute specifications
for fname, ftype in self._features:
s += '@ATTRIBUTE %-30r %s\n' % (fname, ftype)
# Label attribute specification
s += '@ATTRIBUTE %-30r {%s}\n' % ('-label-', ','.join(self._labels))
return s
def data_section(self, tokens, labeled=None):
"""
@param labeled: Indicates whether the given tokens are labeled
or not. If C{None}, then the tokens will be assumed to be
labeled if the first token's value is a tuple or list.
"""
# Check if the tokens are labeled or unlabeled. If unlabeled,
# then use 'None'
if labeled is None:
labeled = tokens and isinstance(tokens[0], (tuple, list))
if not labeled:
tokens = [(tok, None) for tok in tokens]
# Data section
s = '\n@DATA\n'
for (tok, label) in tokens:
for fname, ftype in self._features:
s += '%s,' % self._fmt_arff_val(tok.get(fname))
s += '%s\n' % self._fmt_arff_val(label)
return s
def _fmt_arff_val(self, fval):
if fval is None:
return '?'
elif isinstance(fval, (bool, int, long)):
return '%s' % fval
elif isinstance(fval, float):
return '%r' % fval
else:
return '%r' % fval
if __name__ == '__main__':
from nltk.classify.util import names_demo,binary_names_demo_features
def make_classifier(featuresets):
return WekaClassifier.train('/tmp/name.model', featuresets)
classifier = names_demo(make_classifier,binary_names_demo_features)
| train | identifier_name |
weka.py | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <[email protected]>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfile, os, os.path, subprocess, re
from api import *
from nltk.probability import *
from nltk.internals import java, config_java
"""
Classifiers that make use of the external 'Weka' package.
"""
_weka_classpath = None
_weka_search = ['.',
'/usr/share/weka',
'/usr/local/share/weka',
'/usr/lib/weka',
'/usr/local/lib/weka',]
def config_weka(classpath=None):
global _weka_classpath
# Make sure java's configured first.
config_java()
if classpath is not None:
_weka_classpath = classpath
if _weka_classpath is None:
searchpath = _weka_search
if 'WEKAHOME' in os.environ:
searchpath.insert(0, os.environ['WEKAHOME'])
for path in searchpath:
if os.path.exists(os.path.join(path, 'weka.jar')):
_weka_classpath = os.path.join(path, 'weka.jar')
print '[Found Weka: %s]' % _weka_classpath
if _weka_classpath is None:
raise LookupError('Unable to find weka.jar! Use config_weka() '
'or set the WEKAHOME environment variable. '
'For more information about Weka, please see '
'http://www.cs.waikato.ac.nz/ml/weka/')
class WekaClassifier(ClassifierI):
def __init__(self, formatter, model_filename):
self._formatter = formatter
self._model = model_filename
def batch_prob_classify(self, featuresets):
return self._batch_classify(featuresets, ['-p', '0', '-distribution'])
def batch_classify(self, featuresets):
return self._batch_classify(featuresets, ['-p', '0'])
def _batch_classify(self, featuresets, options):
# Make sure we can find java & weka.
config_weka()
temp_dir = tempfile.mkdtemp()
try:
# Write the test data file.
test_filename = os.path.join(temp_dir, 'test.arff')
self._formatter.write(test_filename, featuresets)
# Call weka to classify the data.
cmd = ['weka.classifiers.bayes.NaiveBayes',
'-l', self._model, '-T', test_filename] + options
(stdout, stderr) = java(cmd, classpath=_weka_classpath,
stdout=subprocess.PIPE)
# Parse weka's output.
return self.parse_weka_output(stdout.split('\n'))
finally:
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir)
def parse_weka_distribution(self, s):
probs = [float(v) for v in re.split('[*,]+', s) if v.strip()]
probs = dict(zip(self._formatter.labels(), probs))
return DictionaryProbDist(probs)
def parse_weka_output(self, lines):
if lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'prediction']:
return [line.split()[2].split(':')[1] |
else:
for line in lines[:10]: print line
raise ValueError('Unhandled output format -- your version '
'of weka may not be supported.\n'
' Header: %s' % lines[0])
@staticmethod
def train(model_filename, featuresets, quiet=True):
# Make sure we can find java & weka.
config_weka()
# Build an ARFF formatter.
formatter = ARFF_Formatter.from_train(featuresets)
temp_dir = tempfile.mkdtemp()
try:
# Write the training data file.
train_filename = os.path.join(temp_dir, 'train.arff')
formatter.write(train_filename, featuresets)
# Train the weka model.
cmd = ['weka.classifiers.bayes.NaiveBayes',
'-d', model_filename, '-t', train_filename]
if quiet: stdout = subprocess.PIPE
else: stdout = None
java(cmd, classpath=_weka_classpath, stdout=stdout)
# Return the new classifier.
return WekaClassifier(formatter, model_filename)
finally:
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir)
class ARFF_Formatter:
"""
Converts featuresets and labeled featuresets to ARFF-formatted
strings, appropriate for input into Weka.
"""
def __init__(self, labels, features):
"""
@param labels: A list of all labels that can be generated.
@param features: A list of feature specifications, where
each feature specification is a tuple (fname, ftype);
and ftype is an ARFF type string such as NUMERIC or
STRING.
"""
self._labels = labels
self._features = features
def format(self, tokens):
return self.header_section() + self.data_section(tokens)
def labels(self):
return list(self._labels)
def write(self, filename, tokens):
f = open(filename, 'w')
f.write(self.format(tokens))
f.close()
@staticmethod
def from_train(tokens):
# Find the set of all attested labels.
labels = set(label for (tok,label) in tokens)
# Determine the types of all features.
features = {}
for tok, label in tokens:
for (fname, fval) in tok.items():
if issubclass(type(fval), bool):
ftype = '{True, False}'
elif issubclass(type(fval), (int, float, long, bool)):
ftype = 'NUMERIC'
elif issubclass(type(fval), basestring):
ftype = 'STRING'
elif fval is None:
continue # can't tell the type.
else:
raise ValueError('Unsupported value type %r' % ftype)
if features.get(fname, ftype) != ftype:
raise ValueError('Inconsistent type for %s' % fname)
features[fname] = ftype
features = sorted(features.items())
return ARFF_Formatter(labels, features)
def header_section(self):
# Header comment.
s = ('% Weka ARFF file\n' +
'% Generated automatically by NLTK\n' +
'%% %s\n\n' % time.ctime())
# Relation name
s += '@RELATION rel\n\n'
# Input attribute specifications
for fname, ftype in self._features:
s += '@ATTRIBUTE %-30r %s\n' % (fname, ftype)
# Label attribute specification
s += '@ATTRIBUTE %-30r {%s}\n' % ('-label-', ','.join(self._labels))
return s
def data_section(self, tokens, labeled=None):
"""
@param labeled: Indicates whether the given tokens are labeled
or not. If C{None}, then the tokens will be assumed to be
labeled if the first token's value is a tuple or list.
"""
# Check if the tokens are labeled or unlabeled. If unlabeled,
# then use 'None'
if labeled is None:
labeled = tokens and isinstance(tokens[0], (tuple, list))
if not labeled:
tokens = [(tok, None) for tok in tokens]
# Data section
s = '\n@DATA\n'
for (tok, label) in tokens:
for fname, ftype in self._features:
s += '%s,' % self._fmt_arff_val(tok.get(fname))
s += '%s\n' % self._fmt_arff_val(label)
return s
def _fmt_arff_val(self, fval):
if fval is None:
return '?'
elif isinstance(fval, (bool, int, long)):
return '%s' % fval
elif isinstance(fval, float):
return '%r' % fval
else:
return '%r' % fval
if __name__ == '__main__':
from nltk.classify.util import names_demo,binary_names_demo_features
def make_classifier(featuresets):
return WekaClassifier.train('/tmp/name.model', featuresets)
classifier = names_demo(make_classifier,binary_names_demo_features) | for line in lines[1:] if line.strip()]
elif lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'distribution']:
return [self.parse_weka_distribution(line.split()[-1])
for line in lines[1:] if line.strip()] | random_line_split |
weka.py | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <[email protected]>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfile, os, os.path, subprocess, re
from api import *
from nltk.probability import *
from nltk.internals import java, config_java
"""
Classifiers that make use of the external 'Weka' package.
"""
_weka_classpath = None
_weka_search = ['.',
'/usr/share/weka',
'/usr/local/share/weka',
'/usr/lib/weka',
'/usr/local/lib/weka',]
def config_weka(classpath=None):
global _weka_classpath
# Make sure java's configured first.
config_java()
if classpath is not None:
_weka_classpath = classpath
if _weka_classpath is None:
searchpath = _weka_search
if 'WEKAHOME' in os.environ:
searchpath.insert(0, os.environ['WEKAHOME'])
for path in searchpath:
if os.path.exists(os.path.join(path, 'weka.jar')):
_weka_classpath = os.path.join(path, 'weka.jar')
print '[Found Weka: %s]' % _weka_classpath
if _weka_classpath is None:
raise LookupError('Unable to find weka.jar! Use config_weka() '
'or set the WEKAHOME environment variable. '
'For more information about Weka, please see '
'http://www.cs.waikato.ac.nz/ml/weka/')
class WekaClassifier(ClassifierI):
def __init__(self, formatter, model_filename):
self._formatter = formatter
self._model = model_filename
def batch_prob_classify(self, featuresets):
return self._batch_classify(featuresets, ['-p', '0', '-distribution'])
def batch_classify(self, featuresets):
return self._batch_classify(featuresets, ['-p', '0'])
def _batch_classify(self, featuresets, options):
# Make sure we can find java & weka.
config_weka()
temp_dir = tempfile.mkdtemp()
try:
# Write the test data file.
test_filename = os.path.join(temp_dir, 'test.arff')
self._formatter.write(test_filename, featuresets)
# Call weka to classify the data.
cmd = ['weka.classifiers.bayes.NaiveBayes',
'-l', self._model, '-T', test_filename] + options
(stdout, stderr) = java(cmd, classpath=_weka_classpath,
stdout=subprocess.PIPE)
# Parse weka's output.
return self.parse_weka_output(stdout.split('\n'))
finally:
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir)
def parse_weka_distribution(self, s):
probs = [float(v) for v in re.split('[*,]+', s) if v.strip()]
probs = dict(zip(self._formatter.labels(), probs))
return DictionaryProbDist(probs)
def parse_weka_output(self, lines):
if lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'prediction']:
return [line.split()[2].split(':')[1]
for line in lines[1:] if line.strip()]
elif lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'distribution']:
return [self.parse_weka_distribution(line.split()[-1])
for line in lines[1:] if line.strip()]
else:
for line in lines[:10]: print line
raise ValueError('Unhandled output format -- your version '
'of weka may not be supported.\n'
' Header: %s' % lines[0])
@staticmethod
def train(model_filename, featuresets, quiet=True):
# Make sure we can find java & weka.
config_weka()
# Build an ARFF formatter.
formatter = ARFF_Formatter.from_train(featuresets)
temp_dir = tempfile.mkdtemp()
try:
# Write the training data file.
train_filename = os.path.join(temp_dir, 'train.arff')
formatter.write(train_filename, featuresets)
# Train the weka model.
cmd = ['weka.classifiers.bayes.NaiveBayes',
'-d', model_filename, '-t', train_filename]
if quiet: stdout = subprocess.PIPE
else: stdout = None
java(cmd, classpath=_weka_classpath, stdout=stdout)
# Return the new classifier.
return WekaClassifier(formatter, model_filename)
finally:
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir)
class ARFF_Formatter:
"""
Converts featuresets and labeled featuresets to ARFF-formatted
strings, appropriate for input into Weka.
"""
def __init__(self, labels, features):
"""
@param labels: A list of all labels that can be generated.
@param features: A list of feature specifications, where
each feature specification is a tuple (fname, ftype);
and ftype is an ARFF type string such as NUMERIC or
STRING.
"""
self._labels = labels
self._features = features
def format(self, tokens):
return self.header_section() + self.data_section(tokens)
def labels(self):
return list(self._labels)
def write(self, filename, tokens):
f = open(filename, 'w')
f.write(self.format(tokens))
f.close()
@staticmethod
def from_train(tokens):
# Find the set of all attested labels.
labels = set(label for (tok,label) in tokens)
# Determine the types of all features.
features = {}
for tok, label in tokens:
for (fname, fval) in tok.items():
if issubclass(type(fval), bool):
ftype = '{True, False}'
elif issubclass(type(fval), (int, float, long, bool)):
ftype = 'NUMERIC'
elif issubclass(type(fval), basestring):
ftype = 'STRING'
elif fval is None:
continue # can't tell the type.
else:
raise ValueError('Unsupported value type %r' % ftype)
if features.get(fname, ftype) != ftype:
raise ValueError('Inconsistent type for %s' % fname)
features[fname] = ftype
features = sorted(features.items())
return ARFF_Formatter(labels, features)
def header_section(self):
# Header comment.
s = ('% Weka ARFF file\n' +
'% Generated automatically by NLTK\n' +
'%% %s\n\n' % time.ctime())
# Relation name
s += '@RELATION rel\n\n'
# Input attribute specifications
for fname, ftype in self._features:
s += '@ATTRIBUTE %-30r %s\n' % (fname, ftype)
# Label attribute specification
s += '@ATTRIBUTE %-30r {%s}\n' % ('-label-', ','.join(self._labels))
return s
def data_section(self, tokens, labeled=None):
"""
@param labeled: Indicates whether the given tokens are labeled
or not. If C{None}, then the tokens will be assumed to be
labeled if the first token's value is a tuple or list.
"""
# Check if the tokens are labeled or unlabeled. If unlabeled,
# then use 'None'
if labeled is None:
labeled = tokens and isinstance(tokens[0], (tuple, list))
if not labeled:
tokens = [(tok, None) for tok in tokens]
# Data section
s = '\n@DATA\n'
for (tok, label) in tokens:
for fname, ftype in self._features:
|
s += '%s\n' % self._fmt_arff_val(label)
return s
def _fmt_arff_val(self, fval):
if fval is None:
return '?'
elif isinstance(fval, (bool, int, long)):
return '%s' % fval
elif isinstance(fval, float):
return '%r' % fval
else:
return '%r' % fval
if __name__ == '__main__':
from nltk.classify.util import names_demo,binary_names_demo_features
def make_classifier(featuresets):
return WekaClassifier.train('/tmp/name.model', featuresets)
classifier = names_demo(make_classifier,binary_names_demo_features)
| s += '%s,' % self._fmt_arff_val(tok.get(fname)) | conditional_block |
weka.py | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <[email protected]>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfile, os, os.path, subprocess, re
from api import *
from nltk.probability import *
from nltk.internals import java, config_java
"""
Classifiers that make use of the external 'Weka' package.
"""
_weka_classpath = None
_weka_search = ['.',
'/usr/share/weka',
'/usr/local/share/weka',
'/usr/lib/weka',
'/usr/local/lib/weka',]
def config_weka(classpath=None):
global _weka_classpath
# Make sure java's configured first.
config_java()
if classpath is not None:
_weka_classpath = classpath
if _weka_classpath is None:
searchpath = _weka_search
if 'WEKAHOME' in os.environ:
searchpath.insert(0, os.environ['WEKAHOME'])
for path in searchpath:
if os.path.exists(os.path.join(path, 'weka.jar')):
_weka_classpath = os.path.join(path, 'weka.jar')
print '[Found Weka: %s]' % _weka_classpath
if _weka_classpath is None:
raise LookupError('Unable to find weka.jar! Use config_weka() '
'or set the WEKAHOME environment variable. '
'For more information about Weka, please see '
'http://www.cs.waikato.ac.nz/ml/weka/')
class WekaClassifier(ClassifierI):
def __init__(self, formatter, model_filename):
self._formatter = formatter
self._model = model_filename
def batch_prob_classify(self, featuresets):
return self._batch_classify(featuresets, ['-p', '0', '-distribution'])
def batch_classify(self, featuresets):
return self._batch_classify(featuresets, ['-p', '0'])
def _batch_classify(self, featuresets, options):
# Make sure we can find java & weka.
config_weka()
temp_dir = tempfile.mkdtemp()
try:
# Write the test data file.
test_filename = os.path.join(temp_dir, 'test.arff')
self._formatter.write(test_filename, featuresets)
# Call weka to classify the data.
cmd = ['weka.classifiers.bayes.NaiveBayes',
'-l', self._model, '-T', test_filename] + options
(stdout, stderr) = java(cmd, classpath=_weka_classpath,
stdout=subprocess.PIPE)
# Parse weka's output.
return self.parse_weka_output(stdout.split('\n'))
finally:
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir)
def parse_weka_distribution(self, s):
probs = [float(v) for v in re.split('[*,]+', s) if v.strip()]
probs = dict(zip(self._formatter.labels(), probs))
return DictionaryProbDist(probs)
def parse_weka_output(self, lines):
if lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'prediction']:
return [line.split()[2].split(':')[1]
for line in lines[1:] if line.strip()]
elif lines[0].split() == ['inst#', 'actual', 'predicted',
'error', 'distribution']:
return [self.parse_weka_distribution(line.split()[-1])
for line in lines[1:] if line.strip()]
else:
for line in lines[:10]: print line
raise ValueError('Unhandled output format -- your version '
'of weka may not be supported.\n'
' Header: %s' % lines[0])
@staticmethod
def train(model_filename, featuresets, quiet=True):
# Make sure we can find java & weka.
|
class ARFF_Formatter:
"""
Converts featuresets and labeled featuresets to ARFF-formatted
strings, appropriate for input into Weka.
"""
def __init__(self, labels, features):
"""
@param labels: A list of all labels that can be generated.
@param features: A list of feature specifications, where
each feature specification is a tuple (fname, ftype);
and ftype is an ARFF type string such as NUMERIC or
STRING.
"""
self._labels = labels
self._features = features
def format(self, tokens):
return self.header_section() + self.data_section(tokens)
def labels(self):
return list(self._labels)
def write(self, filename, tokens):
f = open(filename, 'w')
f.write(self.format(tokens))
f.close()
@staticmethod
def from_train(tokens):
# Find the set of all attested labels.
labels = set(label for (tok,label) in tokens)
# Determine the types of all features.
features = {}
for tok, label in tokens:
for (fname, fval) in tok.items():
if issubclass(type(fval), bool):
ftype = '{True, False}'
elif issubclass(type(fval), (int, float, long, bool)):
ftype = 'NUMERIC'
elif issubclass(type(fval), basestring):
ftype = 'STRING'
elif fval is None:
continue # can't tell the type.
else:
raise ValueError('Unsupported value type %r' % ftype)
if features.get(fname, ftype) != ftype:
raise ValueError('Inconsistent type for %s' % fname)
features[fname] = ftype
features = sorted(features.items())
return ARFF_Formatter(labels, features)
def header_section(self):
# Header comment.
s = ('% Weka ARFF file\n' +
'% Generated automatically by NLTK\n' +
'%% %s\n\n' % time.ctime())
# Relation name
s += '@RELATION rel\n\n'
# Input attribute specifications
for fname, ftype in self._features:
s += '@ATTRIBUTE %-30r %s\n' % (fname, ftype)
# Label attribute specification
s += '@ATTRIBUTE %-30r {%s}\n' % ('-label-', ','.join(self._labels))
return s
def data_section(self, tokens, labeled=None):
"""
@param labeled: Indicates whether the given tokens are labeled
or not. If C{None}, then the tokens will be assumed to be
labeled if the first token's value is a tuple or list.
"""
# Check if the tokens are labeled or unlabeled. If unlabeled,
# then use 'None'
if labeled is None:
labeled = tokens and isinstance(tokens[0], (tuple, list))
if not labeled:
tokens = [(tok, None) for tok in tokens]
# Data section
s = '\n@DATA\n'
for (tok, label) in tokens:
for fname, ftype in self._features:
s += '%s,' % self._fmt_arff_val(tok.get(fname))
s += '%s\n' % self._fmt_arff_val(label)
return s
def _fmt_arff_val(self, fval):
if fval is None:
return '?'
elif isinstance(fval, (bool, int, long)):
return '%s' % fval
elif isinstance(fval, float):
return '%r' % fval
else:
return '%r' % fval
if __name__ == '__main__':
from nltk.classify.util import names_demo,binary_names_demo_features
def make_classifier(featuresets):
return WekaClassifier.train('/tmp/name.model', featuresets)
classifier = names_demo(make_classifier,binary_names_demo_features)
| config_weka()
# Build an ARFF formatter.
formatter = ARFF_Formatter.from_train(featuresets)
temp_dir = tempfile.mkdtemp()
try:
# Write the training data file.
train_filename = os.path.join(temp_dir, 'train.arff')
formatter.write(train_filename, featuresets)
# Train the weka model.
cmd = ['weka.classifiers.bayes.NaiveBayes',
'-d', model_filename, '-t', train_filename]
if quiet: stdout = subprocess.PIPE
else: stdout = None
java(cmd, classpath=_weka_classpath, stdout=stdout)
# Return the new classifier.
return WekaClassifier(formatter, model_filename)
finally:
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir) | identifier_body |
mod.rs | use std::fs;
use std::io;
pub mod cgroup_reader;
pub mod ns_reader;
pub mod process;
fn load_cgroups(procs: Vec<process::Process>) -> Vec<cgroup_reader::Reader> {
let cgroups = Vec::<cgroup_reader::Reader>::new();
for p in procs {
cgroups.push(cgroup_reader::new(p.pid));
}
cgroups
}
pub struct Container {
processes: Vec<process::Process>,
namespaces: Vec<String>,
cgroups: Vec<cgroup_reader::Reader>,
update_intv: i32
}
impl Container {
fn update(&self) |
}
pub fn new(group: ns_reader::NS_Group) -> Container {
let (namespaces, process) = group;
return Container{
processes: process,
namespaces: namespaces,
cgroups: load_cgroups(process),
update_intv: 1,
}
}
| {
loop {
for cgroup in self.cgroups {
let kvs = cgroup.read();
for kv in kvs {
let (key, val) = kv;
println!("{} : {}", key, val);
}
}
}
} | identifier_body |
mod.rs | use std::fs;
use std::io;
pub mod cgroup_reader;
pub mod ns_reader;
pub mod process;
fn load_cgroups(procs: Vec<process::Process>) -> Vec<cgroup_reader::Reader> {
let cgroups = Vec::<cgroup_reader::Reader>::new();
for p in procs {
cgroups.push(cgroup_reader::new(p.pid));
}
cgroups
}
pub struct Container {
processes: Vec<process::Process>,
namespaces: Vec<String>,
cgroups: Vec<cgroup_reader::Reader>,
update_intv: i32
}
impl Container {
fn update(&self) {
loop {
for cgroup in self.cgroups {
let kvs = cgroup.read();
for kv in kvs {
let (key, val) = kv;
println!("{} : {}", key, val);
}
}
}
}
}
pub fn | (group: ns_reader::NS_Group) -> Container {
let (namespaces, process) = group;
return Container{
processes: process,
namespaces: namespaces,
cgroups: load_cgroups(process),
update_intv: 1,
}
}
| new | identifier_name |
mod.rs | use std::fs;
use std::io;
pub mod cgroup_reader;
pub mod ns_reader;
pub mod process;
fn load_cgroups(procs: Vec<process::Process>) -> Vec<cgroup_reader::Reader> {
let cgroups = Vec::<cgroup_reader::Reader>::new();
for p in procs {
cgroups.push(cgroup_reader::new(p.pid));
}
cgroups
}
pub struct Container {
processes: Vec<process::Process>,
namespaces: Vec<String>,
cgroups: Vec<cgroup_reader::Reader>,
update_intv: i32
}
impl Container {
fn update(&self) {
loop {
for cgroup in self.cgroups {
let kvs = cgroup.read();
for kv in kvs {
let (key, val) = kv;
println!("{} : {}", key, val);
}
} | pub fn new(group: ns_reader::NS_Group) -> Container {
let (namespaces, process) = group;
return Container{
processes: process,
namespaces: namespaces,
cgroups: load_cgroups(process),
update_intv: 1,
}
} | }
}
}
| random_line_split |
interfaces.ts | import { Stats } from "fs";
import { Diagnostic } from "typescript";
import { TypescriptConfig } from "./generated/typescript-config";
export * from "./generated/typescript-config";
export type CompilerOptionsConfig = TypescriptConfig["compilerOptions"];
export interface NormalizedOptions {
workingPath: AbsolutePath;
rootPath: AbsolutePath;
projectPath: AbsolutePath;
buildPath: AbsolutePath | undefined;
configFileName: string | undefined;
rawConfig: CompilerOptionsConfig | undefined;
compilerOptions: CompilerOptionsConfig | undefined;
throwOnError: boolean;
}
export interface DiagnosticsHandler {
/**
* Check for diagnostics and handle diagnostics.
*
* Returns true if there are errors.
*/
check(
diagnostics: ReadonlyArray<Diagnostic> | Diagnostic | undefined,
throwOnError?: boolean
): boolean;
}
export interface TypescriptCompilerOptions {
/**
* Acts as the current working directory for compilation.
*
* This affects how file paths are made relative for errors reporting.
*
* Defaults to `process.cwd()`.
*/
workingPath?: string;
/**
* Used as the rootPath for relative paths within the input node.
*
* This affects type resolution for files outside the input node
* like node_modules.
*
* The input node will act as though it is mounted at this location.
*
* The rootPath must contain the emitted files, since a broccoli node
* cannot write outside of its outputPath.
*
* Defaults to options.workingPath.
*/
rootPath?: string;
/**
* Used as the starting search path for the tsconfig file or the basePath for
* config parsing if the options.tsconfig is an object.
*
* Most the time this is the same as the rootPath. The only time this is
* important is if the project writes above its directory since the rootPath
* needs to contain all emitted files.
*
* Acts like the -p option to tsc.
*
* Defaults to options.rootPath.
*/
projectPath?: string;
/**
* Used as the base for output. This should be set to your broccoli output.
*
* Your outDir should be at or beneath this path. The emitted files will be
* written to the output relative to this path.
*
* Defaults to compilerOptions.outDir (assumption is your outDir is set to where
* you place your broccoli output) or options.rootPath.
*
* Set this to where the broccoli output will go. It must contain all emitted files
* and the broccoli node output will be relative to it.
*
* If your outDir is 'dist' and your broccoli output is written to 'dist' then this
* will by default write output relative to 'dist'.
*
* If your broccoli output is written to 'dist' and your outDir is 'dist/a', then this
* should be set to 'dist' so that your emitted output will be 'a' and ultimately 'dist/a'.
*/
buildPath?: string;
/**
* The tsconfig file name search for from the projectPath
* or the JSON that would be in a tsconfig.
*
* If it is the JSON config itself, the base path will be set to the
* projectPath during parse.
*/
tsconfig?: string | TypescriptConfig;
/**
* The compilerOptions of tsconfig.
*
* This allows you to override compilerOptions in the tsconfig.
*
* This acts like if you specify --project plus additional options to tsc.
*/
compilerOptions?: CompilerOptionsConfig;
/**
* Throw if an error occurs during compilation.
*/
throwOnError?: boolean;
/**
* Broccoli node annotation.
*/
annotation?: string;
}
export interface PathInfo {
/**
* The absolute path.
*/
path: AbsolutePath;
/**
* The canonical form of the absolute path.
*/
canonicalPath: CanonicalPath;
/**
* The corresponding absolute path in the input node if within root.
*/
pathInInput: AbsolutePath | undefined;
/**
* The canonical form of `pathInInput`.
*/
canonicalPathInInput: CanonicalPath | undefined;
/**
* Path relative to root.
*/
relativePath: string | undefined;
}
/**
* An AbsolutePath is a path that has been normalized and provides the following
* guarantees:
*
* 1. The path is absolute.
* 2. Path separators have been normalized to slashes.
* 3. Any trailing slash has been removed.
*
* Generally speaking, AbsolutePaths should be preferred because they preserve
* casing, even on case-insensitive file systems. The exception is that
* CanonicalPaths should be used for things like cache keys, where the same file
* may be referred to by multiple casing permutations.
*/ | __absolutePathBrand: any;
};
/**
* A CanonicalPath is an AbsolutePath that has been canonicalized. Primarily,
* this means that in addition to the guarantees of AbsolutePath, it has also
* had casing normalized on case-insensitive file systems. This is an alias of
* `ts.Path` type.
*/
export type CanonicalPath = string & {
__pathBrand: any;
};
export interface Resolution extends PathInfo {
stats: Stats | undefined;
otherStats: Stats | undefined;
isFile(): this is FileResolution | InputFileResolution;
isDirectory(): this is DirectoryResolution | InputDirectoryResolution;
isInput(): this is InputDirectoryResolution | InputFileResolution;
isMerged(): this is MergedDirectoryResolution;
exists(): this is FileResolution | DirectoryResolution;
}
export interface FileResolution extends Resolution {
stats: Stats;
otherStats: undefined;
isFile(): this is FileResolution | InputFileResolution;
isDirectory(): false;
isInput(): this is InputFileResolution;
isMerged(): false;
}
export interface InputFileResolution extends FileResolution {
pathInInput: AbsolutePath;
relativePath: string;
isFile(): this is InputFileResolution;
}
export interface DirectoryResolution extends Resolution {
stats: Stats;
isFile(): false;
isDirectory(): this is DirectoryResolution | InputDirectoryResolution;
isInput(): this is InputDirectoryResolution;
}
export interface InputDirectoryResolution extends DirectoryResolution {
pathInInput: AbsolutePath;
canonicalPathInInput: CanonicalPath;
relativePath: string;
isFile(): false;
isDirectory(): this is InputDirectoryResolution;
}
export interface MergedDirectoryResolution extends InputDirectoryResolution {
otherStats: Stats;
}
export interface FileContent {
version: string;
buffer: Buffer;
}
export interface DirEntries {
files: string[];
directories: string[];
}
export interface CacheDelegate<K, CK, V> {
cacheKey(key: K): CK;
create(key: K): V;
}
export interface PathResolver {
resolve(path: string): Resolution;
} | export type AbsolutePath = string & { | random_line_split |
main.js | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import * as uiv from 'uiv'
import Vue2Filters from 'vue2-filters'
import VueCookies from 'vue-cookies'
import App from './App'
import VueI18n from 'vue-i18n'
import international from './i18n'
import moment from 'moment'
import uivLang from '@rundeck/ui-trellis/lib/utilities/uivi18n'
Vue.config.productionTip = false
Vue.use(Vue2Filters)
Vue.use(VueCookies)
Vue.use(uiv)
Vue.use(VueI18n)
Vue.use(VueCookies)
let messages = international.messages
let language = window._rundeck.language || 'en_US'
let locale = window._rundeck.locale || 'en_US'
let lang = window._rundeck.language || 'en'
moment.locale(locale)
// include any i18n injected in the page by the app
messages =
{
[locale]: Object.assign(
{},
uivLang[locale] || uivLang[lang] || {},
window.Messages,
messages[locale] || messages[lang] || messages['en_US'] || {}
)
}
// Create VueI18n instance with options
const i18n = new VueI18n({ |
/* eslint-disable no-new */
new Vue({
el: '#user-summary-vue',
components: {
App
},
template: '<App/>',
i18n
}) | silentTranslationWarn: true,
locale: locale, // set locale
messages // set locale messages,
}) | random_line_split |
fieldcolumn.py | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__)
class FieldColumn(ObjectColumn):
| """ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
if fieldtype is None: fieldtype = field.getTargetType()
if article is None: article = field.schema.isarticleschema
if fieldname is None: fieldname = field.fieldname
if label is None: label = field.label
ObjectColumn.__init__(self, label, fieldname, fieldtype=fieldtype)
self.field = field
self.article = article
self.valuelabels = {}
def getUnit(self, row):
return row.ca if self.article else row.cs
def getCell(self, row):
try:
val = self.getValue(row)
return val
except AttributeError, e:
log.debug("AttributeError on getting %s.%s: %s" % (row, self.field, e))
raise
return None
def getValues(self, row):
unit = self.getUnit(row)
if unit is None: return None
values = unit.values
return values
def getValue(self, row, fieldname = None):
if not fieldname: fieldname = self.field.fieldname
log.debug(">>>>>> getValue(%r, %r)" % (row, fieldname))
values = self.getValues(row)
if values is None: return None
try:
val = getattr(values, fieldname)
except AttributeError:
log.error("%r has no field %r, but it has %r" % (values, fieldname, dir(values)))
raise
log.debug(">>>>>> values=%r, fieldname=%r, --> val=%s" % (values, fieldname, val))
return val | identifier_body |
|
fieldcolumn.py | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__) | class FieldColumn(ObjectColumn):
"""ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
if fieldtype is None: fieldtype = field.getTargetType()
if article is None: article = field.schema.isarticleschema
if fieldname is None: fieldname = field.fieldname
if label is None: label = field.label
ObjectColumn.__init__(self, label, fieldname, fieldtype=fieldtype)
self.field = field
self.article = article
self.valuelabels = {}
def getUnit(self, row):
return row.ca if self.article else row.cs
def getCell(self, row):
try:
val = self.getValue(row)
return val
except AttributeError, e:
log.debug("AttributeError on getting %s.%s: %s" % (row, self.field, e))
raise
return None
def getValues(self, row):
unit = self.getUnit(row)
if unit is None: return None
values = unit.values
return values
def getValue(self, row, fieldname = None):
if not fieldname: fieldname = self.field.fieldname
log.debug(">>>>>> getValue(%r, %r)" % (row, fieldname))
values = self.getValues(row)
if values is None: return None
try:
val = getattr(values, fieldname)
except AttributeError:
log.error("%r has no field %r, but it has %r" % (values, fieldname, dir(values)))
raise
log.debug(">>>>>> values=%r, fieldname=%r, --> val=%s" % (values, fieldname, val))
return val | random_line_split |
|
fieldcolumn.py | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__)
class FieldColumn(ObjectColumn):
"""ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
if fieldtype is None: fieldtype = field.getTargetType()
if article is None: article = field.schema.isarticleschema
if fieldname is None: |
if label is None: label = field.label
ObjectColumn.__init__(self, label, fieldname, fieldtype=fieldtype)
self.field = field
self.article = article
self.valuelabels = {}
def getUnit(self, row):
return row.ca if self.article else row.cs
def getCell(self, row):
try:
val = self.getValue(row)
return val
except AttributeError, e:
log.debug("AttributeError on getting %s.%s: %s" % (row, self.field, e))
raise
return None
def getValues(self, row):
unit = self.getUnit(row)
if unit is None: return None
values = unit.values
return values
def getValue(self, row, fieldname = None):
if not fieldname: fieldname = self.field.fieldname
log.debug(">>>>>> getValue(%r, %r)" % (row, fieldname))
values = self.getValues(row)
if values is None: return None
try:
val = getattr(values, fieldname)
except AttributeError:
log.error("%r has no field %r, but it has %r" % (values, fieldname, dir(values)))
raise
log.debug(">>>>>> values=%r, fieldname=%r, --> val=%s" % (values, fieldname, val))
return val
| fieldname = field.fieldname | conditional_block |
fieldcolumn.py | from amcat.tools import toolkit
from amcat.tools.table.table3 import ObjectColumn
import logging; log = logging.getLogger(__name__)
class | (ObjectColumn):
"""ObjectColumn based on a AnnotationSchemaField"""
def __init__(self, field, article=None, fieldname=None, label=None, fieldtype=None):
if fieldtype is None: fieldtype = field.getTargetType()
if article is None: article = field.schema.isarticleschema
if fieldname is None: fieldname = field.fieldname
if label is None: label = field.label
ObjectColumn.__init__(self, label, fieldname, fieldtype=fieldtype)
self.field = field
self.article = article
self.valuelabels = {}
def getUnit(self, row):
return row.ca if self.article else row.cs
def getCell(self, row):
try:
val = self.getValue(row)
return val
except AttributeError, e:
log.debug("AttributeError on getting %s.%s: %s" % (row, self.field, e))
raise
return None
def getValues(self, row):
unit = self.getUnit(row)
if unit is None: return None
values = unit.values
return values
def getValue(self, row, fieldname = None):
if not fieldname: fieldname = self.field.fieldname
log.debug(">>>>>> getValue(%r, %r)" % (row, fieldname))
values = self.getValues(row)
if values is None: return None
try:
val = getattr(values, fieldname)
except AttributeError:
log.error("%r has no field %r, but it has %r" % (values, fieldname, dir(values)))
raise
log.debug(">>>>>> values=%r, fieldname=%r, --> val=%s" % (values, fieldname, val))
return val
| FieldColumn | identifier_name |
module-resolver.ts | 'use strict';
import * as path from 'path';
import * as ts from 'typescript';
import * as dependentFilesUtils from './get-dependent-files';
import {Change, ReplaceChange} from './change';
import {NodeHost, Host} from '../lib/ast-tools';
/**
* Rewrites import module of dependent files when the file is moved.
* Also, rewrites export module of related index file of the given file.
*/
export class ModuleResolver {
constructor(public oldFilePath: string, public newFilePath: string, public rootPath: string) {}
/**
* Changes are applied from the bottom of a file to the top.
* An array of Change instances are sorted based upon the order,
* then apply() method is called sequentially.
*
* @param changes {Change []}
* @param host {Host}
* @return Promise after all apply() method of Change class is called
* to all Change instances sequentially.
*/
applySortedChangePromise(changes: Change[], host: Host = NodeHost): Promise<void> {
return changes
.sort((currentChange, nextChange) => nextChange.order - currentChange.order)
.reduce((newChange, change) => newChange.then(() => change.apply(host)), Promise.resolve());
}
/**
* Assesses the import specifier and determines if it is a relative import.
*
* @return {boolean} boolean value if the import specifier is a relative import.
*/
isRelativeImport(importClause: dependentFilesUtils.ModuleImport): boolean {
let singleSlash = importClause.specifierText.charAt(0) === '/';
let currentDirSyntax = importClause.specifierText.slice(0, 2) === './';
let parentDirSyntax = importClause.specifierText.slice(0, 3) === '../';
return singleSlash || currentDirSyntax || parentDirSyntax;
}
/**
* Rewrites the import specifiers of all the dependent files (cases for no index file).
*
* @todo Implement the logic for rewriting imports of the dependent files when the file
* being moved has index file in its old path and/or in its new path.
*
* @return {Promise<Change[]>}
*/
resolveDependentFiles(): Promise<Change[]> {
return dependentFilesUtils.getDependentFiles(this.oldFilePath, this.rootPath)
.then((files: dependentFilesUtils.ModuleMap) => {
let changes: Change[] = [];
let fileBaseName = path.basename(this.oldFilePath, '.ts');
// Filter out the spec file associated with to-be-promoted component unit.
let relavantFiles = Object.keys(files).filter((file) => {
if (path.extname(path.basename(file, '.ts')) === '.spec') {
return path.basename(path.basename(file, '.ts'), '.spec') !== fileBaseName;
} else {
return true;
}
});
relavantFiles.forEach(file => {
let tempChanges: ReplaceChange[] = files[file]
.map(specifier => {
let componentName = path.basename(this.oldFilePath, '.ts');
let fileDir = path.dirname(file);
let changeText = path.relative(fileDir, path.join(this.newFilePath, componentName));
if (changeText.length > 0 && changeText.charAt(0) !== '.') { | changeText = `.${path.sep}${changeText}`;
};
let position = specifier.end - specifier.specifierText.length;
return new ReplaceChange(file, position - 1, specifier.specifierText, changeText);
});
changes = changes.concat(tempChanges);
});
return changes;
});
}
/**
* Rewrites the file's own relative imports after it has been moved to new path.
*
* @return {Promise<Change[]>}
*/
resolveOwnImports(): Promise<Change[]> {
return dependentFilesUtils.createTsSourceFile(this.oldFilePath)
.then((tsFile: ts.SourceFile) => dependentFilesUtils.getImportClauses(tsFile))
.then(moduleSpecifiers => {
let changes: Change[] = moduleSpecifiers
.filter(importClause => this.isRelativeImport(importClause))
.map(specifier => {
let specifierText = specifier.specifierText;
let moduleAbsolutePath = path.resolve(path.dirname(this.oldFilePath), specifierText);
let changeText = path.relative(this.newFilePath, moduleAbsolutePath);
if (changeText.length > 0 && changeText.charAt(0) !== '.') {
changeText = `.${path.sep}${changeText}`;
}
let position = specifier.end - specifier.specifierText.length;
return new ReplaceChange(this.oldFilePath, position - 1, specifierText, changeText);
});
return changes;
});
}
} | random_line_split |
|
module-resolver.ts | 'use strict';
import * as path from 'path';
import * as ts from 'typescript';
import * as dependentFilesUtils from './get-dependent-files';
import {Change, ReplaceChange} from './change';
import {NodeHost, Host} from '../lib/ast-tools';
/**
* Rewrites import module of dependent files when the file is moved.
* Also, rewrites export module of related index file of the given file.
*/
export class ModuleResolver {
constructor(public oldFilePath: string, public newFilePath: string, public rootPath: string) {}
/**
* Changes are applied from the bottom of a file to the top.
* An array of Change instances are sorted based upon the order,
* then apply() method is called sequentially.
*
* @param changes {Change []}
* @param host {Host}
* @return Promise after all apply() method of Change class is called
* to all Change instances sequentially.
*/
applySortedChangePromise(changes: Change[], host: Host = NodeHost): Promise<void> {
return changes
.sort((currentChange, nextChange) => nextChange.order - currentChange.order)
.reduce((newChange, change) => newChange.then(() => change.apply(host)), Promise.resolve());
}
/**
* Assesses the import specifier and determines if it is a relative import.
*
* @return {boolean} boolean value if the import specifier is a relative import.
*/
isRelativeImport(importClause: dependentFilesUtils.ModuleImport): boolean {
let singleSlash = importClause.specifierText.charAt(0) === '/';
let currentDirSyntax = importClause.specifierText.slice(0, 2) === './';
let parentDirSyntax = importClause.specifierText.slice(0, 3) === '../';
return singleSlash || currentDirSyntax || parentDirSyntax;
}
/**
* Rewrites the import specifiers of all the dependent files (cases for no index file).
*
* @todo Implement the logic for rewriting imports of the dependent files when the file
* being moved has index file in its old path and/or in its new path.
*
* @return {Promise<Change[]>}
*/
resolveDependentFiles(): Promise<Change[]> {
return dependentFilesUtils.getDependentFiles(this.oldFilePath, this.rootPath)
.then((files: dependentFilesUtils.ModuleMap) => {
let changes: Change[] = [];
let fileBaseName = path.basename(this.oldFilePath, '.ts');
// Filter out the spec file associated with to-be-promoted component unit.
let relavantFiles = Object.keys(files).filter((file) => {
if (path.extname(path.basename(file, '.ts')) === '.spec') | else {
return true;
}
});
relavantFiles.forEach(file => {
let tempChanges: ReplaceChange[] = files[file]
.map(specifier => {
let componentName = path.basename(this.oldFilePath, '.ts');
let fileDir = path.dirname(file);
let changeText = path.relative(fileDir, path.join(this.newFilePath, componentName));
if (changeText.length > 0 && changeText.charAt(0) !== '.') {
changeText = `.${path.sep}${changeText}`;
};
let position = specifier.end - specifier.specifierText.length;
return new ReplaceChange(file, position - 1, specifier.specifierText, changeText);
});
changes = changes.concat(tempChanges);
});
return changes;
});
}
/**
* Rewrites the file's own relative imports after it has been moved to new path.
*
* @return {Promise<Change[]>}
*/
resolveOwnImports(): Promise<Change[]> {
return dependentFilesUtils.createTsSourceFile(this.oldFilePath)
.then((tsFile: ts.SourceFile) => dependentFilesUtils.getImportClauses(tsFile))
.then(moduleSpecifiers => {
let changes: Change[] = moduleSpecifiers
.filter(importClause => this.isRelativeImport(importClause))
.map(specifier => {
let specifierText = specifier.specifierText;
let moduleAbsolutePath = path.resolve(path.dirname(this.oldFilePath), specifierText);
let changeText = path.relative(this.newFilePath, moduleAbsolutePath);
if (changeText.length > 0 && changeText.charAt(0) !== '.') {
changeText = `.${path.sep}${changeText}`;
}
let position = specifier.end - specifier.specifierText.length;
return new ReplaceChange(this.oldFilePath, position - 1, specifierText, changeText);
});
return changes;
});
}
}
| {
return path.basename(path.basename(file, '.ts'), '.spec') !== fileBaseName;
} | conditional_block |
module-resolver.ts | 'use strict';
import * as path from 'path';
import * as ts from 'typescript';
import * as dependentFilesUtils from './get-dependent-files';
import {Change, ReplaceChange} from './change';
import {NodeHost, Host} from '../lib/ast-tools';
/**
* Rewrites import module of dependent files when the file is moved.
* Also, rewrites export module of related index file of the given file.
*/
export class ModuleResolver {
constructor(public oldFilePath: string, public newFilePath: string, public rootPath: string) {}
/**
* Changes are applied from the bottom of a file to the top.
* An array of Change instances are sorted based upon the order,
* then apply() method is called sequentially.
*
* @param changes {Change []}
* @param host {Host}
* @return Promise after all apply() method of Change class is called
* to all Change instances sequentially.
*/
applySortedChangePromise(changes: Change[], host: Host = NodeHost): Promise<void> {
return changes
.sort((currentChange, nextChange) => nextChange.order - currentChange.order)
.reduce((newChange, change) => newChange.then(() => change.apply(host)), Promise.resolve());
}
/**
* Assesses the import specifier and determines if it is a relative import.
*
* @return {boolean} boolean value if the import specifier is a relative import.
*/
isRelativeImport(importClause: dependentFilesUtils.ModuleImport): boolean {
let singleSlash = importClause.specifierText.charAt(0) === '/';
let currentDirSyntax = importClause.specifierText.slice(0, 2) === './';
let parentDirSyntax = importClause.specifierText.slice(0, 3) === '../';
return singleSlash || currentDirSyntax || parentDirSyntax;
}
/**
* Rewrites the import specifiers of all the dependent files (cases for no index file).
*
* @todo Implement the logic for rewriting imports of the dependent files when the file
* being moved has index file in its old path and/or in its new path.
*
* @return {Promise<Change[]>}
*/
| (): Promise<Change[]> {
return dependentFilesUtils.getDependentFiles(this.oldFilePath, this.rootPath)
.then((files: dependentFilesUtils.ModuleMap) => {
let changes: Change[] = [];
let fileBaseName = path.basename(this.oldFilePath, '.ts');
// Filter out the spec file associated with to-be-promoted component unit.
let relavantFiles = Object.keys(files).filter((file) => {
if (path.extname(path.basename(file, '.ts')) === '.spec') {
return path.basename(path.basename(file, '.ts'), '.spec') !== fileBaseName;
} else {
return true;
}
});
relavantFiles.forEach(file => {
let tempChanges: ReplaceChange[] = files[file]
.map(specifier => {
let componentName = path.basename(this.oldFilePath, '.ts');
let fileDir = path.dirname(file);
let changeText = path.relative(fileDir, path.join(this.newFilePath, componentName));
if (changeText.length > 0 && changeText.charAt(0) !== '.') {
changeText = `.${path.sep}${changeText}`;
};
let position = specifier.end - specifier.specifierText.length;
return new ReplaceChange(file, position - 1, specifier.specifierText, changeText);
});
changes = changes.concat(tempChanges);
});
return changes;
});
}
/**
* Rewrites the file's own relative imports after it has been moved to new path.
*
* @return {Promise<Change[]>}
*/
resolveOwnImports(): Promise<Change[]> {
return dependentFilesUtils.createTsSourceFile(this.oldFilePath)
.then((tsFile: ts.SourceFile) => dependentFilesUtils.getImportClauses(tsFile))
.then(moduleSpecifiers => {
let changes: Change[] = moduleSpecifiers
.filter(importClause => this.isRelativeImport(importClause))
.map(specifier => {
let specifierText = specifier.specifierText;
let moduleAbsolutePath = path.resolve(path.dirname(this.oldFilePath), specifierText);
let changeText = path.relative(this.newFilePath, moduleAbsolutePath);
if (changeText.length > 0 && changeText.charAt(0) !== '.') {
changeText = `.${path.sep}${changeText}`;
}
let position = specifier.end - specifier.specifierText.length;
return new ReplaceChange(this.oldFilePath, position - 1, specifierText, changeText);
});
return changes;
});
}
}
| resolveDependentFiles | identifier_name |
add-keyword.modal.component.ts | import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
@Component({
moduleId: module.id,
selector: 'sd-add-keyword-modal',
styles: [],
template: ` <modal #keywordModal [size]="'sm'">
<modal-header [show-close]="false">
<h4 class="modal-title">Add A Keyword</h4>
</modal-header>
<modal-body>
<input type="text" class="form-control" [(ngModel)]="word">
</modal-body> | export class AddKeywordModalComponent {
@Input('word') word: string = '';
@Output('onAdd') onAdd : EventEmitter<string> = new EventEmitter();
@ViewChild('keywordModal') keywordmodal: ModalComponent;
/**
* Outer open method.
*/
open() {
this.keywordmodal.open();
}
/**
* Opens up the add keyword dialogue
*/
openAddKeyword() {
this.keywordmodal.open();
}
/**
* Submits a new keyword
* emits the event back to parent element
*/
submitword() {
console.log(this.word);
this.onAdd.emit(this.word);
this.keywordmodal.close();
}
} | <modal-footer>
<button type="button" class="btn btn-primary" (click)="submitword()">Submit</button>
</modal-footer>
</modal>`
}) | random_line_split |
add-keyword.modal.component.ts | import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
@Component({
moduleId: module.id,
selector: 'sd-add-keyword-modal',
styles: [],
template: ` <modal #keywordModal [size]="'sm'">
<modal-header [show-close]="false">
<h4 class="modal-title">Add A Keyword</h4>
</modal-header>
<modal-body>
<input type="text" class="form-control" [(ngModel)]="word">
</modal-body>
<modal-footer>
<button type="button" class="btn btn-primary" (click)="submitword()">Submit</button>
</modal-footer>
</modal>`
})
export class AddKeywordModalComponent {
@Input('word') word: string = '';
@Output('onAdd') onAdd : EventEmitter<string> = new EventEmitter();
@ViewChild('keywordModal') keywordmodal: ModalComponent;
/**
* Outer open method.
*/
| () {
this.keywordmodal.open();
}
/**
* Opens up the add keyword dialogue
*/
openAddKeyword() {
this.keywordmodal.open();
}
/**
* Submits a new keyword
* emits the event back to parent element
*/
submitword() {
console.log(this.word);
this.onAdd.emit(this.word);
this.keywordmodal.close();
}
}
| open | identifier_name |
utils.js | var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var chalk = require('chalk');
_.str = require('underscore.string');
_.mixin(_.str.exports());
var ngParseModule = require('ng-parse-module');
exports.JS_MARKER = "<!-- Add New Component JS Above -->";
exports.LESS_MARKER = "/* Add Component LESS Above */";
exports.ROUTE_MARKER = "/* Add New Routes Above */";
exports.STATE_MARKER = "/* Add New States Above */";
exports.addToFile = function(filename, lineToAdd, beforeMarker){
try {
var fullPath = path.resolve(process.cwd(), filename);
var fileSrc = fs.readFileSync(fullPath,'utf8');
var indexOf = fileSrc.indexOf(beforeMarker);
var lineStart = fileSrc.substring(0,indexOf).lastIndexOf('\n') + 1;
var indent = fileSrc.substring(lineStart,indexOf);
fileSrc = fileSrc.substring(0, indexOf) + lineToAdd + "\n" + indent + fileSrc.substring(indexOf);
fs.writeFileSync(fullPath, fileSrc);
} catch(e) {
throw e;
}
};
exports.processTemplates = function(name, dir, type, that, defaultDir, configName, module){
if (!defaultDir) {
defaultDir = 'templates'
}
if (!configName) {
configName = type + 'Templates';
}
var templateDirectory = path.join(path.dirname(that.resolved), defaultDir);
if(that.config.get(configName)){
templateDirectory = path.join(process.cwd(), that.config.get(configName));
}
_.chain(fs.readdirSync(templateDirectory))
.filter(function(template){
return template[0] !== '.';
})
.each(function(template){
var customTemplateName = template.replace(type, name);
var templateFile = path.join(templateDirectory, template);
//create the file in respective folder
if (_(customTemplateName).endsWith('-spec.js') ||
_(customTemplateName).endsWith('_spec.js') ||
_(customTemplateName).endsWith('-test.js') ||
_(customTemplateName).endsWith('_test.js')) {
var testDirLocation = dir.replace('app', 'test/specs');
that.template(templateFile, path.join(testDirLocation, customTemplateName));
}else{
that.template(templateFile, path.join(dir, customTemplateName));
}
//inject the file reference into index.html/app.less/etc as appropriate
exports.inject(path.join(dir, customTemplateName), that, module);
});
};
exports.inject = function(filename, that, module) {
//special case to skip unit tests
if (_(filename).endsWith('-spec.js') ||
_(filename).endsWith('_spec.js') ||
_(filename).endsWith('-test.js') ||
_(filename).endsWith('_test.js')) {
return;
}
var ext = path.extname(filename);
if (ext[0] === '.') {
ext = ext.substring(1);
}
var config = that.config.get('inject')[ext];
if (config) {
var configFile = _.template(config.file)({module:path.basename(module.file, '.js')});
var injectFileRef = filename;
if (config.relativeToModule) {
configFile = path.join(path.dirname(module.file), configFile);
injectFileRef = path.relative(path.dirname(module.file), filename);
}
//Added by Tapas to add app folder in place
if(injectFileRef.indexOf('app\\') > -1){
injectFileRef = injectFileRef.replace('app\\', '');
}
if(injectFileRef.indexOf('app/') > -1){
injectFileRef = injectFileRef.replace('app/', '');
}
injectFileRef = injectFileRef.replace(/\\/g,'/');
var lineTemplate = _.template(config.template)({filename:injectFileRef});
exports.addToFile(configFile, lineTemplate, config.marker);
that.log.writeln(chalk.green(' updating') + ' %s', path.basename(configFile));
}
};
exports.injectRoute = function(moduleFile, uirouter, name, route, routeUrl, that){
//Added by Tapas to add app folder in place
if(routeUrl.indexOf('app\\') > -1){
routeUrl = routeUrl.replace('app\\', '');
}
if(routeUrl.indexOf('app/') > -1){
routeUrl = routeUrl.replace('app/', '');
}
routeUrl = routeUrl.replace(/\\/g,'/');
if (uirouter) | else {
exports.addToFile(moduleFile,'$routeProvider.when(\''+route+'\',{templateUrl: \''+routeUrl+'\'});',exports.ROUTE_MARKER);
}
that.log.writeln(chalk.green(' updating') + ' %s',path.basename(moduleFile));
};
exports.getParentModule = function(dir){
//starting this dir, find the first module and return parsed results
if (fs.existsSync(dir)) {
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
if (path.extname(files[i]) !== '.js') {
continue;
}
var results = ngParseModule.parse(path.join(dir,files[i]));
if (results) {
return results;
}
}
}
if (fs.existsSync(path.join(dir,'.yo-rc.json'))) {
//if we're in the root of the project then bail
return;
}
return exports.getParentModule(path.join(dir,'..'));
};
exports.askForModule = function(type,that,cb){
var modules = that.config.get('modules');
var mainModule = ngParseModule.parse('app/app.js');
mainModule.primary = true;
if (!modules || modules.length === 0) {
cb.bind(that)(mainModule);
return;
}
var choices = _.pluck(modules, 'name');
//Tapas: commented as no need to show main app module in the list
//choices.unshift(mainModule.name + ' (Primary Application Module)');
var prompts = [
{
name:'module',
message:'Which module would you like to place the new ' + type + '?',
type: 'list',
choices: choices,
default: 0
}
];
that.prompt(prompts, function (props) {
var i = choices.indexOf(props.module);
var module = ngParseModule.parse(modules[i].file);
//Tapas: No more required as we are not allowing user to add anything to main module
/*if (i === 0) {
module = mainModule;
} else {
module = ngParseModule.parse(modules[i-1].file);
}*/
cb.bind(that)(module);
}.bind(that));
};
exports.askForDir = function(type, that, module, ownDir, cb){
that.module = module;
that.appname = module.name;
that.dir = path.dirname(module.file);
var configedDir = that.config.get(type + 'Directory');
if (!configedDir){
configedDir = '.';
}
var defaultDir = path.join(that.dir, configedDir,'/');
defaultDir = path.relative(process.cwd(), defaultDir);
if (ownDir) {
defaultDir = path.join(defaultDir, that.name);
}
defaultDir = path.join(defaultDir, '/');
var dirPrompt = [
{
name:'dir',
message:'Where would you like to create the '+type+' files?',
default: defaultDir,
validate: function(dir){
if (!module.primary) {
//ensure dir is in module dir or subdir of it
dir = path.resolve(dir);
if (path.relative(that.dir,dir).substring(0,2) === '..') {
return 'Files must be placed inside the module directory or a subdirectory of the module.'
}
}
return true;
}
}
];
var dirPromptCallback = function (props) {
that.dir = path.join(props.dir, '/');
var dirToCreate = that.dir;
if (ownDir){
dirToCreate = path.join(dirToCreate, '..');
}
if (!fs.existsSync(dirToCreate)) {
that.prompt([{
name:'isConfirmed',
type:'confirm',
message:chalk.cyan(dirToCreate) + ' does not exist. Create it?'
}],function(props){
if (props.isConfirmed){
cb();
} else {
that.prompt(dirPrompt, dirPromptCallback);
}
});
} else if (ownDir && fs.existsSync(that.dir)){
//if the dir exists and this type of thing generally is inside its own dir, confirm it
that.prompt([{
name:'isConfirmed',
type:'confirm',
message:chalk.cyan(that.dir) + ' already exists. Components of this type contain multiple files and are typically put inside directories of their own. Continue?'
}],function(props){
if (props.isConfirmed){
cb();
} else {
that.prompt(dirPrompt, dirPromptCallback);
}
});
} else {
cb();
}
};
that.prompt(dirPrompt, dirPromptCallback);
};
exports.askForModuleAndDir = function(type, that, ownDir, cb) {
exports.askForModule(type, that, function(module){
exports.askForDir(type, that, module, ownDir, cb);
});
};
exports.getNameArg = function(that,args){
if (args.length > 0){
that.name = args[0];
}
};
exports.addNamePrompt = function(that,prompts,type){
if (!that.name){
prompts.splice(0,0,{
name:'name',
message: 'Enter a name for the ' + type + '.',
validate: function(input){
return true;
}
});
}
}
| {
var code = '$stateProvider.state(\''+name+'\', {\n url: \''+route+'\',\n templateUrl: \''+routeUrl+'\'\n\t\t});';
exports.addToFile(moduleFile,code,exports.STATE_MARKER);
} | conditional_block |
utils.js | var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var chalk = require('chalk');
_.str = require('underscore.string');
_.mixin(_.str.exports());
var ngParseModule = require('ng-parse-module');
exports.JS_MARKER = "<!-- Add New Component JS Above -->";
exports.LESS_MARKER = "/* Add Component LESS Above */";
exports.ROUTE_MARKER = "/* Add New Routes Above */";
exports.STATE_MARKER = "/* Add New States Above */";
exports.addToFile = function(filename, lineToAdd, beforeMarker){
try {
var fullPath = path.resolve(process.cwd(), filename);
var fileSrc = fs.readFileSync(fullPath,'utf8');
var indexOf = fileSrc.indexOf(beforeMarker);
var lineStart = fileSrc.substring(0,indexOf).lastIndexOf('\n') + 1;
var indent = fileSrc.substring(lineStart,indexOf);
fileSrc = fileSrc.substring(0, indexOf) + lineToAdd + "\n" + indent + fileSrc.substring(indexOf);
fs.writeFileSync(fullPath, fileSrc);
} catch(e) {
throw e;
}
};
exports.processTemplates = function(name, dir, type, that, defaultDir, configName, module){
if (!defaultDir) {
defaultDir = 'templates'
}
if (!configName) {
configName = type + 'Templates';
}
var templateDirectory = path.join(path.dirname(that.resolved), defaultDir);
if(that.config.get(configName)){
templateDirectory = path.join(process.cwd(), that.config.get(configName));
}
_.chain(fs.readdirSync(templateDirectory))
.filter(function(template){
return template[0] !== '.';
})
.each(function(template){
var customTemplateName = template.replace(type, name);
var templateFile = path.join(templateDirectory, template);
//create the file in respective folder
if (_(customTemplateName).endsWith('-spec.js') ||
_(customTemplateName).endsWith('_spec.js') ||
_(customTemplateName).endsWith('-test.js') ||
_(customTemplateName).endsWith('_test.js')) {
var testDirLocation = dir.replace('app', 'test/specs'); | }else{
that.template(templateFile, path.join(dir, customTemplateName));
}
//inject the file reference into index.html/app.less/etc as appropriate
exports.inject(path.join(dir, customTemplateName), that, module);
});
};
exports.inject = function(filename, that, module) {
//special case to skip unit tests
if (_(filename).endsWith('-spec.js') ||
_(filename).endsWith('_spec.js') ||
_(filename).endsWith('-test.js') ||
_(filename).endsWith('_test.js')) {
return;
}
var ext = path.extname(filename);
if (ext[0] === '.') {
ext = ext.substring(1);
}
var config = that.config.get('inject')[ext];
if (config) {
var configFile = _.template(config.file)({module:path.basename(module.file, '.js')});
var injectFileRef = filename;
if (config.relativeToModule) {
configFile = path.join(path.dirname(module.file), configFile);
injectFileRef = path.relative(path.dirname(module.file), filename);
}
//Added by Tapas to add app folder in place
if(injectFileRef.indexOf('app\\') > -1){
injectFileRef = injectFileRef.replace('app\\', '');
}
if(injectFileRef.indexOf('app/') > -1){
injectFileRef = injectFileRef.replace('app/', '');
}
injectFileRef = injectFileRef.replace(/\\/g,'/');
var lineTemplate = _.template(config.template)({filename:injectFileRef});
exports.addToFile(configFile, lineTemplate, config.marker);
that.log.writeln(chalk.green(' updating') + ' %s', path.basename(configFile));
}
};
exports.injectRoute = function(moduleFile, uirouter, name, route, routeUrl, that){
//Added by Tapas to add app folder in place
if(routeUrl.indexOf('app\\') > -1){
routeUrl = routeUrl.replace('app\\', '');
}
if(routeUrl.indexOf('app/') > -1){
routeUrl = routeUrl.replace('app/', '');
}
routeUrl = routeUrl.replace(/\\/g,'/');
if (uirouter){
var code = '$stateProvider.state(\''+name+'\', {\n url: \''+route+'\',\n templateUrl: \''+routeUrl+'\'\n\t\t});';
exports.addToFile(moduleFile,code,exports.STATE_MARKER);
} else {
exports.addToFile(moduleFile,'$routeProvider.when(\''+route+'\',{templateUrl: \''+routeUrl+'\'});',exports.ROUTE_MARKER);
}
that.log.writeln(chalk.green(' updating') + ' %s',path.basename(moduleFile));
};
exports.getParentModule = function(dir){
//starting this dir, find the first module and return parsed results
if (fs.existsSync(dir)) {
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
if (path.extname(files[i]) !== '.js') {
continue;
}
var results = ngParseModule.parse(path.join(dir,files[i]));
if (results) {
return results;
}
}
}
if (fs.existsSync(path.join(dir,'.yo-rc.json'))) {
//if we're in the root of the project then bail
return;
}
return exports.getParentModule(path.join(dir,'..'));
};
exports.askForModule = function(type,that,cb){
var modules = that.config.get('modules');
var mainModule = ngParseModule.parse('app/app.js');
mainModule.primary = true;
if (!modules || modules.length === 0) {
cb.bind(that)(mainModule);
return;
}
var choices = _.pluck(modules, 'name');
//Tapas: commented as no need to show main app module in the list
//choices.unshift(mainModule.name + ' (Primary Application Module)');
var prompts = [
{
name:'module',
message:'Which module would you like to place the new ' + type + '?',
type: 'list',
choices: choices,
default: 0
}
];
that.prompt(prompts, function (props) {
var i = choices.indexOf(props.module);
var module = ngParseModule.parse(modules[i].file);
//Tapas: No more required as we are not allowing user to add anything to main module
/*if (i === 0) {
module = mainModule;
} else {
module = ngParseModule.parse(modules[i-1].file);
}*/
cb.bind(that)(module);
}.bind(that));
};
exports.askForDir = function(type, that, module, ownDir, cb){
that.module = module;
that.appname = module.name;
that.dir = path.dirname(module.file);
var configedDir = that.config.get(type + 'Directory');
if (!configedDir){
configedDir = '.';
}
var defaultDir = path.join(that.dir, configedDir,'/');
defaultDir = path.relative(process.cwd(), defaultDir);
if (ownDir) {
defaultDir = path.join(defaultDir, that.name);
}
defaultDir = path.join(defaultDir, '/');
var dirPrompt = [
{
name:'dir',
message:'Where would you like to create the '+type+' files?',
default: defaultDir,
validate: function(dir){
if (!module.primary) {
//ensure dir is in module dir or subdir of it
dir = path.resolve(dir);
if (path.relative(that.dir,dir).substring(0,2) === '..') {
return 'Files must be placed inside the module directory or a subdirectory of the module.'
}
}
return true;
}
}
];
var dirPromptCallback = function (props) {
that.dir = path.join(props.dir, '/');
var dirToCreate = that.dir;
if (ownDir){
dirToCreate = path.join(dirToCreate, '..');
}
if (!fs.existsSync(dirToCreate)) {
that.prompt([{
name:'isConfirmed',
type:'confirm',
message:chalk.cyan(dirToCreate) + ' does not exist. Create it?'
}],function(props){
if (props.isConfirmed){
cb();
} else {
that.prompt(dirPrompt, dirPromptCallback);
}
});
} else if (ownDir && fs.existsSync(that.dir)){
//if the dir exists and this type of thing generally is inside its own dir, confirm it
that.prompt([{
name:'isConfirmed',
type:'confirm',
message:chalk.cyan(that.dir) + ' already exists. Components of this type contain multiple files and are typically put inside directories of their own. Continue?'
}],function(props){
if (props.isConfirmed){
cb();
} else {
that.prompt(dirPrompt, dirPromptCallback);
}
});
} else {
cb();
}
};
that.prompt(dirPrompt, dirPromptCallback);
};
exports.askForModuleAndDir = function(type, that, ownDir, cb) {
exports.askForModule(type, that, function(module){
exports.askForDir(type, that, module, ownDir, cb);
});
};
exports.getNameArg = function(that,args){
if (args.length > 0){
that.name = args[0];
}
};
exports.addNamePrompt = function(that,prompts,type){
if (!that.name){
prompts.splice(0,0,{
name:'name',
message: 'Enter a name for the ' + type + '.',
validate: function(input){
return true;
}
});
}
} | that.template(templateFile, path.join(testDirLocation, customTemplateName)); | random_line_split |
regions-infer-invariance-due-to-decl.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::marker;
struct invariant<'a> {
marker: marker::PhantomData<*mut &'a()>
}
fn to_same_lifetime<'r>(b_isize: invariant<'r>) {
let bj: invariant<'r> = b_isize;
}
fn to_longer_lifetime<'r>(b_isize: invariant<'r>) -> invariant<'static> {
b_isize //~ ERROR mismatched types
}
fn main() | {
} | identifier_body |
|
regions-infer-invariance-due-to-decl.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // <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 std::marker;
struct invariant<'a> {
marker: marker::PhantomData<*mut &'a()>
}
fn to_same_lifetime<'r>(b_isize: invariant<'r>) {
let bj: invariant<'r> = b_isize;
}
fn to_longer_lifetime<'r>(b_isize: invariant<'r>) -> invariant<'static> {
b_isize //~ ERROR mismatched types
}
fn main() {
} | // 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 | random_line_split |
regions-infer-invariance-due-to-decl.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::marker;
struct invariant<'a> {
marker: marker::PhantomData<*mut &'a()>
}
fn to_same_lifetime<'r>(b_isize: invariant<'r>) {
let bj: invariant<'r> = b_isize;
}
fn to_longer_lifetime<'r>(b_isize: invariant<'r>) -> invariant<'static> {
b_isize //~ ERROR mismatched types
}
fn | () {
}
| main | identifier_name |
menubutton.rs | // This file is part of rgtk.
//
// rgtk 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, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A widget that shows a menu when clicked on
use gtk::{mod, ffi};
use gtk::cast::GTK_MENUBUTTON;
use gtk::ArrowType;
/// MenuButton — A widget that shows a menu when clicked on
struct_Widget!(MenuButton)
impl MenuButton {
pub fn new() -> Option<MenuButton> {
let tmp_pointer = unsafe { ffi::gtk_menu_button_new() };
check_pointer!(tmp_pointer, MenuButton)
}
pub fn set_popup<T: gtk::WidgetTrait>(&mut self, popup: &T) -> () {
unsafe {
ffi::gtk_menu_button_set_popup(GTK_MENUBUTTON(self.pointer), popup.get_widget());
}
}
pub fn set_direction(&mut self, direction: ArrowType) -> () {
unsafe {
ffi::gtk_menu_button_set_direction(GTK_MENUBUTTON(self.pointer), direction);
}
}
pub fn get_direction(&self) -> ArrowType {
unsafe {
ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.pointer))
}
}
pub fn set_align_widget<T: gtk::WidgetTrait>(&mut self, align_widget: &T) -> () {
|
impl_drop!(MenuButton)
impl_TraitWidget!(MenuButton)
impl gtk::ContainerTrait for MenuButton {}
impl gtk::ButtonTrait for MenuButton {}
impl gtk::ToggleButtonTrait for MenuButton {}
impl_widget_events!(MenuButton)
| unsafe {
ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget.get_widget())
}
}
} | identifier_body |
menubutton.rs | // This file is part of rgtk. | // rgtk 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, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A widget that shows a menu when clicked on
use gtk::{mod, ffi};
use gtk::cast::GTK_MENUBUTTON;
use gtk::ArrowType;
/// MenuButton — A widget that shows a menu when clicked on
struct_Widget!(MenuButton)
impl MenuButton {
pub fn new() -> Option<MenuButton> {
let tmp_pointer = unsafe { ffi::gtk_menu_button_new() };
check_pointer!(tmp_pointer, MenuButton)
}
pub fn set_popup<T: gtk::WidgetTrait>(&mut self, popup: &T) -> () {
unsafe {
ffi::gtk_menu_button_set_popup(GTK_MENUBUTTON(self.pointer), popup.get_widget());
}
}
pub fn set_direction(&mut self, direction: ArrowType) -> () {
unsafe {
ffi::gtk_menu_button_set_direction(GTK_MENUBUTTON(self.pointer), direction);
}
}
pub fn get_direction(&self) -> ArrowType {
unsafe {
ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.pointer))
}
}
pub fn set_align_widget<T: gtk::WidgetTrait>(&mut self, align_widget: &T) -> () {
unsafe {
ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget.get_widget())
}
}
}
impl_drop!(MenuButton)
impl_TraitWidget!(MenuButton)
impl gtk::ContainerTrait for MenuButton {}
impl gtk::ButtonTrait for MenuButton {}
impl gtk::ToggleButtonTrait for MenuButton {}
impl_widget_events!(MenuButton) | // | random_line_split |
menubutton.rs | // This file is part of rgtk.
//
// rgtk 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, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A widget that shows a menu when clicked on
use gtk::{mod, ffi};
use gtk::cast::GTK_MENUBUTTON;
use gtk::ArrowType;
/// MenuButton — A widget that shows a menu when clicked on
struct_Widget!(MenuButton)
impl MenuButton {
pub fn ne | -> Option<MenuButton> {
let tmp_pointer = unsafe { ffi::gtk_menu_button_new() };
check_pointer!(tmp_pointer, MenuButton)
}
pub fn set_popup<T: gtk::WidgetTrait>(&mut self, popup: &T) -> () {
unsafe {
ffi::gtk_menu_button_set_popup(GTK_MENUBUTTON(self.pointer), popup.get_widget());
}
}
pub fn set_direction(&mut self, direction: ArrowType) -> () {
unsafe {
ffi::gtk_menu_button_set_direction(GTK_MENUBUTTON(self.pointer), direction);
}
}
pub fn get_direction(&self) -> ArrowType {
unsafe {
ffi::gtk_menu_button_get_direction(GTK_MENUBUTTON(self.pointer))
}
}
pub fn set_align_widget<T: gtk::WidgetTrait>(&mut self, align_widget: &T) -> () {
unsafe {
ffi::gtk_menu_button_set_align_widget(GTK_MENUBUTTON(self.pointer), align_widget.get_widget())
}
}
}
impl_drop!(MenuButton)
impl_TraitWidget!(MenuButton)
impl gtk::ContainerTrait for MenuButton {}
impl gtk::ButtonTrait for MenuButton {}
impl gtk::ToggleButtonTrait for MenuButton {}
impl_widget_events!(MenuButton)
| w() | identifier_name |
pose_and_debug_publisher.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def pose_publisher():
rospy.init_node('zaber_stage_pose_and_debug_publisher')
rospy.loginfo('zaber_stage pose_and_debug_publisher...')
rate = rospy.Rate(4)
pub_pose = rospy.Publisher('/zaber_stage_node/pose',Pose,queue_size=10)
pub_pose_and_debug = rospy.Publisher('/zaber_stage_node/pose_and_debug_info',PoseAndDebugInfo,queue_size=10)
rospy.wait_for_service('/zaber_stage_node/get_pose_and_debug_info')
get_pose_and_debug_info = rospy.ServiceProxy('/zaber_stage_node/get_pose_and_debug_info',GetPoseAndDebugInfo,persistent=True)
while not rospy.is_shutdown():
try:
response = get_pose_and_debug_info() | except rospy.ServiceException, e:
rospy.logwarn('zaber_stage pose_and_debug_publisher service call failed! %s'%e)
print "Service call failed: %s"%e
rate.sleep()
if __name__ == '__main__':
try:
pose_publisher()
except rospy.ROSInterruptException:
pass | if not response.pose_and_debug_info.zaber_response_error:
pub_pose.publish(response.pose_and_debug_info.pose)
pub_pose_and_debug.publish(response.pose_and_debug_info) | random_line_split |
pose_and_debug_publisher.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def pose_publisher():
rospy.init_node('zaber_stage_pose_and_debug_publisher')
rospy.loginfo('zaber_stage pose_and_debug_publisher...')
rate = rospy.Rate(4)
pub_pose = rospy.Publisher('/zaber_stage_node/pose',Pose,queue_size=10)
pub_pose_and_debug = rospy.Publisher('/zaber_stage_node/pose_and_debug_info',PoseAndDebugInfo,queue_size=10)
rospy.wait_for_service('/zaber_stage_node/get_pose_and_debug_info')
get_pose_and_debug_info = rospy.ServiceProxy('/zaber_stage_node/get_pose_and_debug_info',GetPoseAndDebugInfo,persistent=True)
while not rospy.is_shutdown():
try:
response = get_pose_and_debug_info()
if not response.pose_and_debug_info.zaber_response_error:
pub_pose.publish(response.pose_and_debug_info.pose)
pub_pose_and_debug.publish(response.pose_and_debug_info)
except rospy.ServiceException, e:
rospy.logwarn('zaber_stage pose_and_debug_publisher service call failed! %s'%e)
print "Service call failed: %s"%e
rate.sleep()
if __name__ == '__main__':
| try:
pose_publisher()
except rospy.ROSInterruptException:
pass | conditional_block |
|
pose_and_debug_publisher.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def pose_publisher():
|
if __name__ == '__main__':
try:
pose_publisher()
except rospy.ROSInterruptException:
pass
| rospy.init_node('zaber_stage_pose_and_debug_publisher')
rospy.loginfo('zaber_stage pose_and_debug_publisher...')
rate = rospy.Rate(4)
pub_pose = rospy.Publisher('/zaber_stage_node/pose',Pose,queue_size=10)
pub_pose_and_debug = rospy.Publisher('/zaber_stage_node/pose_and_debug_info',PoseAndDebugInfo,queue_size=10)
rospy.wait_for_service('/zaber_stage_node/get_pose_and_debug_info')
get_pose_and_debug_info = rospy.ServiceProxy('/zaber_stage_node/get_pose_and_debug_info',GetPoseAndDebugInfo,persistent=True)
while not rospy.is_shutdown():
try:
response = get_pose_and_debug_info()
if not response.pose_and_debug_info.zaber_response_error:
pub_pose.publish(response.pose_and_debug_info.pose)
pub_pose_and_debug.publish(response.pose_and_debug_info)
except rospy.ServiceException, e:
rospy.logwarn('zaber_stage pose_and_debug_publisher service call failed! %s'%e)
print "Service call failed: %s"%e
rate.sleep() | identifier_body |
pose_and_debug_publisher.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import roslib; roslib.load_manifest('zaber_stage')
import rospy
import actionlib
from geometry_msgs.msg import Pose
from zaber_stage.msg import PoseAndDebugInfo
from zaber_stage.srv import GetPoseAndDebugInfo,GetPoseAndDebugInfoResponse
def | ():
rospy.init_node('zaber_stage_pose_and_debug_publisher')
rospy.loginfo('zaber_stage pose_and_debug_publisher...')
rate = rospy.Rate(4)
pub_pose = rospy.Publisher('/zaber_stage_node/pose',Pose,queue_size=10)
pub_pose_and_debug = rospy.Publisher('/zaber_stage_node/pose_and_debug_info',PoseAndDebugInfo,queue_size=10)
rospy.wait_for_service('/zaber_stage_node/get_pose_and_debug_info')
get_pose_and_debug_info = rospy.ServiceProxy('/zaber_stage_node/get_pose_and_debug_info',GetPoseAndDebugInfo,persistent=True)
while not rospy.is_shutdown():
try:
response = get_pose_and_debug_info()
if not response.pose_and_debug_info.zaber_response_error:
pub_pose.publish(response.pose_and_debug_info.pose)
pub_pose_and_debug.publish(response.pose_and_debug_info)
except rospy.ServiceException, e:
rospy.logwarn('zaber_stage pose_and_debug_publisher service call failed! %s'%e)
print "Service call failed: %s"%e
rate.sleep()
if __name__ == '__main__':
try:
pose_publisher()
except rospy.ROSInterruptException:
pass
| pose_publisher | identifier_name |
DirectoryMemory.py | # Copyright (c) 2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Copyright (c) 2009 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Steve Reinhardt
# Brad Beckmann
from m5.params import *
from m5.proxy import *
from m5.SimObject import SimObject
class | (SimObject):
type = 'RubyDirectoryMemory'
cxx_class = 'DirectoryMemory'
cxx_header = "mem/ruby/structures/DirectoryMemory.hh"
addr_ranges = VectorParam.AddrRange(
Parent.addr_ranges, "Address range this directory responds to")
| RubyDirectoryMemory | identifier_name |
DirectoryMemory.py | # Copyright (c) 2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Copyright (c) 2009 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Steve Reinhardt
# Brad Beckmann
from m5.params import * | from m5.proxy import *
from m5.SimObject import SimObject
class RubyDirectoryMemory(SimObject):
type = 'RubyDirectoryMemory'
cxx_class = 'DirectoryMemory'
cxx_header = "mem/ruby/structures/DirectoryMemory.hh"
addr_ranges = VectorParam.AddrRange(
Parent.addr_ranges, "Address range this directory responds to") | random_line_split |
|
DirectoryMemory.py | # Copyright (c) 2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Copyright (c) 2009 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Steve Reinhardt
# Brad Beckmann
from m5.params import *
from m5.proxy import *
from m5.SimObject import SimObject
class RubyDirectoryMemory(SimObject):
| type = 'RubyDirectoryMemory'
cxx_class = 'DirectoryMemory'
cxx_header = "mem/ruby/structures/DirectoryMemory.hh"
addr_ranges = VectorParam.AddrRange(
Parent.addr_ranges, "Address range this directory responds to") | identifier_body |
|
error.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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. | #[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "Invalid bind specification '{}'", _0)]
InvalidBindSpec(String),
#[fail(display = "Invalid topology '{}'. Possible values: standalone, leader", _0)]
InvalidTopology(String),
#[fail(display = "Invalid binding \"{}\", must be of the form <NAME>:<SERVICE_GROUP> where \
<NAME> is a service name and <SERVICE_GROUP> is a valid service group",
_0)]
InvalidBinding(String),
#[fail(display = "{}", _0)]
HabitatCore(hcore::Error),
}
impl From<hcore::Error> for Error {
fn from(err: hcore::Error) -> Error {
Error::HabitatCore(err)
}
} | // See the License for the specific language governing permissions and
// limitations under the License.
use hcore;
| random_line_split |
error.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// 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.
use hcore;
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "Invalid bind specification '{}'", _0)]
InvalidBindSpec(String),
#[fail(display = "Invalid topology '{}'. Possible values: standalone, leader", _0)]
InvalidTopology(String),
#[fail(display = "Invalid binding \"{}\", must be of the form <NAME>:<SERVICE_GROUP> where \
<NAME> is a service name and <SERVICE_GROUP> is a valid service group",
_0)]
InvalidBinding(String),
#[fail(display = "{}", _0)]
HabitatCore(hcore::Error),
}
impl From<hcore::Error> for Error {
fn | (err: hcore::Error) -> Error {
Error::HabitatCore(err)
}
}
| from | identifier_name |
DynamoTable.py | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the definition (see demo/sample_reservation.yml)',
'state': 'table can be in two states: present (it is the default state) or absent'
}
required_params = ( 'name', 'source' )
required_configs = ('user', 'branch')
task_name = 'dynamo-table'
def __str__(self):
if self.name:
return self.name
else:
return "Create a table '%s' from '%s'" % (self.params['name'], os.path.abspath(self.params['source']))
def run(self, clients, cache):
client = clients.get('dynamodb')
table_name = name_constructor.table_name(self.params['name'], self.config)
if 'state' in self.params and self.params['state'] == 'absent':
return self.make_table_absent(client, table_name)
else:
return self.make_table_present(client, table_name)
def make_table_absent(self, client, table_name):
try:
table_def = client.describe_table(TableName=table_name)['Table']
except botocore.exceptions.ClientError as e:
return (True, '')
self.wait_for_table(client, table_name)
client.delete_table(TableName=table_name)
return (True, self.CHANGED)
def make_table_present(self, client, table_name):
try:
new_def = yaml.load(open(self.params['source']).read())
except Exception as e:
return (False, str(e))
try:
table_def = client.describe_table(TableName=table_name)['Table']
except botocore.exceptions.ClientError as e:
return self.create(client, table_name, new_def)
request = self.build_update_request(table_def, new_def)
if not request:
return (True, '')
self.process_update_request(client, request, table_name)
return (True, self.CHANGED)
def process_update_request(self, client, request, table_name):
if 'GlobalSecondaryIndexUpdates' in request:
for index_request in request['GlobalSecondaryIndexUpdates']:
new_request = { 'TableName': table_name, 'AttributeDefinitions': request['AttributeDefinitions'], 'GlobalSecondaryIndexUpdates': [index_request]}
self.modify_table(client, new_request, table_name)
if 'ProvisionedThroughput' in request:
new_request = { 'TableName': table_name, 'ProvisionedThroughput': request['ProvisionedThroughput'] }
self.modify_table(client, new_request, table_name)
def wait_for_table(self, client, table_name):
def rotate(t):
# animation = ('|', '\\', '-', '/')
animation = (':.. ', '.:. ', '..: ', '.:. ')
sys.stdout.write('\b'*len(animation)+animation[t % len(animation)])
sys.stdout.flush()
retry = 600
sys.stdout.write('\r')
while True:
table_def = client.describe_table(TableName=table_name)['Table']
busy_reason = self.table_busy_reason(table_def)
if busy_reason == '':
break
retry -= 1
if retry < 1:
raise Exception("%s too long." % busy_reason)
rotate(retry)
time.sleep(1)
def modify_table(self, client, request, table_name):
|
def table_busy_reason(self, table_def):
if table_def['TableStatus'] != 'ACTIVE':
return 'Table is in state %s' % table_def['TableStatus']
if 'GlobalSecondaryIndexes' in table_def:
for index in table_def['GlobalSecondaryIndexes']:
if index['IndexStatus'] != 'ACTIVE':
return 'Index %s is in state %s' % (index['IndexName'], index['IndexStatus'])
return ''
def build_update_request(self, table_def, new_def):
request = {}
old_indexes = self.get_indexes_by_name(self.construct_secondary_indexes(table_def['GlobalSecondaryIndexes']))
new_indexes = self.get_indexes_by_name(self.construct_secondary_indexes(new_def['GlobalSecondaryIndexes']))
updates = []
for index_name in old_indexes:
if index_name not in new_indexes:
updates.append({ 'Delete': { 'IndexName': index_name }})
for (index_name, index) in new_indexes.iteritems():
if index_name in old_indexes:
if index != old_indexes[index_name]:
updates.append({ 'Delete': { 'IndexName': index_name }})
updates.append({ 'Create': index})
else:
updates.append({ 'Create': index})
if updates:
request['GlobalSecondaryIndexUpdates'] = updates
request['AttributeDefinitions'] = new_def['AttributeDefinitions']
old_provisioning = self.construct_provisioned_throughput(table_def['ProvisionedThroughput'])
new_provisioning = self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
if old_provisioning != new_provisioning:
request['ProvisionedThroughput'] = new_provisioning
return request
def get_indexes_by_name(self, indexes):
out = {}
for index in indexes:
out[index['IndexName']] = index
return out
def construct_provisioned_throughput(self, idef):
return {
'ReadCapacityUnits': idef['ReadCapacityUnits'],
'WriteCapacityUnits': idef['WriteCapacityUnits']
}
def construct_secondary_indexes(self, idefs):
outs = []
for idef in idefs:
out = {
'IndexName': idef['IndexName'],
'KeySchema': idef['KeySchema'],
'Projection': idef['Projection']
}
if 'ProvisionedThroughput' in idef:
out['ProvisionedThroughput'] = self.construct_provisioned_throughput(idef['ProvisionedThroughput'])
outs.append(out)
return outs
def create(self, client, table_name, new_def):
params = {
'AttributeDefinitions': new_def['AttributeDefinitions'],
'TableName': table_name,
'KeySchema': new_def['KeySchema'] if 'KeySchema' in new_def else [],
'ProvisionedThroughput': self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
}
if 'LocalSecondaryIndexes' in new_def:
params['LocalSecondaryIndexes'] = self.construct_secondary_indexes(new_def['LocalSecondaryIndexes'])
if 'GlobalSecondaryIndexes' in new_def:
params['GlobalSecondaryIndexes'] = self.construct_secondary_indexes(new_def['GlobalSecondaryIndexes'])
if 'StreamSpecification' in new_def:
params['StreamSpecification'] = new_def['StreamSpecification']
try:
client.create_table(**params)
except botocore.exceptions.ClientError as e:
return (False, str(e))
return (True, self.CREATED)
| self.wait_for_table(client, table_name)
client.update_table(**request) | identifier_body |
DynamoTable.py | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the definition (see demo/sample_reservation.yml)',
'state': 'table can be in two states: present (it is the default state) or absent'
}
required_params = ( 'name', 'source' )
required_configs = ('user', 'branch')
task_name = 'dynamo-table'
def __str__(self):
if self.name:
return self.name
else:
return "Create a table '%s' from '%s'" % (self.params['name'], os.path.abspath(self.params['source']))
def run(self, clients, cache):
client = clients.get('dynamodb')
table_name = name_constructor.table_name(self.params['name'], self.config)
if 'state' in self.params and self.params['state'] == 'absent':
return self.make_table_absent(client, table_name)
else:
return self.make_table_present(client, table_name)
def make_table_absent(self, client, table_name):
try:
table_def = client.describe_table(TableName=table_name)['Table']
except botocore.exceptions.ClientError as e:
return (True, '')
self.wait_for_table(client, table_name)
client.delete_table(TableName=table_name)
return (True, self.CHANGED)
def make_table_present(self, client, table_name):
try:
new_def = yaml.load(open(self.params['source']).read())
except Exception as e:
return (False, str(e))
try:
table_def = client.describe_table(TableName=table_name)['Table']
except botocore.exceptions.ClientError as e:
return self.create(client, table_name, new_def)
request = self.build_update_request(table_def, new_def)
if not request:
return (True, '')
self.process_update_request(client, request, table_name)
return (True, self.CHANGED)
def process_update_request(self, client, request, table_name):
if 'GlobalSecondaryIndexUpdates' in request:
for index_request in request['GlobalSecondaryIndexUpdates']:
new_request = { 'TableName': table_name, 'AttributeDefinitions': request['AttributeDefinitions'], 'GlobalSecondaryIndexUpdates': [index_request]}
self.modify_table(client, new_request, table_name)
if 'ProvisionedThroughput' in request:
new_request = { 'TableName': table_name, 'ProvisionedThroughput': request['ProvisionedThroughput'] }
self.modify_table(client, new_request, table_name)
def wait_for_table(self, client, table_name):
def rotate(t):
# animation = ('|', '\\', '-', '/')
animation = (':.. ', '.:. ', '..: ', '.:. ')
sys.stdout.write('\b'*len(animation)+animation[t % len(animation)])
sys.stdout.flush()
retry = 600
sys.stdout.write('\r')
while True:
table_def = client.describe_table(TableName=table_name)['Table']
busy_reason = self.table_busy_reason(table_def)
if busy_reason == '':
break
retry -= 1
if retry < 1:
raise Exception("%s too long." % busy_reason)
rotate(retry)
time.sleep(1)
def modify_table(self, client, request, table_name):
self.wait_for_table(client, table_name)
client.update_table(**request)
def table_busy_reason(self, table_def):
if table_def['TableStatus'] != 'ACTIVE':
return 'Table is in state %s' % table_def['TableStatus']
if 'GlobalSecondaryIndexes' in table_def:
for index in table_def['GlobalSecondaryIndexes']:
if index['IndexStatus'] != 'ACTIVE':
return 'Index %s is in state %s' % (index['IndexName'], index['IndexStatus'])
return ''
def build_update_request(self, table_def, new_def):
request = {}
old_indexes = self.get_indexes_by_name(self.construct_secondary_indexes(table_def['GlobalSecondaryIndexes']))
new_indexes = self.get_indexes_by_name(self.construct_secondary_indexes(new_def['GlobalSecondaryIndexes']))
updates = []
for index_name in old_indexes:
if index_name not in new_indexes:
updates.append({ 'Delete': { 'IndexName': index_name }})
for (index_name, index) in new_indexes.iteritems():
if index_name in old_indexes:
if index != old_indexes[index_name]:
updates.append({ 'Delete': { 'IndexName': index_name }})
updates.append({ 'Create': index})
else:
updates.append({ 'Create': index})
if updates:
request['GlobalSecondaryIndexUpdates'] = updates
request['AttributeDefinitions'] = new_def['AttributeDefinitions']
old_provisioning = self.construct_provisioned_throughput(table_def['ProvisionedThroughput'])
new_provisioning = self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
if old_provisioning != new_provisioning:
request['ProvisionedThroughput'] = new_provisioning
return request
def get_indexes_by_name(self, indexes):
out = {}
for index in indexes:
out[index['IndexName']] = index
return out
def construct_provisioned_throughput(self, idef):
return {
'ReadCapacityUnits': idef['ReadCapacityUnits'],
'WriteCapacityUnits': idef['WriteCapacityUnits']
}
def construct_secondary_indexes(self, idefs):
outs = []
for idef in idefs:
out = {
'IndexName': idef['IndexName'],
'KeySchema': idef['KeySchema'],
'Projection': idef['Projection']
}
if 'ProvisionedThroughput' in idef:
out['ProvisionedThroughput'] = self.construct_provisioned_throughput(idef['ProvisionedThroughput'])
outs.append(out)
return outs
| params = {
'AttributeDefinitions': new_def['AttributeDefinitions'],
'TableName': table_name,
'KeySchema': new_def['KeySchema'] if 'KeySchema' in new_def else [],
'ProvisionedThroughput': self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
}
if 'LocalSecondaryIndexes' in new_def:
params['LocalSecondaryIndexes'] = self.construct_secondary_indexes(new_def['LocalSecondaryIndexes'])
if 'GlobalSecondaryIndexes' in new_def:
params['GlobalSecondaryIndexes'] = self.construct_secondary_indexes(new_def['GlobalSecondaryIndexes'])
if 'StreamSpecification' in new_def:
params['StreamSpecification'] = new_def['StreamSpecification']
try:
client.create_table(**params)
except botocore.exceptions.ClientError as e:
return (False, str(e))
return (True, self.CREATED) | def create(self, client, table_name, new_def): | random_line_split |
DynamoTable.py | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the definition (see demo/sample_reservation.yml)',
'state': 'table can be in two states: present (it is the default state) or absent'
}
required_params = ( 'name', 'source' )
required_configs = ('user', 'branch')
task_name = 'dynamo-table'
def __str__(self):
if self.name:
return self.name
else:
return "Create a table '%s' from '%s'" % (self.params['name'], os.path.abspath(self.params['source']))
def run(self, clients, cache):
client = clients.get('dynamodb')
table_name = name_constructor.table_name(self.params['name'], self.config)
if 'state' in self.params and self.params['state'] == 'absent':
return self.make_table_absent(client, table_name)
else:
return self.make_table_present(client, table_name)
def make_table_absent(self, client, table_name):
try:
table_def = client.describe_table(TableName=table_name)['Table']
except botocore.exceptions.ClientError as e:
return (True, '')
self.wait_for_table(client, table_name)
client.delete_table(TableName=table_name)
return (True, self.CHANGED)
def make_table_present(self, client, table_name):
try:
new_def = yaml.load(open(self.params['source']).read())
except Exception as e:
return (False, str(e))
try:
table_def = client.describe_table(TableName=table_name)['Table']
except botocore.exceptions.ClientError as e:
return self.create(client, table_name, new_def)
request = self.build_update_request(table_def, new_def)
if not request:
return (True, '')
self.process_update_request(client, request, table_name)
return (True, self.CHANGED)
def process_update_request(self, client, request, table_name):
if 'GlobalSecondaryIndexUpdates' in request:
for index_request in request['GlobalSecondaryIndexUpdates']:
new_request = { 'TableName': table_name, 'AttributeDefinitions': request['AttributeDefinitions'], 'GlobalSecondaryIndexUpdates': [index_request]}
self.modify_table(client, new_request, table_name)
if 'ProvisionedThroughput' in request:
new_request = { 'TableName': table_name, 'ProvisionedThroughput': request['ProvisionedThroughput'] }
self.modify_table(client, new_request, table_name)
def wait_for_table(self, client, table_name):
def rotate(t):
# animation = ('|', '\\', '-', '/')
animation = (':.. ', '.:. ', '..: ', '.:. ')
sys.stdout.write('\b'*len(animation)+animation[t % len(animation)])
sys.stdout.flush()
retry = 600
sys.stdout.write('\r')
while True:
table_def = client.describe_table(TableName=table_name)['Table']
busy_reason = self.table_busy_reason(table_def)
if busy_reason == '':
break
retry -= 1
if retry < 1:
raise Exception("%s too long." % busy_reason)
rotate(retry)
time.sleep(1)
def modify_table(self, client, request, table_name):
self.wait_for_table(client, table_name)
client.update_table(**request)
def table_busy_reason(self, table_def):
if table_def['TableStatus'] != 'ACTIVE':
return 'Table is in state %s' % table_def['TableStatus']
if 'GlobalSecondaryIndexes' in table_def:
for index in table_def['GlobalSecondaryIndexes']:
if index['IndexStatus'] != 'ACTIVE':
return 'Index %s is in state %s' % (index['IndexName'], index['IndexStatus'])
return ''
def build_update_request(self, table_def, new_def):
request = {}
old_indexes = self.get_indexes_by_name(self.construct_secondary_indexes(table_def['GlobalSecondaryIndexes']))
new_indexes = self.get_indexes_by_name(self.construct_secondary_indexes(new_def['GlobalSecondaryIndexes']))
updates = []
for index_name in old_indexes:
if index_name not in new_indexes:
updates.append({ 'Delete': { 'IndexName': index_name }})
for (index_name, index) in new_indexes.iteritems():
if index_name in old_indexes:
if index != old_indexes[index_name]:
updates.append({ 'Delete': { 'IndexName': index_name }})
updates.append({ 'Create': index})
else:
updates.append({ 'Create': index})
if updates:
request['GlobalSecondaryIndexUpdates'] = updates
request['AttributeDefinitions'] = new_def['AttributeDefinitions']
old_provisioning = self.construct_provisioned_throughput(table_def['ProvisionedThroughput'])
new_provisioning = self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
if old_provisioning != new_provisioning:
request['ProvisionedThroughput'] = new_provisioning
return request
def get_indexes_by_name(self, indexes):
out = {}
for index in indexes:
out[index['IndexName']] = index
return out
def construct_provisioned_throughput(self, idef):
return {
'ReadCapacityUnits': idef['ReadCapacityUnits'],
'WriteCapacityUnits': idef['WriteCapacityUnits']
}
def | (self, idefs):
outs = []
for idef in idefs:
out = {
'IndexName': idef['IndexName'],
'KeySchema': idef['KeySchema'],
'Projection': idef['Projection']
}
if 'ProvisionedThroughput' in idef:
out['ProvisionedThroughput'] = self.construct_provisioned_throughput(idef['ProvisionedThroughput'])
outs.append(out)
return outs
def create(self, client, table_name, new_def):
params = {
'AttributeDefinitions': new_def['AttributeDefinitions'],
'TableName': table_name,
'KeySchema': new_def['KeySchema'] if 'KeySchema' in new_def else [],
'ProvisionedThroughput': self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
}
if 'LocalSecondaryIndexes' in new_def:
params['LocalSecondaryIndexes'] = self.construct_secondary_indexes(new_def['LocalSecondaryIndexes'])
if 'GlobalSecondaryIndexes' in new_def:
params['GlobalSecondaryIndexes'] = self.construct_secondary_indexes(new_def['GlobalSecondaryIndexes'])
if 'StreamSpecification' in new_def:
params['StreamSpecification'] = new_def['StreamSpecification']
try:
client.create_table(**params)
except botocore.exceptions.ClientError as e:
return (False, str(e))
return (True, self.CREATED)
| construct_secondary_indexes | identifier_name |
DynamoTable.py | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the definition (see demo/sample_reservation.yml)',
'state': 'table can be in two states: present (it is the default state) or absent'
}
required_params = ( 'name', 'source' )
required_configs = ('user', 'branch')
task_name = 'dynamo-table'
def __str__(self):
if self.name:
return self.name
else:
return "Create a table '%s' from '%s'" % (self.params['name'], os.path.abspath(self.params['source']))
def run(self, clients, cache):
client = clients.get('dynamodb')
table_name = name_constructor.table_name(self.params['name'], self.config)
if 'state' in self.params and self.params['state'] == 'absent':
return self.make_table_absent(client, table_name)
else:
return self.make_table_present(client, table_name)
def make_table_absent(self, client, table_name):
try:
table_def = client.describe_table(TableName=table_name)['Table']
except botocore.exceptions.ClientError as e:
return (True, '')
self.wait_for_table(client, table_name)
client.delete_table(TableName=table_name)
return (True, self.CHANGED)
def make_table_present(self, client, table_name):
try:
new_def = yaml.load(open(self.params['source']).read())
except Exception as e:
return (False, str(e))
try:
table_def = client.describe_table(TableName=table_name)['Table']
except botocore.exceptions.ClientError as e:
return self.create(client, table_name, new_def)
request = self.build_update_request(table_def, new_def)
if not request:
return (True, '')
self.process_update_request(client, request, table_name)
return (True, self.CHANGED)
def process_update_request(self, client, request, table_name):
if 'GlobalSecondaryIndexUpdates' in request:
for index_request in request['GlobalSecondaryIndexUpdates']:
new_request = { 'TableName': table_name, 'AttributeDefinitions': request['AttributeDefinitions'], 'GlobalSecondaryIndexUpdates': [index_request]}
self.modify_table(client, new_request, table_name)
if 'ProvisionedThroughput' in request:
new_request = { 'TableName': table_name, 'ProvisionedThroughput': request['ProvisionedThroughput'] }
self.modify_table(client, new_request, table_name)
def wait_for_table(self, client, table_name):
def rotate(t):
# animation = ('|', '\\', '-', '/')
animation = (':.. ', '.:. ', '..: ', '.:. ')
sys.stdout.write('\b'*len(animation)+animation[t % len(animation)])
sys.stdout.flush()
retry = 600
sys.stdout.write('\r')
while True:
table_def = client.describe_table(TableName=table_name)['Table']
busy_reason = self.table_busy_reason(table_def)
if busy_reason == '':
break
retry -= 1
if retry < 1:
raise Exception("%s too long." % busy_reason)
rotate(retry)
time.sleep(1)
def modify_table(self, client, request, table_name):
self.wait_for_table(client, table_name)
client.update_table(**request)
def table_busy_reason(self, table_def):
if table_def['TableStatus'] != 'ACTIVE':
return 'Table is in state %s' % table_def['TableStatus']
if 'GlobalSecondaryIndexes' in table_def:
for index in table_def['GlobalSecondaryIndexes']:
if index['IndexStatus'] != 'ACTIVE':
return 'Index %s is in state %s' % (index['IndexName'], index['IndexStatus'])
return ''
def build_update_request(self, table_def, new_def):
request = {}
old_indexes = self.get_indexes_by_name(self.construct_secondary_indexes(table_def['GlobalSecondaryIndexes']))
new_indexes = self.get_indexes_by_name(self.construct_secondary_indexes(new_def['GlobalSecondaryIndexes']))
updates = []
for index_name in old_indexes:
if index_name not in new_indexes:
updates.append({ 'Delete': { 'IndexName': index_name }})
for (index_name, index) in new_indexes.iteritems():
if index_name in old_indexes:
if index != old_indexes[index_name]:
updates.append({ 'Delete': { 'IndexName': index_name }})
updates.append({ 'Create': index})
else:
|
if updates:
request['GlobalSecondaryIndexUpdates'] = updates
request['AttributeDefinitions'] = new_def['AttributeDefinitions']
old_provisioning = self.construct_provisioned_throughput(table_def['ProvisionedThroughput'])
new_provisioning = self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
if old_provisioning != new_provisioning:
request['ProvisionedThroughput'] = new_provisioning
return request
def get_indexes_by_name(self, indexes):
out = {}
for index in indexes:
out[index['IndexName']] = index
return out
def construct_provisioned_throughput(self, idef):
return {
'ReadCapacityUnits': idef['ReadCapacityUnits'],
'WriteCapacityUnits': idef['WriteCapacityUnits']
}
def construct_secondary_indexes(self, idefs):
outs = []
for idef in idefs:
out = {
'IndexName': idef['IndexName'],
'KeySchema': idef['KeySchema'],
'Projection': idef['Projection']
}
if 'ProvisionedThroughput' in idef:
out['ProvisionedThroughput'] = self.construct_provisioned_throughput(idef['ProvisionedThroughput'])
outs.append(out)
return outs
def create(self, client, table_name, new_def):
params = {
'AttributeDefinitions': new_def['AttributeDefinitions'],
'TableName': table_name,
'KeySchema': new_def['KeySchema'] if 'KeySchema' in new_def else [],
'ProvisionedThroughput': self.construct_provisioned_throughput(new_def['ProvisionedThroughput'])
}
if 'LocalSecondaryIndexes' in new_def:
params['LocalSecondaryIndexes'] = self.construct_secondary_indexes(new_def['LocalSecondaryIndexes'])
if 'GlobalSecondaryIndexes' in new_def:
params['GlobalSecondaryIndexes'] = self.construct_secondary_indexes(new_def['GlobalSecondaryIndexes'])
if 'StreamSpecification' in new_def:
params['StreamSpecification'] = new_def['StreamSpecification']
try:
client.create_table(**params)
except botocore.exceptions.ClientError as e:
return (False, str(e))
return (True, self.CREATED)
| updates.append({ 'Create': index}) | conditional_block |
ranking-curiosity.js | class Ranking { //object for ranking in curiosity
constructor(){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
}
show (color){
ranking.colorActive = color;//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
ranking.runRankingSetColors($(object),ranking.stars);
});
}
init(){//init function
this.setDatasToRankings();
}
setDatasToRankings(){//this function set values to ranking this date get from attribute data-stars in html
var these = this;
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
$.each($(object).children(),function(index,obj){
obj.addEventListener("mouseover",these.hoverStar,false);
obj.addEventListener("mouseout",these.mouseOut,false);
if(index <= ranking.stars){
obj.style = "color:"+ranking.colorActive+";";
}
});
});
}
uploadStars(itemRanking,averageStars){//upload data stars in ranking element
if(averageStars>5 && averageStars<0){//validate data parameter
console.error("El segundo parametros recivido tiene que ser menor que 5 y mayor que 0");
}else{//if data parameter is correct
var parent = itemRanking.parentNode;// get ranking element(ul)
var stars = Math.floor(averageStars);// convert to int data stars
parent.setAttribute("data-stars",averageStars);//set new data stars to ranking
$(parent).find(".star-text").text(averageStars);//set text of average stars
ranking.runRankingSetColors($(parent),stars);// paint stars
}
}
hoverStar(event){//hover event
var starIndex = $(event.target).index();
ranking.runRankingSetColors($(event.target.parentNode),starIndex);
}
mouseOut(event){// mouse over event
var limitStars = Math.floor(event.target.parentNode.getAttribute("data-stars"));
ranking.runRankingSetColors($(event.target.parentNode),limitStars);
}
setColorActive(color) |
setColorUnActive(color){//set new color in case unactive
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorUnActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setEventClick(clickfunction){
if($.isFunction(clickfunction)){
$(".curiosity-ranking>li.item-ranking").click(clickfunction);
}else{
console.error("El parametro recibido tiene que ser una función");
}
}
};
var ranking = {//object with values to use in this class
colorActive : "",
colorUnActive : "",
stars : 0,
averageStars : 0,
runRankingSetColors : function(rankingElement,limitStars){//run to item ranking for set stars
$.each(rankingElement.children(),function(index,object){
if(index <= limitStars){
object.style = "color:"+ranking.colorActive+";";
}else{
object.style = "color:"+ranking.colorUnActive+";";
}
});
}
};
//end of document
| {//set new color in case active
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
} | identifier_body |
ranking-curiosity.js | class Ranking { //object for ranking in curiosity
| (){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
}
show (color){
ranking.colorActive = color;//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
ranking.runRankingSetColors($(object),ranking.stars);
});
}
init(){//init function
this.setDatasToRankings();
}
setDatasToRankings(){//this function set values to ranking this date get from attribute data-stars in html
var these = this;
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
$.each($(object).children(),function(index,obj){
obj.addEventListener("mouseover",these.hoverStar,false);
obj.addEventListener("mouseout",these.mouseOut,false);
if(index <= ranking.stars){
obj.style = "color:"+ranking.colorActive+";";
}
});
});
}
uploadStars(itemRanking,averageStars){//upload data stars in ranking element
if(averageStars>5 && averageStars<0){//validate data parameter
console.error("El segundo parametros recivido tiene que ser menor que 5 y mayor que 0");
}else{//if data parameter is correct
var parent = itemRanking.parentNode;// get ranking element(ul)
var stars = Math.floor(averageStars);// convert to int data stars
parent.setAttribute("data-stars",averageStars);//set new data stars to ranking
$(parent).find(".star-text").text(averageStars);//set text of average stars
ranking.runRankingSetColors($(parent),stars);// paint stars
}
}
hoverStar(event){//hover event
var starIndex = $(event.target).index();
ranking.runRankingSetColors($(event.target.parentNode),starIndex);
}
mouseOut(event){// mouse over event
var limitStars = Math.floor(event.target.parentNode.getAttribute("data-stars"));
ranking.runRankingSetColors($(event.target.parentNode),limitStars);
}
setColorActive(color){//set new color in case active
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setColorUnActive(color){//set new color in case unactive
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorUnActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setEventClick(clickfunction){
if($.isFunction(clickfunction)){
$(".curiosity-ranking>li.item-ranking").click(clickfunction);
}else{
console.error("El parametro recibido tiene que ser una función");
}
}
};
var ranking = {//object with values to use in this class
colorActive : "",
colorUnActive : "",
stars : 0,
averageStars : 0,
runRankingSetColors : function(rankingElement,limitStars){//run to item ranking for set stars
$.each(rankingElement.children(),function(index,object){
if(index <= limitStars){
object.style = "color:"+ranking.colorActive+";";
}else{
object.style = "color:"+ranking.colorUnActive+";";
}
});
}
};
//end of document
| constructor | identifier_name |
ranking-curiosity.js | class Ranking { //object for ranking in curiosity
constructor(){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
}
show (color){
ranking.colorActive = color;//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
ranking.runRankingSetColors($(object),ranking.stars);
});
}
init(){//init function
this.setDatasToRankings();
}
setDatasToRankings(){//this function set values to ranking this date get from attribute data-stars in html
var these = this;
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
$.each($(object).children(),function(index,obj){
obj.addEventListener("mouseover",these.hoverStar,false);
obj.addEventListener("mouseout",these.mouseOut,false);
if(index <= ranking.stars){
obj.style = "color:"+ranking.colorActive+";";
}
});
});
}
uploadStars(itemRanking,averageStars){//upload data stars in ranking element
if(averageStars>5 && averageStars<0){//validate data parameter
console.error("El segundo parametros recivido tiene que ser menor que 5 y mayor que 0");
}else{//if data parameter is correct
var parent = itemRanking.parentNode;// get ranking element(ul)
var stars = Math.floor(averageStars);// convert to int data stars
parent.setAttribute("data-stars",averageStars);//set new data stars to ranking
$(parent).find(".star-text").text(averageStars);//set text of average stars
ranking.runRankingSetColors($(parent),stars);// paint stars
}
}
hoverStar(event){//hover event
var starIndex = $(event.target).index();
ranking.runRankingSetColors($(event.target.parentNode),starIndex);
}
mouseOut(event){// mouse over event
var limitStars = Math.floor(event.target.parentNode.getAttribute("data-stars"));
ranking.runRankingSetColors($(event.target.parentNode),limitStars);
}
setColorActive(color){//set new color in case active
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setColorUnActive(color){//set new color in case unactive
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorUnActive = color;
}
else |
}
setEventClick(clickfunction){
if($.isFunction(clickfunction)){
$(".curiosity-ranking>li.item-ranking").click(clickfunction);
}else{
console.error("El parametro recibido tiene que ser una función");
}
}
};
var ranking = {//object with values to use in this class
colorActive : "",
colorUnActive : "",
stars : 0,
averageStars : 0,
runRankingSetColors : function(rankingElement,limitStars){//run to item ranking for set stars
$.each(rankingElement.children(),function(index,object){
if(index <= limitStars){
object.style = "color:"+ranking.colorActive+";";
}else{
object.style = "color:"+ranking.colorUnActive+";";
}
});
}
};
//end of document
| {
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
} | conditional_block |
ranking-curiosity.js | class Ranking { //object for ranking in curiosity
constructor(){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
}
show (color){
ranking.colorActive = color;//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
ranking.runRankingSetColors($(object),ranking.stars);
});
}
init(){//init function
this.setDatasToRankings();
}
setDatasToRankings(){//this function set values to ranking this date get from attribute data-stars in html
var these = this;
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
$.each($(object).children(),function(index,obj){
obj.addEventListener("mouseover",these.hoverStar,false);
obj.addEventListener("mouseout",these.mouseOut,false);
if(index <= ranking.stars){
obj.style = "color:"+ranking.colorActive+";";
}
});
});
}
uploadStars(itemRanking,averageStars){//upload data stars in ranking element
if(averageStars>5 && averageStars<0){//validate data parameter
console.error("El segundo parametros recivido tiene que ser menor que 5 y mayor que 0");
}else{//if data parameter is correct
var parent = itemRanking.parentNode;// get ranking element(ul)
var stars = Math.floor(averageStars);// convert to int data stars | ranking.runRankingSetColors($(parent),stars);// paint stars
}
}
hoverStar(event){//hover event
var starIndex = $(event.target).index();
ranking.runRankingSetColors($(event.target.parentNode),starIndex);
}
mouseOut(event){// mouse over event
var limitStars = Math.floor(event.target.parentNode.getAttribute("data-stars"));
ranking.runRankingSetColors($(event.target.parentNode),limitStars);
}
setColorActive(color){//set new color in case active
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setColorUnActive(color){//set new color in case unactive
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorUnActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setEventClick(clickfunction){
if($.isFunction(clickfunction)){
$(".curiosity-ranking>li.item-ranking").click(clickfunction);
}else{
console.error("El parametro recibido tiene que ser una función");
}
}
};
var ranking = {//object with values to use in this class
colorActive : "",
colorUnActive : "",
stars : 0,
averageStars : 0,
runRankingSetColors : function(rankingElement,limitStars){//run to item ranking for set stars
$.each(rankingElement.children(),function(index,object){
if(index <= limitStars){
object.style = "color:"+ranking.colorActive+";";
}else{
object.style = "color:"+ranking.colorUnActive+";";
}
});
}
};
//end of document | parent.setAttribute("data-stars",averageStars);//set new data stars to ranking
$(parent).find(".star-text").text(averageStars);//set text of average stars | random_line_split |
loop.js | import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // Millisecs we're allowed to spend on tasks in each frame
const fpsSamples = [];
const numFPSSamples = 30;
let lastTime = 0;
let elapsedTime;
let totalFPS = 0;
const frame = function () {
let time = Date.now();
if (lastTime > 0) |
runTasks(time);
fireTickEvents(time);
renderScenes();
lastTime = time;
window.requestAnimationFrame(frame);
};
function runTasks(time) { // Process as many enqueued tasks as we can within the per-frame task budget
const tasksRun = tasks.runTasks(time + taskBudget);
const tasksScheduled = tasks.getNumTasks();
stats.frame.tasksRun = tasksRun;
stats.frame.tasksScheduled = tasksScheduled;
stats.frame.tasksBudget = taskBudget;
}
function fireTickEvents(time) { // Fire tick event on each Scene
tickEvent.time = time;
for (var id in core.scenes) {
if (core.scenes.hasOwnProperty(id)) {
var scene = core.scenes[id];
tickEvent.sceneId = id;
tickEvent.startTime = scene.startTime;
tickEvent.deltaTime = tickEvent.prevTime != null ? tickEvent.time - tickEvent.prevTime : 0;
/**
* Fired on each game loop iteration.
*
* @event tick
* @param {String} sceneID The ID of this Scene.
* @param {Number} startTime The time in seconds since 1970 that this Scene was instantiated.
* @param {Number} time The time in seconds since 1970 of this "tick" event.
* @param {Number} prevTime The time of the previous "tick" event from this Scene.
* @param {Number} deltaTime The time in seconds since the previous "tick" event from this Scene.
*/
scene.fire("tick", tickEvent, true);
}
}
tickEvent.prevTime = time;
}
function renderScenes() {
const scenes = core.scenes;
const forceRender = false;
let scene;
let renderInfo;
let ticksPerRender;
let id;
for (id in scenes) {
if (scenes.hasOwnProperty(id)) {
scene = scenes[id];
renderInfo = scenesRenderInfo[id];
if (!renderInfo) {
renderInfo = scenesRenderInfo[id] = {}; // FIXME
}
ticksPerRender = scene.ticksPerRender;
if (renderInfo.ticksPerRender !== ticksPerRender) {
renderInfo.ticksPerRender = ticksPerRender;
renderInfo.renderCountdown = ticksPerRender;
}
if (--renderInfo.renderCountdown === 0) {
scene.render(forceRender);
renderInfo.renderCountdown = ticksPerRender;
}
}
}
}
window.requestAnimationFrame(frame);
const loop = {};
export{loop};
| { // Log FPS stats
elapsedTime = time - lastTime;
var newFPS = 1000 / elapsedTime; // Moving average of FPS
totalFPS += newFPS;
fpsSamples.push(newFPS);
if (fpsSamples.length >= numFPSSamples) {
totalFPS -= fpsSamples.shift();
}
stats.frame.fps = Math.round(totalFPS / fpsSamples.length);
} | conditional_block |
loop.js | import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // Millisecs we're allowed to spend on tasks in each frame
const fpsSamples = [];
const numFPSSamples = 30;
let lastTime = 0;
let elapsedTime;
let totalFPS = 0;
const frame = function () {
let time = Date.now();
if (lastTime > 0) { // Log FPS stats
elapsedTime = time - lastTime;
var newFPS = 1000 / elapsedTime; // Moving average of FPS
totalFPS += newFPS;
fpsSamples.push(newFPS);
if (fpsSamples.length >= numFPSSamples) {
totalFPS -= fpsSamples.shift();
}
stats.frame.fps = Math.round(totalFPS / fpsSamples.length);
}
runTasks(time);
fireTickEvents(time);
renderScenes();
lastTime = time;
window.requestAnimationFrame(frame);
};
function | (time) { // Process as many enqueued tasks as we can within the per-frame task budget
const tasksRun = tasks.runTasks(time + taskBudget);
const tasksScheduled = tasks.getNumTasks();
stats.frame.tasksRun = tasksRun;
stats.frame.tasksScheduled = tasksScheduled;
stats.frame.tasksBudget = taskBudget;
}
function fireTickEvents(time) { // Fire tick event on each Scene
tickEvent.time = time;
for (var id in core.scenes) {
if (core.scenes.hasOwnProperty(id)) {
var scene = core.scenes[id];
tickEvent.sceneId = id;
tickEvent.startTime = scene.startTime;
tickEvent.deltaTime = tickEvent.prevTime != null ? tickEvent.time - tickEvent.prevTime : 0;
/**
* Fired on each game loop iteration.
*
* @event tick
* @param {String} sceneID The ID of this Scene.
* @param {Number} startTime The time in seconds since 1970 that this Scene was instantiated.
* @param {Number} time The time in seconds since 1970 of this "tick" event.
* @param {Number} prevTime The time of the previous "tick" event from this Scene.
* @param {Number} deltaTime The time in seconds since the previous "tick" event from this Scene.
*/
scene.fire("tick", tickEvent, true);
}
}
tickEvent.prevTime = time;
}
function renderScenes() {
const scenes = core.scenes;
const forceRender = false;
let scene;
let renderInfo;
let ticksPerRender;
let id;
for (id in scenes) {
if (scenes.hasOwnProperty(id)) {
scene = scenes[id];
renderInfo = scenesRenderInfo[id];
if (!renderInfo) {
renderInfo = scenesRenderInfo[id] = {}; // FIXME
}
ticksPerRender = scene.ticksPerRender;
if (renderInfo.ticksPerRender !== ticksPerRender) {
renderInfo.ticksPerRender = ticksPerRender;
renderInfo.renderCountdown = ticksPerRender;
}
if (--renderInfo.renderCountdown === 0) {
scene.render(forceRender);
renderInfo.renderCountdown = ticksPerRender;
}
}
}
}
window.requestAnimationFrame(frame);
const loop = {};
export{loop};
| runTasks | identifier_name |
loop.js | import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // Millisecs we're allowed to spend on tasks in each frame
const fpsSamples = [];
const numFPSSamples = 30;
let lastTime = 0;
let elapsedTime;
let totalFPS = 0;
const frame = function () {
let time = Date.now();
if (lastTime > 0) { // Log FPS stats
elapsedTime = time - lastTime;
var newFPS = 1000 / elapsedTime; // Moving average of FPS
totalFPS += newFPS;
fpsSamples.push(newFPS);
if (fpsSamples.length >= numFPSSamples) {
totalFPS -= fpsSamples.shift();
}
stats.frame.fps = Math.round(totalFPS / fpsSamples.length);
}
runTasks(time);
fireTickEvents(time);
renderScenes();
lastTime = time;
window.requestAnimationFrame(frame);
};
function runTasks(time) { // Process as many enqueued tasks as we can within the per-frame task budget
const tasksRun = tasks.runTasks(time + taskBudget);
const tasksScheduled = tasks.getNumTasks();
stats.frame.tasksRun = tasksRun;
stats.frame.tasksScheduled = tasksScheduled;
stats.frame.tasksBudget = taskBudget;
}
function fireTickEvents(time) { // Fire tick event on each Scene
tickEvent.time = time;
for (var id in core.scenes) {
if (core.scenes.hasOwnProperty(id)) {
var scene = core.scenes[id];
tickEvent.sceneId = id;
tickEvent.startTime = scene.startTime;
tickEvent.deltaTime = tickEvent.prevTime != null ? tickEvent.time - tickEvent.prevTime : 0;
/**
* Fired on each game loop iteration.
*
* @event tick
* @param {String} sceneID The ID of this Scene.
* @param {Number} startTime The time in seconds since 1970 that this Scene was instantiated.
* @param {Number} time The time in seconds since 1970 of this "tick" event.
* @param {Number} prevTime The time of the previous "tick" event from this Scene.
* @param {Number} deltaTime The time in seconds since the previous "tick" event from this Scene.
*/
scene.fire("tick", tickEvent, true);
}
}
tickEvent.prevTime = time; |
function renderScenes() {
const scenes = core.scenes;
const forceRender = false;
let scene;
let renderInfo;
let ticksPerRender;
let id;
for (id in scenes) {
if (scenes.hasOwnProperty(id)) {
scene = scenes[id];
renderInfo = scenesRenderInfo[id];
if (!renderInfo) {
renderInfo = scenesRenderInfo[id] = {}; // FIXME
}
ticksPerRender = scene.ticksPerRender;
if (renderInfo.ticksPerRender !== ticksPerRender) {
renderInfo.ticksPerRender = ticksPerRender;
renderInfo.renderCountdown = ticksPerRender;
}
if (--renderInfo.renderCountdown === 0) {
scene.render(forceRender);
renderInfo.renderCountdown = ticksPerRender;
}
}
}
}
window.requestAnimationFrame(frame);
const loop = {};
export{loop}; | } | random_line_split |
loop.js | import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // Millisecs we're allowed to spend on tasks in each frame
const fpsSamples = [];
const numFPSSamples = 30;
let lastTime = 0;
let elapsedTime;
let totalFPS = 0;
const frame = function () {
let time = Date.now();
if (lastTime > 0) { // Log FPS stats
elapsedTime = time - lastTime;
var newFPS = 1000 / elapsedTime; // Moving average of FPS
totalFPS += newFPS;
fpsSamples.push(newFPS);
if (fpsSamples.length >= numFPSSamples) {
totalFPS -= fpsSamples.shift();
}
stats.frame.fps = Math.round(totalFPS / fpsSamples.length);
}
runTasks(time);
fireTickEvents(time);
renderScenes();
lastTime = time;
window.requestAnimationFrame(frame);
};
function runTasks(time) { // Process as many enqueued tasks as we can within the per-frame task budget
const tasksRun = tasks.runTasks(time + taskBudget);
const tasksScheduled = tasks.getNumTasks();
stats.frame.tasksRun = tasksRun;
stats.frame.tasksScheduled = tasksScheduled;
stats.frame.tasksBudget = taskBudget;
}
function fireTickEvents(time) |
function renderScenes() {
const scenes = core.scenes;
const forceRender = false;
let scene;
let renderInfo;
let ticksPerRender;
let id;
for (id in scenes) {
if (scenes.hasOwnProperty(id)) {
scene = scenes[id];
renderInfo = scenesRenderInfo[id];
if (!renderInfo) {
renderInfo = scenesRenderInfo[id] = {}; // FIXME
}
ticksPerRender = scene.ticksPerRender;
if (renderInfo.ticksPerRender !== ticksPerRender) {
renderInfo.ticksPerRender = ticksPerRender;
renderInfo.renderCountdown = ticksPerRender;
}
if (--renderInfo.renderCountdown === 0) {
scene.render(forceRender);
renderInfo.renderCountdown = ticksPerRender;
}
}
}
}
window.requestAnimationFrame(frame);
const loop = {};
export{loop};
| { // Fire tick event on each Scene
tickEvent.time = time;
for (var id in core.scenes) {
if (core.scenes.hasOwnProperty(id)) {
var scene = core.scenes[id];
tickEvent.sceneId = id;
tickEvent.startTime = scene.startTime;
tickEvent.deltaTime = tickEvent.prevTime != null ? tickEvent.time - tickEvent.prevTime : 0;
/**
* Fired on each game loop iteration.
*
* @event tick
* @param {String} sceneID The ID of this Scene.
* @param {Number} startTime The time in seconds since 1970 that this Scene was instantiated.
* @param {Number} time The time in seconds since 1970 of this "tick" event.
* @param {Number} prevTime The time of the previous "tick" event from this Scene.
* @param {Number} deltaTime The time in seconds since the previous "tick" event from this Scene.
*/
scene.fire("tick", tickEvent, true);
}
}
tickEvent.prevTime = time;
} | identifier_body |
43-basic-object-oriented-analysis-and-design.py | # Exercise 43: Basic Object-Oriented Analysis and Design
# Process to build something to evolve problems
# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and refine.
# The Analysis of a Simple Game Engine
# Write or Draw About the Problem
"""
Aliens have invaded a space ship and our hero has to go through a maze of rooms
defeating them so he can escape into an escape pod to the planet below. The game
will be more like a Zork or Adventure type game with text outputs and funny ways
to die. The game will involve an engine that runs a map full of rooms or scenes.
Each room will print its own description when the player enters it and then tell
the engine what room to run next out of the map.
"""
# At this point I have a good idea for the game and how it would run, so now I want
# to describe each scene:
"""
Death
This is when the player dies and should be something funny.
Central Corridor
This is the starting point and has a Gothon already standing there.
They have to defeat with a joke before continuing.
Laser Weapon Armory
This is where the hero gets a neutron bomb to blow up the ship before
getting to the escape pod. It has a keypad the hero has to gues the
number for.
The Bridge
Another battle scene with a Gothon where the hero places the bomb.
Escape Pod
Where the hero escapes but only after guessing the right escape pod.
"""
# Extract Key Concepts and Research Them
# First I make a list of all the nouns:
# Alien, Player, Ship, Maze, Room, Scene, Gothon, Escape Pod, Planet, Map, Engine, Death,
# Central Corridor, Laser Weapon Armory, The Bridge
# Create a Class Hierarchy and Object Map for the Concepts
"""
Right away I see that "Room" and "Scene" are basically the same thing depending on how
I want to do things. I'm going to pick "Scene" for this game. Then I see that all the
specific rooms like "Central Corridor" are basically just Scenes. I see also that Death
is basically a Scene, which confirms my choice of "Scene" over "Room" since you can have
a death scene, but a death room is kind of odd. "Maze" and "Map" are basically the same
so I'm going to go with "Map" since I used it more often. I don't want to do a battle
system so I'm going to ignore "Alien" and "Player" and save that for later. The "Planet"
could also just be another scene instead of something specific
"""
# After all of that thoiught process I start to make a class hierarchy that looks
# like this in my text editor:
# * Map
# * Engine
# * Scene
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
"""
I would then go through and figure out what actions are needed on each thing based on
verbs in the description. For example, I know from the description I'm going to need a
way to "run" the engine, "get the next scene" from the map, get the "opening scene" and
"enter" a scene. I'll add those like this:
"""
# * Map
# - next_scene
# - opening_scene
# * Engine
# - play
# * Scene
# - enter
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
"""
Notice how I just put -enter under Scene since I know that all the scenes under it will
inherit it and have to override it later.
"""
# Code the Classes and a Test to Run Them
# The Code for "Gothons from Planet Percal #25"
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
# be sure to print out the last scene
current_scene.enter()
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your mom would be proud...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(1)
class CentralCorridor(Scene):
def enter(self):
print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print "your entire crew. You are the last surviving member and your last"
print "mission is to get the neutron destruct bomb from the Weapons Armory,"
print "put it in the bridge, and blow the ship up after getting into an "
print "escape pod."
print "\n"
print "You're running down the central corridor to the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print "flowing around his hate filled body. He's blocking the door to the"
print "Armory and about to pull a weapon to blast you."
print "What will you do?"
print ">> shoot!"
print ">> dodge!"
print ">>tell a joke"
action = raw_input("> ")
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death'
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know: "
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
print "While he's laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
print "This is the code: %s." % code
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
class TheBridge(Scene):
def enter(self):
print "You burst onto the Bridge with the netron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
print "What will you do?"
print ">> throw the bomb"
print ">>slowly place the bomb"
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
class EscapePod(Scene):
def enter(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
print "Fast look tells you %s is good." % good_pod
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
return 'finished'
class Finished(Scene):
| return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
# Top Down vs Bottom Up
# Steps to do Bottom Up:
# 1. Take a small piece of the problem; hack on some code and get it to run barely.
# 2. Refine the code into something more formal with classes and automated tests.
# 3. Extract the key concepts you're using and try to find research for them.
# 4. Write a description of what's really going on.
# 5. Go back and refine the code, possibly throwing it out and starting over.
# 6. Repeat, moving on to some other piece of the problem.
# Study Drills:
# 1. Change it! Maybe you hate this game. Could be to violent, you aren't into sci-fi. Get the game
# working, then change it to what you like. This is your computer, you make it do what you want.
# 2. I have a bug in this code. Why is the door lock guessing 11 times?
# 3. Explain how returning the next room works.
# 4. Add cheat codes to the game so you can get past the more difficult rooms. I can do this with
# two words on one line.
# 5. Go back to my description and analysis, then try to build a small combat system for the hero
# and the various Gothons he encounters.
# 6. This is actually a small version of something called a "finite state machine". Read about them.
# They might not make sense but try anyway. | def enter(self):
print "You won! Good job." | random_line_split |
43-basic-object-oriented-analysis-and-design.py | # Exercise 43: Basic Object-Oriented Analysis and Design
# Process to build something to evolve problems
# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and refine.
# The Analysis of a Simple Game Engine
# Write or Draw About the Problem
"""
Aliens have invaded a space ship and our hero has to go through a maze of rooms
defeating them so he can escape into an escape pod to the planet below. The game
will be more like a Zork or Adventure type game with text outputs and funny ways
to die. The game will involve an engine that runs a map full of rooms or scenes.
Each room will print its own description when the player enters it and then tell
the engine what room to run next out of the map.
"""
# At this point I have a good idea for the game and how it would run, so now I want
# to describe each scene:
"""
Death
This is when the player dies and should be something funny.
Central Corridor
This is the starting point and has a Gothon already standing there.
They have to defeat with a joke before continuing.
Laser Weapon Armory
This is where the hero gets a neutron bomb to blow up the ship before
getting to the escape pod. It has a keypad the hero has to gues the
number for.
The Bridge
Another battle scene with a Gothon where the hero places the bomb.
Escape Pod
Where the hero escapes but only after guessing the right escape pod.
"""
# Extract Key Concepts and Research Them
# First I make a list of all the nouns:
# Alien, Player, Ship, Maze, Room, Scene, Gothon, Escape Pod, Planet, Map, Engine, Death,
# Central Corridor, Laser Weapon Armory, The Bridge
# Create a Class Hierarchy and Object Map for the Concepts
"""
Right away I see that "Room" and "Scene" are basically the same thing depending on how
I want to do things. I'm going to pick "Scene" for this game. Then I see that all the
specific rooms like "Central Corridor" are basically just Scenes. I see also that Death
is basically a Scene, which confirms my choice of "Scene" over "Room" since you can have
a death scene, but a death room is kind of odd. "Maze" and "Map" are basically the same
so I'm going to go with "Map" since I used it more often. I don't want to do a battle
system so I'm going to ignore "Alien" and "Player" and save that for later. The "Planet"
could also just be another scene instead of something specific
"""
# After all of that thoiught process I start to make a class hierarchy that looks
# like this in my text editor:
# * Map
# * Engine
# * Scene
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
"""
I would then go through and figure out what actions are needed on each thing based on
verbs in the description. For example, I know from the description I'm going to need a
way to "run" the engine, "get the next scene" from the map, get the "opening scene" and
"enter" a scene. I'll add those like this:
"""
# * Map
# - next_scene
# - opening_scene
# * Engine
# - play
# * Scene
# - enter
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
"""
Notice how I just put -enter under Scene since I know that all the scenes under it will
inherit it and have to override it later.
"""
# Code the Classes and a Test to Run Them
# The Code for "Gothons from Planet Percal #25"
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
# be sure to print out the last scene
current_scene.enter()
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your mom would be proud...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(1)
class CentralCorridor(Scene):
def enter(self):
print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print "your entire crew. You are the last surviving member and your last"
print "mission is to get the neutron destruct bomb from the Weapons Armory,"
print "put it in the bridge, and blow the ship up after getting into an "
print "escape pod."
print "\n"
print "You're running down the central corridor to the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print "flowing around his hate filled body. He's blocking the door to the"
print "Armory and about to pull a weapon to blast you."
print "What will you do?"
print ">> shoot!"
print ">> dodge!"
print ">>tell a joke"
action = raw_input("> ")
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action == "dodge!":
|
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know: "
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
print "While he's laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
print "This is the code: %s." % code
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
class TheBridge(Scene):
def enter(self):
print "You burst onto the Bridge with the netron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
print "What will you do?"
print ">> throw the bomb"
print ">>slowly place the bomb"
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
class EscapePod(Scene):
def enter(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
print "Fast look tells you %s is good." % good_pod
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
return 'finished'
class Finished(Scene):
def enter(self):
print "You won! Good job."
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
# Top Down vs Bottom Up
# Steps to do Bottom Up:
# 1. Take a small piece of the problem; hack on some code and get it to run barely.
# 2. Refine the code into something more formal with classes and automated tests.
# 3. Extract the key concepts you're using and try to find research for them.
# 4. Write a description of what's really going on.
# 5. Go back and refine the code, possibly throwing it out and starting over.
# 6. Repeat, moving on to some other piece of the problem.
# Study Drills:
# 1. Change it! Maybe you hate this game. Could be to violent, you aren't into sci-fi. Get the game
# working, then change it to what you like. This is your computer, you make it do what you want.
# 2. I have a bug in this code. Why is the door lock guessing 11 times?
# 3. Explain how returning the next room works.
# 4. Add cheat codes to the game so you can get past the more difficult rooms. I can do this with
# two words on one line.
# 5. Go back to my description and analysis, then try to build a small combat system for the hero
# and the various Gothons he encounters.
# 6. This is actually a small version of something called a "finite state machine". Read about them.
# They might not make sense but try anyway.
| print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death' | conditional_block |
43-basic-object-oriented-analysis-and-design.py | # Exercise 43: Basic Object-Oriented Analysis and Design
# Process to build something to evolve problems
# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and refine.
# The Analysis of a Simple Game Engine
# Write or Draw About the Problem
"""
Aliens have invaded a space ship and our hero has to go through a maze of rooms
defeating them so he can escape into an escape pod to the planet below. The game
will be more like a Zork or Adventure type game with text outputs and funny ways
to die. The game will involve an engine that runs a map full of rooms or scenes.
Each room will print its own description when the player enters it and then tell
the engine what room to run next out of the map.
"""
# At this point I have a good idea for the game and how it would run, so now I want
# to describe each scene:
"""
Death
This is when the player dies and should be something funny.
Central Corridor
This is the starting point and has a Gothon already standing there.
They have to defeat with a joke before continuing.
Laser Weapon Armory
This is where the hero gets a neutron bomb to blow up the ship before
getting to the escape pod. It has a keypad the hero has to gues the
number for.
The Bridge
Another battle scene with a Gothon where the hero places the bomb.
Escape Pod
Where the hero escapes but only after guessing the right escape pod.
"""
# Extract Key Concepts and Research Them
# First I make a list of all the nouns:
# Alien, Player, Ship, Maze, Room, Scene, Gothon, Escape Pod, Planet, Map, Engine, Death,
# Central Corridor, Laser Weapon Armory, The Bridge
# Create a Class Hierarchy and Object Map for the Concepts
"""
Right away I see that "Room" and "Scene" are basically the same thing depending on how
I want to do things. I'm going to pick "Scene" for this game. Then I see that all the
specific rooms like "Central Corridor" are basically just Scenes. I see also that Death
is basically a Scene, which confirms my choice of "Scene" over "Room" since you can have
a death scene, but a death room is kind of odd. "Maze" and "Map" are basically the same
so I'm going to go with "Map" since I used it more often. I don't want to do a battle
system so I'm going to ignore "Alien" and "Player" and save that for later. The "Planet"
could also just be another scene instead of something specific
"""
# After all of that thoiught process I start to make a class hierarchy that looks
# like this in my text editor:
# * Map
# * Engine
# * Scene
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
"""
I would then go through and figure out what actions are needed on each thing based on
verbs in the description. For example, I know from the description I'm going to need a
way to "run" the engine, "get the next scene" from the map, get the "opening scene" and
"enter" a scene. I'll add those like this:
"""
# * Map
# - next_scene
# - opening_scene
# * Engine
# - play
# * Scene
# - enter
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
"""
Notice how I just put -enter under Scene since I know that all the scenes under it will
inherit it and have to override it later.
"""
# Code the Classes and a Test to Run Them
# The Code for "Gothons from Planet Percal #25"
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
# be sure to print out the last scene
current_scene.enter()
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your mom would be proud...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(1)
class CentralCorridor(Scene):
def enter(self):
print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print "your entire crew. You are the last surviving member and your last"
print "mission is to get the neutron destruct bomb from the Weapons Armory,"
print "put it in the bridge, and blow the ship up after getting into an "
print "escape pod."
print "\n"
print "You're running down the central corridor to the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print "flowing around his hate filled body. He's blocking the door to the"
print "Armory and about to pull a weapon to blast you."
print "What will you do?"
print ">> shoot!"
print ">> dodge!"
print ">>tell a joke"
action = raw_input("> ")
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death'
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know: "
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
print "While he's laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
print "This is the code: %s." % code
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
class TheBridge(Scene):
def enter(self):
print "You burst onto the Bridge with the netron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
print "What will you do?"
print ">> throw the bomb"
print ">>slowly place the bomb"
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
class EscapePod(Scene):
def enter(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
print "Fast look tells you %s is good." % good_pod
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
return 'finished'
class Finished(Scene):
def | (self):
print "You won! Good job."
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
# Top Down vs Bottom Up
# Steps to do Bottom Up:
# 1. Take a small piece of the problem; hack on some code and get it to run barely.
# 2. Refine the code into something more formal with classes and automated tests.
# 3. Extract the key concepts you're using and try to find research for them.
# 4. Write a description of what's really going on.
# 5. Go back and refine the code, possibly throwing it out and starting over.
# 6. Repeat, moving on to some other piece of the problem.
# Study Drills:
# 1. Change it! Maybe you hate this game. Could be to violent, you aren't into sci-fi. Get the game
# working, then change it to what you like. This is your computer, you make it do what you want.
# 2. I have a bug in this code. Why is the door lock guessing 11 times?
# 3. Explain how returning the next room works.
# 4. Add cheat codes to the game so you can get past the more difficult rooms. I can do this with
# two words on one line.
# 5. Go back to my description and analysis, then try to build a small combat system for the hero
# and the various Gothons he encounters.
# 6. This is actually a small version of something called a "finite state machine". Read about them.
# They might not make sense but try anyway.
| enter | identifier_name |
43-basic-object-oriented-analysis-and-design.py | # Exercise 43: Basic Object-Oriented Analysis and Design
# Process to build something to evolve problems
# 1. Write or draw about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create a class hierarchy and object map for the concepts.
# 4. Code the classes and a test to run them.
# 5. Repeat and refine.
# The Analysis of a Simple Game Engine
# Write or Draw About the Problem
"""
Aliens have invaded a space ship and our hero has to go through a maze of rooms
defeating them so he can escape into an escape pod to the planet below. The game
will be more like a Zork or Adventure type game with text outputs and funny ways
to die. The game will involve an engine that runs a map full of rooms or scenes.
Each room will print its own description when the player enters it and then tell
the engine what room to run next out of the map.
"""
# At this point I have a good idea for the game and how it would run, so now I want
# to describe each scene:
"""
Death
This is when the player dies and should be something funny.
Central Corridor
This is the starting point and has a Gothon already standing there.
They have to defeat with a joke before continuing.
Laser Weapon Armory
This is where the hero gets a neutron bomb to blow up the ship before
getting to the escape pod. It has a keypad the hero has to gues the
number for.
The Bridge
Another battle scene with a Gothon where the hero places the bomb.
Escape Pod
Where the hero escapes but only after guessing the right escape pod.
"""
# Extract Key Concepts and Research Them
# First I make a list of all the nouns:
# Alien, Player, Ship, Maze, Room, Scene, Gothon, Escape Pod, Planet, Map, Engine, Death,
# Central Corridor, Laser Weapon Armory, The Bridge
# Create a Class Hierarchy and Object Map for the Concepts
"""
Right away I see that "Room" and "Scene" are basically the same thing depending on how
I want to do things. I'm going to pick "Scene" for this game. Then I see that all the
specific rooms like "Central Corridor" are basically just Scenes. I see also that Death
is basically a Scene, which confirms my choice of "Scene" over "Room" since you can have
a death scene, but a death room is kind of odd. "Maze" and "Map" are basically the same
so I'm going to go with "Map" since I used it more often. I don't want to do a battle
system so I'm going to ignore "Alien" and "Player" and save that for later. The "Planet"
could also just be another scene instead of something specific
"""
# After all of that thoiught process I start to make a class hierarchy that looks
# like this in my text editor:
# * Map
# * Engine
# * Scene
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
"""
I would then go through and figure out what actions are needed on each thing based on
verbs in the description. For example, I know from the description I'm going to need a
way to "run" the engine, "get the next scene" from the map, get the "opening scene" and
"enter" a scene. I'll add those like this:
"""
# * Map
# - next_scene
# - opening_scene
# * Engine
# - play
# * Scene
# - enter
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
"""
Notice how I just put -enter under Scene since I know that all the scenes under it will
inherit it and have to override it later.
"""
# Code the Classes and a Test to Run Them
# The Code for "Gothons from Planet Percal #25"
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
# be sure to print out the last scene
current_scene.enter()
class Death(Scene):
quips = [
"You died. You kinda suck at this.",
"Your mom would be proud...if she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def enter(self):
print Death.quips[randint(0, len(self.quips)-1)]
exit(1)
class CentralCorridor(Scene):
def enter(self):
print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print "your entire crew. You are the last surviving member and your last"
print "mission is to get the neutron destruct bomb from the Weapons Armory,"
print "put it in the bridge, and blow the ship up after getting into an "
print "escape pod."
print "\n"
print "You're running down the central corridor to the Weapons Armory when"
print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print "flowing around his hate filled body. He's blocking the door to the"
print "Armory and about to pull a weapon to blast you."
print "What will you do?"
print ">> shoot!"
print ">> dodge!"
print ">>tell a joke"
action = raw_input("> ")
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return 'death'
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon's blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return 'death'
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know: "
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
print "While he's laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
print "This is the code: %s." % code
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
class TheBridge(Scene):
def enter(self):
print "You burst onto the Bridge with the netron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven't pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don't want to set it off."
print "What will you do?"
print ">> throw the bomb"
print ">>slowly place the bomb"
action = raw_input("> ")
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return 'death'
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can't get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return 'escape_pod'
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
class EscapePod(Scene):
|
class Finished(Scene):
def enter(self):
print "You won! Good job."
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death(),
'finished': Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
# Top Down vs Bottom Up
# Steps to do Bottom Up:
# 1. Take a small piece of the problem; hack on some code and get it to run barely.
# 2. Refine the code into something more formal with classes and automated tests.
# 3. Extract the key concepts you're using and try to find research for them.
# 4. Write a description of what's really going on.
# 5. Go back and refine the code, possibly throwing it out and starting over.
# 6. Repeat, moving on to some other piece of the problem.
# Study Drills:
# 1. Change it! Maybe you hate this game. Could be to violent, you aren't into sci-fi. Get the game
# working, then change it to what you like. This is your computer, you make it do what you want.
# 2. I have a bug in this code. Why is the door lock guessing 11 times?
# 3. Explain how returning the next room works.
# 4. Add cheat codes to the game so you can get past the more difficult rooms. I can do this with
# two words on one line.
# 5. Go back to my description and analysis, then try to build a small combat system for the hero
# and the various Gothons he encounters.
# 6. This is actually a small version of something called a "finite state machine". Read about them.
# They might not make sense but try anyway.
| def enter(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don't have time to look. There's 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
print "Fast look tells you %s is good." % good_pod
guess = raw_input("[pod #]> ")
if int(guess) != good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return 'death'
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
return 'finished' | identifier_body |
react-localstorage.js | 'use strict';
var warn = require('./lib/warning');
var hasLocalStorage = 'localStorage' in global;
var ls, testKey;
if (hasLocalStorage) {
testKey = 'react-localstorage.mixin.test-key';
try {
// Access to global `localStorage` property must be guarded as it
// fails under iOS private session mode.
ls = global.localStorage;
ls.setItem(testKey, 'foo');
ls.removeItem(testKey);
} catch (e) {
hasLocalStorage = false;
}
}
// Warn if localStorage cannot be found or accessed.
if (process.browser) {
warn(
hasLocalStorage,
'localStorage not found. Component state will not be stored to localStorage.'
);
}
module.exports = {
/**
* Error checking. On update, ensure that the last state stored in localStorage is equal
* to the state on the component. We skip the check the first time around as state is left
* alone until mount to keep server rendering working.
*
* If it is not consistent, we know that someone else is modifying localStorage out from under us, so we throw
* an error.
*
* There are a lot of ways this can happen, so it is worth throwing the error.
*/
componentWillUpdate: function(nextProps, nextState) {
if (!hasLocalStorage || !this.__stateLoadedFromLS) return;
var key = getLocalStorageKey(this);
if (key === false) return;
var prevStoredState = ls.getItem(key);
if (prevStoredState && process.env.NODE_ENV !== "production") {
warn(
prevStoredState === JSON.stringify(getSyncState(this, this.state)),
'While component ' + getDisplayName(this) + ' was saving state to localStorage, ' +
'the localStorage entry was modified by another actor. This can happen when multiple ' +
'components are using the same localStorage key. Set the property `localStorageKey` ' +
'on ' + getDisplayName(this) + '.'
);
}
// Since setState() can't be called in CWU, it's a fine time to save the state.
ls.setItem(key, JSON.stringify(getSyncState(this, nextState)));
},
/**
* Load data.
* This seems odd to do this on componentDidMount, but it prevents server checksum errors.
* This is because the server has no way to know what is in your localStorage. So instead
* of breaking the checksum and causing a full rerender, we instead change the component after mount
* for an efficient diff.
*/
componentDidMount: function () {
if (!hasLocalStorage) return;
var me = this;
loadStateFromLocalStorage(this, function() {
// After setting state, mirror back to localstorage.
// This prevents invariants if the developer has changed the initial state of the component.
ls.setItem(getLocalStorageKey(me), JSON.stringify(getSyncState(me, me.state)));
});
}
};
function loadStateFromLocalStorage(component, cb) {
if (!ls) return;
var key = getLocalStorageKey(component);
if (key === false) return;
var settingState = false;
try {
var storedState = JSON.parse(ls.getItem(key));
if (storedState) {
settingState = true;
component.setState(storedState, done);
}
} catch(e) {
// eslint-disable-next-line no-console
if (console) console.warn("Unable to load state for", getDisplayName(component), "from localStorage.");
}
// If we didn't set state, run the callback right away.
if (!settingState) done();
function done() {
// Flag this component as loaded.
component.__stateLoadedFromLS = true;
cb();
}
}
function getDisplayName(component) {
// at least, we cannot get displayname
// via this.displayname in react 0.12
return component.displayName || component.constructor.displayName || component.constructor.name;
}
function getLocalStorageKey(component) {
if (component.getLocalStorageKey) return component.getLocalStorageKey();
if (component.props.localStorageKey === false) return false;
if (typeof component.props.localStorageKey === 'function') return component.props.localStorageKey.call(component);
return component.props.localStorageKey || getDisplayName(component) || 'react-localstorage';
}
function | (component) {
if (component.getStateFilterKeys) {
return typeof component.getStateFilterKeys() === 'string' ?
[component.getStateFilterKeys()] : component.getStateFilterKeys();
}
return typeof component.props.stateFilterKeys === 'string' ?
[component.props.stateFilterKeys] : component.props.stateFilterKeys;
}
/**
* Filters state to only save keys defined in stateFilterKeys.
* If stateFilterKeys is not set, returns full state.
*/
function getSyncState(component, state) {
var stateFilterKeys = getStateFilterKeys(component);
if (!stateFilterKeys || !state) return state;
var result = {}, key;
for (var i = 0; i < stateFilterKeys.length; i++) {
key = stateFilterKeys[i];
if (state.hasOwnProperty(key)) result[key] = state[key];
}
return result;
}
| getStateFilterKeys | identifier_name |
react-localstorage.js | 'use strict';
var warn = require('./lib/warning');
var hasLocalStorage = 'localStorage' in global;
var ls, testKey;
if (hasLocalStorage) {
testKey = 'react-localstorage.mixin.test-key';
try {
// Access to global `localStorage` property must be guarded as it
// fails under iOS private session mode.
ls = global.localStorage;
ls.setItem(testKey, 'foo');
ls.removeItem(testKey);
} catch (e) {
hasLocalStorage = false;
}
}
// Warn if localStorage cannot be found or accessed.
if (process.browser) {
warn(
hasLocalStorage,
'localStorage not found. Component state will not be stored to localStorage.'
);
}
module.exports = {
/**
* Error checking. On update, ensure that the last state stored in localStorage is equal
* to the state on the component. We skip the check the first time around as state is left
* alone until mount to keep server rendering working.
*
* If it is not consistent, we know that someone else is modifying localStorage out from under us, so we throw
* an error.
*
* There are a lot of ways this can happen, so it is worth throwing the error.
*/
componentWillUpdate: function(nextProps, nextState) {
if (!hasLocalStorage || !this.__stateLoadedFromLS) return;
var key = getLocalStorageKey(this);
if (key === false) return;
var prevStoredState = ls.getItem(key);
if (prevStoredState && process.env.NODE_ENV !== "production") {
warn(
prevStoredState === JSON.stringify(getSyncState(this, this.state)),
'While component ' + getDisplayName(this) + ' was saving state to localStorage, ' +
'the localStorage entry was modified by another actor. This can happen when multiple ' +
'components are using the same localStorage key. Set the property `localStorageKey` ' +
'on ' + getDisplayName(this) + '.'
);
}
// Since setState() can't be called in CWU, it's a fine time to save the state.
ls.setItem(key, JSON.stringify(getSyncState(this, nextState)));
},
/**
* Load data.
* This seems odd to do this on componentDidMount, but it prevents server checksum errors.
* This is because the server has no way to know what is in your localStorage. So instead
* of breaking the checksum and causing a full rerender, we instead change the component after mount
* for an efficient diff.
*/
componentDidMount: function () {
if (!hasLocalStorage) return;
var me = this;
loadStateFromLocalStorage(this, function() {
// After setting state, mirror back to localstorage.
// This prevents invariants if the developer has changed the initial state of the component.
ls.setItem(getLocalStorageKey(me), JSON.stringify(getSyncState(me, me.state)));
});
}
};
function loadStateFromLocalStorage(component, cb) {
if (!ls) return;
var key = getLocalStorageKey(component);
if (key === false) return;
var settingState = false;
try {
var storedState = JSON.parse(ls.getItem(key));
if (storedState) |
} catch(e) {
// eslint-disable-next-line no-console
if (console) console.warn("Unable to load state for", getDisplayName(component), "from localStorage.");
}
// If we didn't set state, run the callback right away.
if (!settingState) done();
function done() {
// Flag this component as loaded.
component.__stateLoadedFromLS = true;
cb();
}
}
function getDisplayName(component) {
// at least, we cannot get displayname
// via this.displayname in react 0.12
return component.displayName || component.constructor.displayName || component.constructor.name;
}
function getLocalStorageKey(component) {
if (component.getLocalStorageKey) return component.getLocalStorageKey();
if (component.props.localStorageKey === false) return false;
if (typeof component.props.localStorageKey === 'function') return component.props.localStorageKey.call(component);
return component.props.localStorageKey || getDisplayName(component) || 'react-localstorage';
}
function getStateFilterKeys(component) {
if (component.getStateFilterKeys) {
return typeof component.getStateFilterKeys() === 'string' ?
[component.getStateFilterKeys()] : component.getStateFilterKeys();
}
return typeof component.props.stateFilterKeys === 'string' ?
[component.props.stateFilterKeys] : component.props.stateFilterKeys;
}
/**
* Filters state to only save keys defined in stateFilterKeys.
* If stateFilterKeys is not set, returns full state.
*/
function getSyncState(component, state) {
var stateFilterKeys = getStateFilterKeys(component);
if (!stateFilterKeys || !state) return state;
var result = {}, key;
for (var i = 0; i < stateFilterKeys.length; i++) {
key = stateFilterKeys[i];
if (state.hasOwnProperty(key)) result[key] = state[key];
}
return result;
}
| {
settingState = true;
component.setState(storedState, done);
} | conditional_block |
react-localstorage.js | 'use strict';
var warn = require('./lib/warning');
var hasLocalStorage = 'localStorage' in global;
var ls, testKey;
if (hasLocalStorage) {
testKey = 'react-localstorage.mixin.test-key';
try {
// Access to global `localStorage` property must be guarded as it
// fails under iOS private session mode.
ls = global.localStorage;
ls.setItem(testKey, 'foo');
ls.removeItem(testKey);
} catch (e) {
hasLocalStorage = false;
}
}
// Warn if localStorage cannot be found or accessed.
if (process.browser) {
warn(
hasLocalStorage,
'localStorage not found. Component state will not be stored to localStorage.'
);
}
module.exports = {
/**
* Error checking. On update, ensure that the last state stored in localStorage is equal
* to the state on the component. We skip the check the first time around as state is left
* alone until mount to keep server rendering working.
*
* If it is not consistent, we know that someone else is modifying localStorage out from under us, so we throw
* an error.
*
* There are a lot of ways this can happen, so it is worth throwing the error.
*/ | var key = getLocalStorageKey(this);
if (key === false) return;
var prevStoredState = ls.getItem(key);
if (prevStoredState && process.env.NODE_ENV !== "production") {
warn(
prevStoredState === JSON.stringify(getSyncState(this, this.state)),
'While component ' + getDisplayName(this) + ' was saving state to localStorage, ' +
'the localStorage entry was modified by another actor. This can happen when multiple ' +
'components are using the same localStorage key. Set the property `localStorageKey` ' +
'on ' + getDisplayName(this) + '.'
);
}
// Since setState() can't be called in CWU, it's a fine time to save the state.
ls.setItem(key, JSON.stringify(getSyncState(this, nextState)));
},
/**
* Load data.
* This seems odd to do this on componentDidMount, but it prevents server checksum errors.
* This is because the server has no way to know what is in your localStorage. So instead
* of breaking the checksum and causing a full rerender, we instead change the component after mount
* for an efficient diff.
*/
componentDidMount: function () {
if (!hasLocalStorage) return;
var me = this;
loadStateFromLocalStorage(this, function() {
// After setting state, mirror back to localstorage.
// This prevents invariants if the developer has changed the initial state of the component.
ls.setItem(getLocalStorageKey(me), JSON.stringify(getSyncState(me, me.state)));
});
}
};
function loadStateFromLocalStorage(component, cb) {
if (!ls) return;
var key = getLocalStorageKey(component);
if (key === false) return;
var settingState = false;
try {
var storedState = JSON.parse(ls.getItem(key));
if (storedState) {
settingState = true;
component.setState(storedState, done);
}
} catch(e) {
// eslint-disable-next-line no-console
if (console) console.warn("Unable to load state for", getDisplayName(component), "from localStorage.");
}
// If we didn't set state, run the callback right away.
if (!settingState) done();
function done() {
// Flag this component as loaded.
component.__stateLoadedFromLS = true;
cb();
}
}
function getDisplayName(component) {
// at least, we cannot get displayname
// via this.displayname in react 0.12
return component.displayName || component.constructor.displayName || component.constructor.name;
}
function getLocalStorageKey(component) {
if (component.getLocalStorageKey) return component.getLocalStorageKey();
if (component.props.localStorageKey === false) return false;
if (typeof component.props.localStorageKey === 'function') return component.props.localStorageKey.call(component);
return component.props.localStorageKey || getDisplayName(component) || 'react-localstorage';
}
function getStateFilterKeys(component) {
if (component.getStateFilterKeys) {
return typeof component.getStateFilterKeys() === 'string' ?
[component.getStateFilterKeys()] : component.getStateFilterKeys();
}
return typeof component.props.stateFilterKeys === 'string' ?
[component.props.stateFilterKeys] : component.props.stateFilterKeys;
}
/**
* Filters state to only save keys defined in stateFilterKeys.
* If stateFilterKeys is not set, returns full state.
*/
function getSyncState(component, state) {
var stateFilterKeys = getStateFilterKeys(component);
if (!stateFilterKeys || !state) return state;
var result = {}, key;
for (var i = 0; i < stateFilterKeys.length; i++) {
key = stateFilterKeys[i];
if (state.hasOwnProperty(key)) result[key] = state[key];
}
return result;
} | componentWillUpdate: function(nextProps, nextState) {
if (!hasLocalStorage || !this.__stateLoadedFromLS) return; | random_line_split |
react-localstorage.js | 'use strict';
var warn = require('./lib/warning');
var hasLocalStorage = 'localStorage' in global;
var ls, testKey;
if (hasLocalStorage) {
testKey = 'react-localstorage.mixin.test-key';
try {
// Access to global `localStorage` property must be guarded as it
// fails under iOS private session mode.
ls = global.localStorage;
ls.setItem(testKey, 'foo');
ls.removeItem(testKey);
} catch (e) {
hasLocalStorage = false;
}
}
// Warn if localStorage cannot be found or accessed.
if (process.browser) {
warn(
hasLocalStorage,
'localStorage not found. Component state will not be stored to localStorage.'
);
}
module.exports = {
/**
* Error checking. On update, ensure that the last state stored in localStorage is equal
* to the state on the component. We skip the check the first time around as state is left
* alone until mount to keep server rendering working.
*
* If it is not consistent, we know that someone else is modifying localStorage out from under us, so we throw
* an error.
*
* There are a lot of ways this can happen, so it is worth throwing the error.
*/
componentWillUpdate: function(nextProps, nextState) {
if (!hasLocalStorage || !this.__stateLoadedFromLS) return;
var key = getLocalStorageKey(this);
if (key === false) return;
var prevStoredState = ls.getItem(key);
if (prevStoredState && process.env.NODE_ENV !== "production") {
warn(
prevStoredState === JSON.stringify(getSyncState(this, this.state)),
'While component ' + getDisplayName(this) + ' was saving state to localStorage, ' +
'the localStorage entry was modified by another actor. This can happen when multiple ' +
'components are using the same localStorage key. Set the property `localStorageKey` ' +
'on ' + getDisplayName(this) + '.'
);
}
// Since setState() can't be called in CWU, it's a fine time to save the state.
ls.setItem(key, JSON.stringify(getSyncState(this, nextState)));
},
/**
* Load data.
* This seems odd to do this on componentDidMount, but it prevents server checksum errors.
* This is because the server has no way to know what is in your localStorage. So instead
* of breaking the checksum and causing a full rerender, we instead change the component after mount
* for an efficient diff.
*/
componentDidMount: function () {
if (!hasLocalStorage) return;
var me = this;
loadStateFromLocalStorage(this, function() {
// After setting state, mirror back to localstorage.
// This prevents invariants if the developer has changed the initial state of the component.
ls.setItem(getLocalStorageKey(me), JSON.stringify(getSyncState(me, me.state)));
});
}
};
function loadStateFromLocalStorage(component, cb) {
if (!ls) return;
var key = getLocalStorageKey(component);
if (key === false) return;
var settingState = false;
try {
var storedState = JSON.parse(ls.getItem(key));
if (storedState) {
settingState = true;
component.setState(storedState, done);
}
} catch(e) {
// eslint-disable-next-line no-console
if (console) console.warn("Unable to load state for", getDisplayName(component), "from localStorage.");
}
// If we didn't set state, run the callback right away.
if (!settingState) done();
function done() |
}
function getDisplayName(component) {
// at least, we cannot get displayname
// via this.displayname in react 0.12
return component.displayName || component.constructor.displayName || component.constructor.name;
}
function getLocalStorageKey(component) {
if (component.getLocalStorageKey) return component.getLocalStorageKey();
if (component.props.localStorageKey === false) return false;
if (typeof component.props.localStorageKey === 'function') return component.props.localStorageKey.call(component);
return component.props.localStorageKey || getDisplayName(component) || 'react-localstorage';
}
function getStateFilterKeys(component) {
if (component.getStateFilterKeys) {
return typeof component.getStateFilterKeys() === 'string' ?
[component.getStateFilterKeys()] : component.getStateFilterKeys();
}
return typeof component.props.stateFilterKeys === 'string' ?
[component.props.stateFilterKeys] : component.props.stateFilterKeys;
}
/**
* Filters state to only save keys defined in stateFilterKeys.
* If stateFilterKeys is not set, returns full state.
*/
function getSyncState(component, state) {
var stateFilterKeys = getStateFilterKeys(component);
if (!stateFilterKeys || !state) return state;
var result = {}, key;
for (var i = 0; i < stateFilterKeys.length; i++) {
key = stateFilterKeys[i];
if (state.hasOwnProperty(key)) result[key] = state[key];
}
return result;
}
| {
// Flag this component as loaded.
component.__stateLoadedFromLS = true;
cb();
} | identifier_body |
beeswax.py | # Copyright 2014 Cloudera 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.
from __future__ import absolute_import
import getpass
import time
import sys
import six
import os
from impala.dbapi.interface import Connection, Cursor, _bind_parameters
from impala._rpc import beeswax as rpc
from impala.error import NotSupportedError, ProgrammingError, OperationalError
from impala._thrift_api.beeswax import QueryState
class BeeswaxConnection(Connection):
# PEP 249
def __init__(self, service, default_db=None):
self.service = service
self.default_db = default_db
self.default_query_options = {}
def close(self):
"""Close the session and the Thrift transport."""
# PEP 249
rpc.close_service(self.service)
def commit(self):
"""Impala doesn't support transactions; does nothing."""
# PEP 249
pass
def rollback(self):
"""Impala doesn't support transactions; raises NotSupportedError"""
# PEP 249
raise NotSupportedError
def cursor(self, user=None, configuration=None):
# PEP 249
if user is None:
user = getpass.getuser()
options = rpc.build_default_query_options_dict(self.service)
for opt in options:
self.default_query_options[opt.key.upper()] = opt.value
cursor = BeeswaxCursor(self.service, user)
if self.default_db is not None:
cursor.execute('USE %s' % self.default_db)
return cursor
def reconnect(self):
rpc.reconnect(self.service)
class BeeswaxCursor(Cursor):
# PEP 249
# Beeswax does not support sessions
def __init__(self, service, user):
self.service = service
self.user = user
self._last_operation_string = None
self._last_operation_handle = None
self._last_operation_active = False
self._buffersize = None
self._buffer = []
# initial values, per PEP 249
self._description = None
self._rowcount = -1
self.query_state = QueryState._NAMES_TO_VALUES
@property
def description(self):
# PEP 249
return self._description
@property
def rowcount(self):
# PEP 249
return self._rowcount
@property
def query_string(self):
return self._last_operation_string
def get_arraysize(self):
# PEP 249
return self._buffersize if self._buffersize else 1
def set_arraysize(self, arraysize):
# PEP 249
self._buffersize = arraysize
arraysize = property(get_arraysize, set_arraysize)
@property
def buffersize(self):
# this is for internal use. it provides an alternate default value for
# the size of the buffer, so that calling .next() will read multiple
# rows into a buffer if arraysize hasn't been set. (otherwise, we'd
# get an unbuffered impl because the PEP 249 default value of arraysize
# is 1)
return self._buffersize if self._buffersize else 1024
@property
def has_result_set(self):
return (self._last_operation_handle is not None and
rpc.expect_result_metadata(self._last_operation_string))
def close(self):
# PEP 249
pass
def cancel_operation(self):
if self._last_operation_active:
self._last_operation_active = False
rpc.cancel_query(self.service, self._last_operation_handle)
def close_operation(self):
if self._last_operation_active:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
def execute(self, operation, parameters=None, configuration=None):
# PEP 249
if configuration is None:
configuration = {}
def op():
if parameters:
self._last_operation_string = _bind_parameters(operation,
parameters)
else:
self._last_operation_string = operation
query = rpc.create_beeswax_query(self._last_operation_string,
self.user, configuration)
self._last_operation_handle = rpc.execute_statement(self.service,
query)
self._execute_sync(op)
def _execute_sync(self, operation_fn):
# operation_fn should set self._last_operation_string and
# self._last_operation_handle
self._reset_state()
operation_fn()
self._last_operation_active = True
self._wait_to_finish() # make execute synchronous
if self.has_result_set:
schema = rpc.get_results_metadata(
self.service, self._last_operation_handle)
self._description = [tuple([tup.name, tup.type.upper()] +
[None, None, None, None, None])
for tup in schema]
else:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
def _reset_state(self):
self._buffer = []
self._rowcount = -1
self._description = None
if self._last_operation_active:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
self._last_operation_string = None
self._last_operation_handle = None
def _wait_to_finish(self):
loop_start = time.time()
while True:
|
def _get_sleep_interval(self, start_time):
"""Returns a step function of time to sleep in seconds before polling
again. Maximum sleep is 1s, minimum is 0.1s"""
elapsed = time.time() - start_time
if elapsed < 10.0:
return 0.1
elif elapsed < 60.0:
return 0.5
return 1.0
def executemany(self, operation, seq_of_parameters):
# PEP 249
for parameters in seq_of_parameters:
self.execute(operation, parameters)
if self.has_result_set:
raise ProgrammingError("Operations that have result sets are "
"not allowed with executemany.")
def fetchone(self):
# PEP 249
if not self.has_result_set:
raise ProgrammingError("Tried to fetch but no results.")
try:
return next(self)
except StopIteration:
return None
def fetchmany(self, size=None):
# PEP 249
if not self.has_result_set:
raise ProgrammingError("Tried to fetch but no results.")
if size is None:
size = self.arraysize
local_buffer = []
i = 0
while i < size:
try:
local_buffer.append(next(self))
i += 1
except StopIteration:
break
return local_buffer
def fetchall(self):
# PEP 249
try:
return list(self)
except StopIteration:
return []
def setinputsizes(self, sizes):
# PEP 249
pass
def setoutputsize(self, size, column=None):
# PEP 249
pass
def __iter__(self):
return self
def __next__(self):
if not self.has_result_set:
raise ProgrammingError(
"Trying to fetch results on an operation with no results.")
if len(self._buffer) > 0:
return self._buffer.pop(0)
elif self._last_operation_active:
# self._buffer is empty here and op is active: try to pull
# more rows
rows = rpc.fetch_internal(self.service,
self._last_operation_handle,
self.buffersize)
self._buffer.extend(rows)
if len(self._buffer) == 0:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
raise StopIteration
return self._buffer.pop(0)
else:
# empty buffer and op is now closed: raise StopIteration
raise StopIteration
def ping(self):
"""Checks connection to server by requesting some info
from the server.
"""
return rpc.ping(self.service)
def get_log(self):
return rpc.get_warning_log(self.service, self._last_operation_handle)
def get_profile(self):
return rpc.get_runtime_profile(
self.service, self._last_operation_handle)
def get_summary(self):
return rpc.get_summary(self.service, self._last_operation_handle)
def build_summary_table(self, summary, output, idx=0,
is_fragment_root=False, indent_level=0):
return rpc.build_summary_table(
summary, idx, is_fragment_root, indent_level, output)
| operation_state = rpc.get_query_state(
self.service, self._last_operation_handle)
if operation_state == self.query_state["FINISHED"]:
break
elif operation_state == self.query_state["EXCEPTION"]:
raise OperationalError(self.get_log())
time.sleep(self._get_sleep_interval(loop_start)) | conditional_block |
beeswax.py | # Copyright 2014 Cloudera 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.
from __future__ import absolute_import
import getpass
import time
import sys
import six
import os
from impala.dbapi.interface import Connection, Cursor, _bind_parameters
from impala._rpc import beeswax as rpc
from impala.error import NotSupportedError, ProgrammingError, OperationalError
from impala._thrift_api.beeswax import QueryState
class BeeswaxConnection(Connection):
# PEP 249
def __init__(self, service, default_db=None):
self.service = service
self.default_db = default_db
self.default_query_options = {}
def close(self):
"""Close the session and the Thrift transport."""
# PEP 249
rpc.close_service(self.service)
def commit(self):
"""Impala doesn't support transactions; does nothing."""
# PEP 249
pass
def rollback(self):
|
def cursor(self, user=None, configuration=None):
# PEP 249
if user is None:
user = getpass.getuser()
options = rpc.build_default_query_options_dict(self.service)
for opt in options:
self.default_query_options[opt.key.upper()] = opt.value
cursor = BeeswaxCursor(self.service, user)
if self.default_db is not None:
cursor.execute('USE %s' % self.default_db)
return cursor
def reconnect(self):
rpc.reconnect(self.service)
class BeeswaxCursor(Cursor):
# PEP 249
# Beeswax does not support sessions
def __init__(self, service, user):
self.service = service
self.user = user
self._last_operation_string = None
self._last_operation_handle = None
self._last_operation_active = False
self._buffersize = None
self._buffer = []
# initial values, per PEP 249
self._description = None
self._rowcount = -1
self.query_state = QueryState._NAMES_TO_VALUES
@property
def description(self):
# PEP 249
return self._description
@property
def rowcount(self):
# PEP 249
return self._rowcount
@property
def query_string(self):
return self._last_operation_string
def get_arraysize(self):
# PEP 249
return self._buffersize if self._buffersize else 1
def set_arraysize(self, arraysize):
# PEP 249
self._buffersize = arraysize
arraysize = property(get_arraysize, set_arraysize)
@property
def buffersize(self):
# this is for internal use. it provides an alternate default value for
# the size of the buffer, so that calling .next() will read multiple
# rows into a buffer if arraysize hasn't been set. (otherwise, we'd
# get an unbuffered impl because the PEP 249 default value of arraysize
# is 1)
return self._buffersize if self._buffersize else 1024
@property
def has_result_set(self):
return (self._last_operation_handle is not None and
rpc.expect_result_metadata(self._last_operation_string))
def close(self):
# PEP 249
pass
def cancel_operation(self):
if self._last_operation_active:
self._last_operation_active = False
rpc.cancel_query(self.service, self._last_operation_handle)
def close_operation(self):
if self._last_operation_active:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
def execute(self, operation, parameters=None, configuration=None):
# PEP 249
if configuration is None:
configuration = {}
def op():
if parameters:
self._last_operation_string = _bind_parameters(operation,
parameters)
else:
self._last_operation_string = operation
query = rpc.create_beeswax_query(self._last_operation_string,
self.user, configuration)
self._last_operation_handle = rpc.execute_statement(self.service,
query)
self._execute_sync(op)
def _execute_sync(self, operation_fn):
# operation_fn should set self._last_operation_string and
# self._last_operation_handle
self._reset_state()
operation_fn()
self._last_operation_active = True
self._wait_to_finish() # make execute synchronous
if self.has_result_set:
schema = rpc.get_results_metadata(
self.service, self._last_operation_handle)
self._description = [tuple([tup.name, tup.type.upper()] +
[None, None, None, None, None])
for tup in schema]
else:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
def _reset_state(self):
self._buffer = []
self._rowcount = -1
self._description = None
if self._last_operation_active:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
self._last_operation_string = None
self._last_operation_handle = None
def _wait_to_finish(self):
loop_start = time.time()
while True:
operation_state = rpc.get_query_state(
self.service, self._last_operation_handle)
if operation_state == self.query_state["FINISHED"]:
break
elif operation_state == self.query_state["EXCEPTION"]:
raise OperationalError(self.get_log())
time.sleep(self._get_sleep_interval(loop_start))
def _get_sleep_interval(self, start_time):
"""Returns a step function of time to sleep in seconds before polling
again. Maximum sleep is 1s, minimum is 0.1s"""
elapsed = time.time() - start_time
if elapsed < 10.0:
return 0.1
elif elapsed < 60.0:
return 0.5
return 1.0
def executemany(self, operation, seq_of_parameters):
# PEP 249
for parameters in seq_of_parameters:
self.execute(operation, parameters)
if self.has_result_set:
raise ProgrammingError("Operations that have result sets are "
"not allowed with executemany.")
def fetchone(self):
# PEP 249
if not self.has_result_set:
raise ProgrammingError("Tried to fetch but no results.")
try:
return next(self)
except StopIteration:
return None
def fetchmany(self, size=None):
# PEP 249
if not self.has_result_set:
raise ProgrammingError("Tried to fetch but no results.")
if size is None:
size = self.arraysize
local_buffer = []
i = 0
while i < size:
try:
local_buffer.append(next(self))
i += 1
except StopIteration:
break
return local_buffer
def fetchall(self):
# PEP 249
try:
return list(self)
except StopIteration:
return []
def setinputsizes(self, sizes):
# PEP 249
pass
def setoutputsize(self, size, column=None):
# PEP 249
pass
def __iter__(self):
return self
def __next__(self):
if not self.has_result_set:
raise ProgrammingError(
"Trying to fetch results on an operation with no results.")
if len(self._buffer) > 0:
return self._buffer.pop(0)
elif self._last_operation_active:
# self._buffer is empty here and op is active: try to pull
# more rows
rows = rpc.fetch_internal(self.service,
self._last_operation_handle,
self.buffersize)
self._buffer.extend(rows)
if len(self._buffer) == 0:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
raise StopIteration
return self._buffer.pop(0)
else:
# empty buffer and op is now closed: raise StopIteration
raise StopIteration
def ping(self):
"""Checks connection to server by requesting some info
from the server.
"""
return rpc.ping(self.service)
def get_log(self):
return rpc.get_warning_log(self.service, self._last_operation_handle)
def get_profile(self):
return rpc.get_runtime_profile(
self.service, self._last_operation_handle)
def get_summary(self):
return rpc.get_summary(self.service, self._last_operation_handle)
def build_summary_table(self, summary, output, idx=0,
is_fragment_root=False, indent_level=0):
return rpc.build_summary_table(
summary, idx, is_fragment_root, indent_level, output)
| """Impala doesn't support transactions; raises NotSupportedError"""
# PEP 249
raise NotSupportedError | identifier_body |
beeswax.py | # Copyright 2014 Cloudera 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.
from __future__ import absolute_import
import getpass
import time
import sys
import six
import os
from impala.dbapi.interface import Connection, Cursor, _bind_parameters
from impala._rpc import beeswax as rpc
from impala.error import NotSupportedError, ProgrammingError, OperationalError
from impala._thrift_api.beeswax import QueryState
class BeeswaxConnection(Connection):
# PEP 249
def __init__(self, service, default_db=None):
self.service = service
self.default_db = default_db
self.default_query_options = {}
def close(self):
"""Close the session and the Thrift transport."""
# PEP 249
rpc.close_service(self.service)
def commit(self):
"""Impala doesn't support transactions; does nothing."""
# PEP 249
pass
def rollback(self):
"""Impala doesn't support transactions; raises NotSupportedError"""
# PEP 249
raise NotSupportedError
def cursor(self, user=None, configuration=None):
# PEP 249
if user is None:
user = getpass.getuser()
options = rpc.build_default_query_options_dict(self.service)
for opt in options:
self.default_query_options[opt.key.upper()] = opt.value
cursor = BeeswaxCursor(self.service, user)
if self.default_db is not None:
cursor.execute('USE %s' % self.default_db)
return cursor
def reconnect(self):
rpc.reconnect(self.service)
class BeeswaxCursor(Cursor):
# PEP 249
# Beeswax does not support sessions
def __init__(self, service, user):
self.service = service
self.user = user
self._last_operation_string = None
self._last_operation_handle = None
self._last_operation_active = False
self._buffersize = None
self._buffer = []
# initial values, per PEP 249
self._description = None
self._rowcount = -1
self.query_state = QueryState._NAMES_TO_VALUES
@property
def description(self):
# PEP 249
return self._description
@property
def rowcount(self):
# PEP 249
return self._rowcount
@property
def query_string(self):
return self._last_operation_string
def get_arraysize(self):
# PEP 249
return self._buffersize if self._buffersize else 1
def set_arraysize(self, arraysize):
# PEP 249
self._buffersize = arraysize
arraysize = property(get_arraysize, set_arraysize)
@property
def buffersize(self):
# this is for internal use. it provides an alternate default value for
# the size of the buffer, so that calling .next() will read multiple
# rows into a buffer if arraysize hasn't been set. (otherwise, we'd
# get an unbuffered impl because the PEP 249 default value of arraysize
# is 1)
return self._buffersize if self._buffersize else 1024
@property
def has_result_set(self):
return (self._last_operation_handle is not None and
rpc.expect_result_metadata(self._last_operation_string))
def close(self):
# PEP 249
pass
def cancel_operation(self):
if self._last_operation_active:
self._last_operation_active = False
rpc.cancel_query(self.service, self._last_operation_handle)
def close_operation(self):
if self._last_operation_active:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
def execute(self, operation, parameters=None, configuration=None):
# PEP 249
if configuration is None:
configuration = {}
def op():
if parameters:
self._last_operation_string = _bind_parameters(operation,
parameters)
else:
self._last_operation_string = operation
query = rpc.create_beeswax_query(self._last_operation_string,
self.user, configuration)
self._last_operation_handle = rpc.execute_statement(self.service,
query)
self._execute_sync(op)
def _execute_sync(self, operation_fn):
# operation_fn should set self._last_operation_string and
# self._last_operation_handle
self._reset_state()
operation_fn()
self._last_operation_active = True
self._wait_to_finish() # make execute synchronous
if self.has_result_set:
schema = rpc.get_results_metadata(
self.service, self._last_operation_handle)
self._description = [tuple([tup.name, tup.type.upper()] +
[None, None, None, None, None])
for tup in schema]
else:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
def _reset_state(self):
self._buffer = []
self._rowcount = -1
self._description = None
if self._last_operation_active:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
self._last_operation_string = None
self._last_operation_handle = None
def _wait_to_finish(self):
loop_start = time.time()
while True:
operation_state = rpc.get_query_state(
self.service, self._last_operation_handle)
if operation_state == self.query_state["FINISHED"]:
break
elif operation_state == self.query_state["EXCEPTION"]:
raise OperationalError(self.get_log())
time.sleep(self._get_sleep_interval(loop_start))
def _get_sleep_interval(self, start_time):
"""Returns a step function of time to sleep in seconds before polling
again. Maximum sleep is 1s, minimum is 0.1s"""
elapsed = time.time() - start_time
if elapsed < 10.0:
return 0.1
elif elapsed < 60.0:
return 0.5
return 1.0
def executemany(self, operation, seq_of_parameters):
# PEP 249
for parameters in seq_of_parameters:
self.execute(operation, parameters)
if self.has_result_set:
raise ProgrammingError("Operations that have result sets are "
"not allowed with executemany.")
def fetchone(self):
# PEP 249
if not self.has_result_set:
raise ProgrammingError("Tried to fetch but no results.")
try:
return next(self)
except StopIteration:
return None
def fetchmany(self, size=None):
# PEP 249
if not self.has_result_set:
raise ProgrammingError("Tried to fetch but no results.")
if size is None:
size = self.arraysize
local_buffer = []
i = 0
while i < size:
try:
local_buffer.append(next(self))
i += 1
except StopIteration:
break
return local_buffer
def fetchall(self):
# PEP 249
try:
return list(self)
except StopIteration:
return []
def setinputsizes(self, sizes):
# PEP 249
pass
def setoutputsize(self, size, column=None):
# PEP 249
pass
def __iter__(self):
return self
def __next__(self):
if not self.has_result_set:
raise ProgrammingError(
"Trying to fetch results on an operation with no results.")
if len(self._buffer) > 0:
return self._buffer.pop(0)
elif self._last_operation_active:
# self._buffer is empty here and op is active: try to pull
# more rows
rows = rpc.fetch_internal(self.service,
self._last_operation_handle,
self.buffersize)
self._buffer.extend(rows)
if len(self._buffer) == 0:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
raise StopIteration
return self._buffer.pop(0)
else:
# empty buffer and op is now closed: raise StopIteration
raise StopIteration
def ping(self):
"""Checks connection to server by requesting some info
from the server.
"""
return rpc.ping(self.service)
def get_log(self):
return rpc.get_warning_log(self.service, self._last_operation_handle)
def get_profile(self):
return rpc.get_runtime_profile(
self.service, self._last_operation_handle)
def | (self):
return rpc.get_summary(self.service, self._last_operation_handle)
def build_summary_table(self, summary, output, idx=0,
is_fragment_root=False, indent_level=0):
return rpc.build_summary_table(
summary, idx, is_fragment_root, indent_level, output)
| get_summary | identifier_name |
beeswax.py | # Copyright 2014 Cloudera 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.
from __future__ import absolute_import
import getpass
import time
import sys
import six
import os
from impala.dbapi.interface import Connection, Cursor, _bind_parameters
from impala._rpc import beeswax as rpc
from impala.error import NotSupportedError, ProgrammingError, OperationalError
from impala._thrift_api.beeswax import QueryState
class BeeswaxConnection(Connection):
# PEP 249
def __init__(self, service, default_db=None):
self.service = service
self.default_db = default_db
self.default_query_options = {}
def close(self):
"""Close the session and the Thrift transport."""
# PEP 249
rpc.close_service(self.service)
def commit(self):
"""Impala doesn't support transactions; does nothing."""
# PEP 249
pass
def rollback(self):
"""Impala doesn't support transactions; raises NotSupportedError"""
# PEP 249
raise NotSupportedError
def cursor(self, user=None, configuration=None):
# PEP 249
if user is None:
user = getpass.getuser()
options = rpc.build_default_query_options_dict(self.service)
for opt in options:
self.default_query_options[opt.key.upper()] = opt.value
cursor = BeeswaxCursor(self.service, user)
if self.default_db is not None:
cursor.execute('USE %s' % self.default_db)
return cursor
def reconnect(self):
rpc.reconnect(self.service)
class BeeswaxCursor(Cursor):
# PEP 249
# Beeswax does not support sessions
def __init__(self, service, user):
self.service = service
self.user = user
self._last_operation_string = None
self._last_operation_handle = None
self._last_operation_active = False
self._buffersize = None
self._buffer = []
# initial values, per PEP 249
self._description = None
self._rowcount = -1
self.query_state = QueryState._NAMES_TO_VALUES
@property
def description(self):
# PEP 249
return self._description
@property
def rowcount(self):
# PEP 249 | def query_string(self):
return self._last_operation_string
def get_arraysize(self):
# PEP 249
return self._buffersize if self._buffersize else 1
def set_arraysize(self, arraysize):
# PEP 249
self._buffersize = arraysize
arraysize = property(get_arraysize, set_arraysize)
@property
def buffersize(self):
# this is for internal use. it provides an alternate default value for
# the size of the buffer, so that calling .next() will read multiple
# rows into a buffer if arraysize hasn't been set. (otherwise, we'd
# get an unbuffered impl because the PEP 249 default value of arraysize
# is 1)
return self._buffersize if self._buffersize else 1024
@property
def has_result_set(self):
return (self._last_operation_handle is not None and
rpc.expect_result_metadata(self._last_operation_string))
def close(self):
# PEP 249
pass
def cancel_operation(self):
if self._last_operation_active:
self._last_operation_active = False
rpc.cancel_query(self.service, self._last_operation_handle)
def close_operation(self):
if self._last_operation_active:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
def execute(self, operation, parameters=None, configuration=None):
# PEP 249
if configuration is None:
configuration = {}
def op():
if parameters:
self._last_operation_string = _bind_parameters(operation,
parameters)
else:
self._last_operation_string = operation
query = rpc.create_beeswax_query(self._last_operation_string,
self.user, configuration)
self._last_operation_handle = rpc.execute_statement(self.service,
query)
self._execute_sync(op)
def _execute_sync(self, operation_fn):
# operation_fn should set self._last_operation_string and
# self._last_operation_handle
self._reset_state()
operation_fn()
self._last_operation_active = True
self._wait_to_finish() # make execute synchronous
if self.has_result_set:
schema = rpc.get_results_metadata(
self.service, self._last_operation_handle)
self._description = [tuple([tup.name, tup.type.upper()] +
[None, None, None, None, None])
for tup in schema]
else:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
def _reset_state(self):
self._buffer = []
self._rowcount = -1
self._description = None
if self._last_operation_active:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
self._last_operation_string = None
self._last_operation_handle = None
def _wait_to_finish(self):
loop_start = time.time()
while True:
operation_state = rpc.get_query_state(
self.service, self._last_operation_handle)
if operation_state == self.query_state["FINISHED"]:
break
elif operation_state == self.query_state["EXCEPTION"]:
raise OperationalError(self.get_log())
time.sleep(self._get_sleep_interval(loop_start))
def _get_sleep_interval(self, start_time):
"""Returns a step function of time to sleep in seconds before polling
again. Maximum sleep is 1s, minimum is 0.1s"""
elapsed = time.time() - start_time
if elapsed < 10.0:
return 0.1
elif elapsed < 60.0:
return 0.5
return 1.0
def executemany(self, operation, seq_of_parameters):
# PEP 249
for parameters in seq_of_parameters:
self.execute(operation, parameters)
if self.has_result_set:
raise ProgrammingError("Operations that have result sets are "
"not allowed with executemany.")
def fetchone(self):
# PEP 249
if not self.has_result_set:
raise ProgrammingError("Tried to fetch but no results.")
try:
return next(self)
except StopIteration:
return None
def fetchmany(self, size=None):
# PEP 249
if not self.has_result_set:
raise ProgrammingError("Tried to fetch but no results.")
if size is None:
size = self.arraysize
local_buffer = []
i = 0
while i < size:
try:
local_buffer.append(next(self))
i += 1
except StopIteration:
break
return local_buffer
def fetchall(self):
# PEP 249
try:
return list(self)
except StopIteration:
return []
def setinputsizes(self, sizes):
# PEP 249
pass
def setoutputsize(self, size, column=None):
# PEP 249
pass
def __iter__(self):
return self
def __next__(self):
if not self.has_result_set:
raise ProgrammingError(
"Trying to fetch results on an operation with no results.")
if len(self._buffer) > 0:
return self._buffer.pop(0)
elif self._last_operation_active:
# self._buffer is empty here and op is active: try to pull
# more rows
rows = rpc.fetch_internal(self.service,
self._last_operation_handle,
self.buffersize)
self._buffer.extend(rows)
if len(self._buffer) == 0:
self._last_operation_active = False
rpc.close_query(self.service, self._last_operation_handle)
raise StopIteration
return self._buffer.pop(0)
else:
# empty buffer and op is now closed: raise StopIteration
raise StopIteration
def ping(self):
"""Checks connection to server by requesting some info
from the server.
"""
return rpc.ping(self.service)
def get_log(self):
return rpc.get_warning_log(self.service, self._last_operation_handle)
def get_profile(self):
return rpc.get_runtime_profile(
self.service, self._last_operation_handle)
def get_summary(self):
return rpc.get_summary(self.service, self._last_operation_handle)
def build_summary_table(self, summary, output, idx=0,
is_fragment_root=False, indent_level=0):
return rpc.build_summary_table(
summary, idx, is_fragment_root, indent_level, output) | return self._rowcount
@property | random_line_split |
tasks.py | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from celery.decorators import task
from socialbeer.posts.models import Post
from socialbeer.core.utils import expand_urls
from socialbeer.members.models import Profile
from socialregistration.models import TwitterProfile
@task()
def | (status, *args, **kwargs):
try:
profile = Profile.objects.get(user__twitterprofile__twitter_id=status.user.id)
except:
user,created = User.objects.get_or_create(username=status.author.screen_name)
twitter_profile, created = TwitterProfile.objects.get_or_create(user=user, site=Site.objects.get_current(), twitter_id=status.user.id)
profile = Profile.objects.get(user=user, user__twitterprofile=twitter_profile)
try:
obj, created = Post.objects.get_or_create(author=profile.user, tweet_id=status.id)
except:
created=False
if created:
obj.content=expand_urls(status.text)
obj.pub_date = status.created_at
try:
obj.parent_post = Post.objects.get(tweet_id=status.in_reply_to_status_id)
except:
pass
try:
retweeted_status = Post.objects.get(tweet_id=status.retweeted_status.id)
retweeted_status.retweets.add(obj)
retweeted_status.save()
obj.retweet = True
except:
pass
obj.save()
return True
| process_tweet | identifier_name |
tasks.py | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from celery.decorators import task
from socialbeer.posts.models import Post
from socialbeer.core.utils import expand_urls
from socialbeer.members.models import Profile
from socialregistration.models import TwitterProfile
@task()
def process_tweet(status, *args, **kwargs):
| try:
profile = Profile.objects.get(user__twitterprofile__twitter_id=status.user.id)
except:
user,created = User.objects.get_or_create(username=status.author.screen_name)
twitter_profile, created = TwitterProfile.objects.get_or_create(user=user, site=Site.objects.get_current(), twitter_id=status.user.id)
profile = Profile.objects.get(user=user, user__twitterprofile=twitter_profile)
try:
obj, created = Post.objects.get_or_create(author=profile.user, tweet_id=status.id)
except:
created=False
if created:
obj.content=expand_urls(status.text)
obj.pub_date = status.created_at
try:
obj.parent_post = Post.objects.get(tweet_id=status.in_reply_to_status_id)
except:
pass
try:
retweeted_status = Post.objects.get(tweet_id=status.retweeted_status.id)
retweeted_status.retweets.add(obj)
retweeted_status.save()
obj.retweet = True
except:
pass
obj.save()
return True | identifier_body |
|
tasks.py | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from celery.decorators import task
from socialbeer.posts.models import Post
from socialbeer.core.utils import expand_urls
from socialbeer.members.models import Profile
from socialregistration.models import TwitterProfile
@task()
def process_tweet(status, *args, **kwargs):
try:
profile = Profile.objects.get(user__twitterprofile__twitter_id=status.user.id)
except:
user,created = User.objects.get_or_create(username=status.author.screen_name)
twitter_profile, created = TwitterProfile.objects.get_or_create(user=user, site=Site.objects.get_current(), twitter_id=status.user.id)
profile = Profile.objects.get(user=user, user__twitterprofile=twitter_profile)
try:
obj, created = Post.objects.get_or_create(author=profile.user, tweet_id=status.id)
except:
created=False
if created:
|
return True
| obj.content=expand_urls(status.text)
obj.pub_date = status.created_at
try:
obj.parent_post = Post.objects.get(tweet_id=status.in_reply_to_status_id)
except:
pass
try:
retweeted_status = Post.objects.get(tweet_id=status.retweeted_status.id)
retweeted_status.retweets.add(obj)
retweeted_status.save()
obj.retweet = True
except:
pass
obj.save() | conditional_block |
tasks.py | from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from celery.decorators import task
from socialbeer.posts.models import Post
from socialbeer.core.utils import expand_urls
from socialbeer.members.models import Profile
from socialregistration.models import TwitterProfile
@task()
def process_tweet(status, *args, **kwargs):
try:
profile = Profile.objects.get(user__twitterprofile__twitter_id=status.user.id)
except:
user,created = User.objects.get_or_create(username=status.author.screen_name)
twitter_profile, created = TwitterProfile.objects.get_or_create(user=user, site=Site.objects.get_current(), twitter_id=status.user.id)
profile = Profile.objects.get(user=user, user__twitterprofile=twitter_profile)
try:
obj, created = Post.objects.get_or_create(author=profile.user, tweet_id=status.id)
except:
created=False
if created:
obj.content=expand_urls(status.text)
obj.pub_date = status.created_at
try:
obj.parent_post = Post.objects.get(tweet_id=status.in_reply_to_status_id)
except: |
try:
retweeted_status = Post.objects.get(tweet_id=status.retweeted_status.id)
retweeted_status.retweets.add(obj)
retweeted_status.save()
obj.retweet = True
except:
pass
obj.save()
return True | pass | random_line_split |
generator.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from datetime import date
from ggrc import db
from ggrc import builder
from ggrc_workflows.models import (Workflow, TaskGroup, TaskGroupTask,
TaskGroupObject, Cycle)
from tests.ggrc.generator import Generator
import random
import copy
class WorkflowsGenerator(Generator):
def generate_workflow(self, data={}):
""" create a workflow with dict data
return: wf if it was created, or response otherwise
"""
obj_name = "workflow"
data = copy.deepcopy(data)
tgs = data.pop("task_groups", [])
wf = Workflow(title="wf " + self.random_str())
obj_dict = self.obj_to_dict(wf, obj_name)
obj_dict[obj_name].update(data)
response, workflow = self.generate(Workflow, obj_name, obj_dict)
for tg in tgs:
self.generate_task_group(workflow, tg)
return response, workflow
def generate_task_group(self, workflow=None, data={}):
if not workflow:
_, workflow = self.generate_workflow()
data = copy.deepcopy(data)
tgts = data.pop("task_group_tasks", [])
tgos = data.pop("task_group_objects", [])
obj_name = "task_group"
workflow = self._session_add(workflow)
tg = TaskGroup(
title="tg " + self.random_str(),
workflow_id=workflow.id,
context_id=workflow.context.id,
contact_id=1
)
obj_dict = self.obj_to_dict(tg, obj_name)
obj_dict[obj_name].update(data)
response, task_group = self.generate(TaskGroup, obj_name, obj_dict)
for tgt in tgts:
self.generate_task_group_task(task_group, tgt)
for tgo in tgos:
self.generate_task_group_object(task_group, tgo)
return response, task_group
def generate_task_group_task(self, task_group=None, data={}):
if not task_group:
_, task_group = self.generate_task_group()
task_group = self._session_add(task_group)
default_start = self.random_date()
default_end = self.random_date(default_start, date.today())
day_range = 5 if task_group.workflow.frequency == "weekly" else 31
obj_name = "task_group_task"
tgt = TaskGroupTask(
task_group_id=task_group.id,
context_id=task_group.context.id,
title="tgt " + self.random_str(),
start_date=default_start,
end_date=default_end,
relative_start_day=random.randrange(1, day_range),
relative_start_month=random.randrange(1, 12),
relative_end_day=random.randrange(1, day_range),
relative_end_month=random.randrange(1, 12),
contact_id=1
)
obj_dict = self.obj_to_dict(tgt, obj_name)
obj_dict[obj_name].update(data)
return self.generate(TaskGroupTask, obj_name, obj_dict)
def | (self, task_group=None, obj=None):
if not task_group:
_, task_group = self.generate_task_group()
task_group = self._session_add(task_group)
obj = self._session_add(obj)
obj_name = "task_group_object"
tgo = TaskGroupObject(
object_id=obj.id,
object=obj,
task_group_id=task_group.id,
context_id=task_group.context.id
)
obj_dict = self.obj_to_dict(tgo, obj_name)
return self.generate(TaskGroupObject, obj_name, obj_dict)
def generate_cycle(self, workflow=None):
if not workflow:
_, workflow = self.generate_workflow()
workflow = self._session_add(workflow) # this should be nicer
obj_name = "cycle"
obj_dict = {
obj_name: {
"workflow": {
"id": workflow.id,
"type": workflow.__class__.__name__,
"href": "/api/workflows/%d" % workflow.id
},
"context": {
"id": workflow.context.id,
"type": workflow.context.__class__.__name__,
"href": "/api/workflows/%d" % workflow.context.id
},
"autogenerate": "true"
}
}
return self.generate(Cycle, obj_name, obj_dict)
def activate_workflow(self, workflow):
workflow = self._session_add(workflow)
return self.modify_workflow(workflow, {
"status": "Active",
"recurrences": workflow.frequency != "one_time"
})
def modify_workflow(self, wf=None, data={}):
if not wf:
_, wf = self.generate_workflow()
wf = self._session_add(wf)
obj_name = "workflow"
obj_dict = builder.json.publish(wf)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
default = {obj_name: obj_dict}
response, workflow = self.modify(wf, obj_name, default)
return response, workflow
def modify_object(self, obj, data={}):
obj = self._session_add(obj)
obj_name = obj._inflector.table_singular
obj_dict = builder.json.publish(obj)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
obj_data = {obj_name: obj_dict}
response, generated_object = self.modify(obj, obj_name, obj_data)
return response, generated_object
def _session_add(self, obj):
""" Sometimes tests throw conflicting state present error."""
try:
db.session.add(obj)
return obj
except:
return obj.__class__.query.get(obj.id)
| generate_task_group_object | identifier_name |
generator.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from datetime import date
from ggrc import db
from ggrc import builder
from ggrc_workflows.models import (Workflow, TaskGroup, TaskGroupTask,
TaskGroupObject, Cycle)
from tests.ggrc.generator import Generator
import random
import copy
class WorkflowsGenerator(Generator):
def generate_workflow(self, data={}):
""" create a workflow with dict data
return: wf if it was created, or response otherwise
"""
obj_name = "workflow"
data = copy.deepcopy(data)
tgs = data.pop("task_groups", [])
wf = Workflow(title="wf " + self.random_str())
obj_dict = self.obj_to_dict(wf, obj_name)
obj_dict[obj_name].update(data)
response, workflow = self.generate(Workflow, obj_name, obj_dict)
for tg in tgs:
self.generate_task_group(workflow, tg)
return response, workflow
def generate_task_group(self, workflow=None, data={}):
if not workflow:
_, workflow = self.generate_workflow()
data = copy.deepcopy(data)
tgts = data.pop("task_group_tasks", [])
tgos = data.pop("task_group_objects", [])
obj_name = "task_group"
workflow = self._session_add(workflow)
tg = TaskGroup(
title="tg " + self.random_str(),
workflow_id=workflow.id,
context_id=workflow.context.id,
contact_id=1
)
obj_dict = self.obj_to_dict(tg, obj_name)
obj_dict[obj_name].update(data)
response, task_group = self.generate(TaskGroup, obj_name, obj_dict)
for tgt in tgts:
self.generate_task_group_task(task_group, tgt)
for tgo in tgos:
self.generate_task_group_object(task_group, tgo)
return response, task_group
def generate_task_group_task(self, task_group=None, data={}):
if not task_group:
_, task_group = self.generate_task_group()
task_group = self._session_add(task_group)
default_start = self.random_date()
default_end = self.random_date(default_start, date.today())
day_range = 5 if task_group.workflow.frequency == "weekly" else 31
obj_name = "task_group_task"
tgt = TaskGroupTask(
task_group_id=task_group.id,
context_id=task_group.context.id,
title="tgt " + self.random_str(),
start_date=default_start,
end_date=default_end,
relative_start_day=random.randrange(1, day_range),
relative_start_month=random.randrange(1, 12),
relative_end_day=random.randrange(1, day_range),
relative_end_month=random.randrange(1, 12),
contact_id=1
)
obj_dict = self.obj_to_dict(tgt, obj_name)
obj_dict[obj_name].update(data)
return self.generate(TaskGroupTask, obj_name, obj_dict)
def generate_task_group_object(self, task_group=None, obj=None):
if not task_group:
_, task_group = self.generate_task_group()
task_group = self._session_add(task_group)
obj = self._session_add(obj)
obj_name = "task_group_object"
tgo = TaskGroupObject(
object_id=obj.id,
object=obj,
task_group_id=task_group.id,
context_id=task_group.context.id
)
obj_dict = self.obj_to_dict(tgo, obj_name)
return self.generate(TaskGroupObject, obj_name, obj_dict)
def generate_cycle(self, workflow=None):
if not workflow:
_, workflow = self.generate_workflow()
workflow = self._session_add(workflow) # this should be nicer
obj_name = "cycle"
obj_dict = {
obj_name: {
"workflow": {
"id": workflow.id,
"type": workflow.__class__.__name__,
"href": "/api/workflows/%d" % workflow.id
},
"context": {
"id": workflow.context.id,
"type": workflow.context.__class__.__name__,
"href": "/api/workflows/%d" % workflow.context.id
},
"autogenerate": "true"
}
}
return self.generate(Cycle, obj_name, obj_dict)
def activate_workflow(self, workflow):
workflow = self._session_add(workflow)
return self.modify_workflow(workflow, { | if not wf:
_, wf = self.generate_workflow()
wf = self._session_add(wf)
obj_name = "workflow"
obj_dict = builder.json.publish(wf)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
default = {obj_name: obj_dict}
response, workflow = self.modify(wf, obj_name, default)
return response, workflow
def modify_object(self, obj, data={}):
obj = self._session_add(obj)
obj_name = obj._inflector.table_singular
obj_dict = builder.json.publish(obj)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
obj_data = {obj_name: obj_dict}
response, generated_object = self.modify(obj, obj_name, obj_data)
return response, generated_object
def _session_add(self, obj):
""" Sometimes tests throw conflicting state present error."""
try:
db.session.add(obj)
return obj
except:
return obj.__class__.query.get(obj.id) | "status": "Active",
"recurrences": workflow.frequency != "one_time"
})
def modify_workflow(self, wf=None, data={}): | random_line_split |
generator.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from datetime import date
from ggrc import db
from ggrc import builder
from ggrc_workflows.models import (Workflow, TaskGroup, TaskGroupTask,
TaskGroupObject, Cycle)
from tests.ggrc.generator import Generator
import random
import copy
class WorkflowsGenerator(Generator):
def generate_workflow(self, data={}):
""" create a workflow with dict data
return: wf if it was created, or response otherwise
"""
obj_name = "workflow"
data = copy.deepcopy(data)
tgs = data.pop("task_groups", [])
wf = Workflow(title="wf " + self.random_str())
obj_dict = self.obj_to_dict(wf, obj_name)
obj_dict[obj_name].update(data)
response, workflow = self.generate(Workflow, obj_name, obj_dict)
for tg in tgs:
self.generate_task_group(workflow, tg)
return response, workflow
def generate_task_group(self, workflow=None, data={}):
if not workflow:
_, workflow = self.generate_workflow()
data = copy.deepcopy(data)
tgts = data.pop("task_group_tasks", [])
tgos = data.pop("task_group_objects", [])
obj_name = "task_group"
workflow = self._session_add(workflow)
tg = TaskGroup(
title="tg " + self.random_str(),
workflow_id=workflow.id,
context_id=workflow.context.id,
contact_id=1
)
obj_dict = self.obj_to_dict(tg, obj_name)
obj_dict[obj_name].update(data)
response, task_group = self.generate(TaskGroup, obj_name, obj_dict)
for tgt in tgts:
self.generate_task_group_task(task_group, tgt)
for tgo in tgos:
self.generate_task_group_object(task_group, tgo)
return response, task_group
def generate_task_group_task(self, task_group=None, data={}):
if not task_group:
_, task_group = self.generate_task_group()
task_group = self._session_add(task_group)
default_start = self.random_date()
default_end = self.random_date(default_start, date.today())
day_range = 5 if task_group.workflow.frequency == "weekly" else 31
obj_name = "task_group_task"
tgt = TaskGroupTask(
task_group_id=task_group.id,
context_id=task_group.context.id,
title="tgt " + self.random_str(),
start_date=default_start,
end_date=default_end,
relative_start_day=random.randrange(1, day_range),
relative_start_month=random.randrange(1, 12),
relative_end_day=random.randrange(1, day_range),
relative_end_month=random.randrange(1, 12),
contact_id=1
)
obj_dict = self.obj_to_dict(tgt, obj_name)
obj_dict[obj_name].update(data)
return self.generate(TaskGroupTask, obj_name, obj_dict)
def generate_task_group_object(self, task_group=None, obj=None):
if not task_group:
_, task_group = self.generate_task_group()
task_group = self._session_add(task_group)
obj = self._session_add(obj)
obj_name = "task_group_object"
tgo = TaskGroupObject(
object_id=obj.id,
object=obj,
task_group_id=task_group.id,
context_id=task_group.context.id
)
obj_dict = self.obj_to_dict(tgo, obj_name)
return self.generate(TaskGroupObject, obj_name, obj_dict)
def generate_cycle(self, workflow=None):
|
def activate_workflow(self, workflow):
workflow = self._session_add(workflow)
return self.modify_workflow(workflow, {
"status": "Active",
"recurrences": workflow.frequency != "one_time"
})
def modify_workflow(self, wf=None, data={}):
if not wf:
_, wf = self.generate_workflow()
wf = self._session_add(wf)
obj_name = "workflow"
obj_dict = builder.json.publish(wf)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
default = {obj_name: obj_dict}
response, workflow = self.modify(wf, obj_name, default)
return response, workflow
def modify_object(self, obj, data={}):
obj = self._session_add(obj)
obj_name = obj._inflector.table_singular
obj_dict = builder.json.publish(obj)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
obj_data = {obj_name: obj_dict}
response, generated_object = self.modify(obj, obj_name, obj_data)
return response, generated_object
def _session_add(self, obj):
""" Sometimes tests throw conflicting state present error."""
try:
db.session.add(obj)
return obj
except:
return obj.__class__.query.get(obj.id)
| if not workflow:
_, workflow = self.generate_workflow()
workflow = self._session_add(workflow) # this should be nicer
obj_name = "cycle"
obj_dict = {
obj_name: {
"workflow": {
"id": workflow.id,
"type": workflow.__class__.__name__,
"href": "/api/workflows/%d" % workflow.id
},
"context": {
"id": workflow.context.id,
"type": workflow.context.__class__.__name__,
"href": "/api/workflows/%d" % workflow.context.id
},
"autogenerate": "true"
}
}
return self.generate(Cycle, obj_name, obj_dict) | identifier_body |
generator.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from datetime import date
from ggrc import db
from ggrc import builder
from ggrc_workflows.models import (Workflow, TaskGroup, TaskGroupTask,
TaskGroupObject, Cycle)
from tests.ggrc.generator import Generator
import random
import copy
class WorkflowsGenerator(Generator):
def generate_workflow(self, data={}):
""" create a workflow with dict data
return: wf if it was created, or response otherwise
"""
obj_name = "workflow"
data = copy.deepcopy(data)
tgs = data.pop("task_groups", [])
wf = Workflow(title="wf " + self.random_str())
obj_dict = self.obj_to_dict(wf, obj_name)
obj_dict[obj_name].update(data)
response, workflow = self.generate(Workflow, obj_name, obj_dict)
for tg in tgs:
self.generate_task_group(workflow, tg)
return response, workflow
def generate_task_group(self, workflow=None, data={}):
if not workflow:
_, workflow = self.generate_workflow()
data = copy.deepcopy(data)
tgts = data.pop("task_group_tasks", [])
tgos = data.pop("task_group_objects", [])
obj_name = "task_group"
workflow = self._session_add(workflow)
tg = TaskGroup(
title="tg " + self.random_str(),
workflow_id=workflow.id,
context_id=workflow.context.id,
contact_id=1
)
obj_dict = self.obj_to_dict(tg, obj_name)
obj_dict[obj_name].update(data)
response, task_group = self.generate(TaskGroup, obj_name, obj_dict)
for tgt in tgts:
self.generate_task_group_task(task_group, tgt)
for tgo in tgos:
self.generate_task_group_object(task_group, tgo)
return response, task_group
def generate_task_group_task(self, task_group=None, data={}):
if not task_group:
_, task_group = self.generate_task_group()
task_group = self._session_add(task_group)
default_start = self.random_date()
default_end = self.random_date(default_start, date.today())
day_range = 5 if task_group.workflow.frequency == "weekly" else 31
obj_name = "task_group_task"
tgt = TaskGroupTask(
task_group_id=task_group.id,
context_id=task_group.context.id,
title="tgt " + self.random_str(),
start_date=default_start,
end_date=default_end,
relative_start_day=random.randrange(1, day_range),
relative_start_month=random.randrange(1, 12),
relative_end_day=random.randrange(1, day_range),
relative_end_month=random.randrange(1, 12),
contact_id=1
)
obj_dict = self.obj_to_dict(tgt, obj_name)
obj_dict[obj_name].update(data)
return self.generate(TaskGroupTask, obj_name, obj_dict)
def generate_task_group_object(self, task_group=None, obj=None):
if not task_group:
|
task_group = self._session_add(task_group)
obj = self._session_add(obj)
obj_name = "task_group_object"
tgo = TaskGroupObject(
object_id=obj.id,
object=obj,
task_group_id=task_group.id,
context_id=task_group.context.id
)
obj_dict = self.obj_to_dict(tgo, obj_name)
return self.generate(TaskGroupObject, obj_name, obj_dict)
def generate_cycle(self, workflow=None):
if not workflow:
_, workflow = self.generate_workflow()
workflow = self._session_add(workflow) # this should be nicer
obj_name = "cycle"
obj_dict = {
obj_name: {
"workflow": {
"id": workflow.id,
"type": workflow.__class__.__name__,
"href": "/api/workflows/%d" % workflow.id
},
"context": {
"id": workflow.context.id,
"type": workflow.context.__class__.__name__,
"href": "/api/workflows/%d" % workflow.context.id
},
"autogenerate": "true"
}
}
return self.generate(Cycle, obj_name, obj_dict)
def activate_workflow(self, workflow):
workflow = self._session_add(workflow)
return self.modify_workflow(workflow, {
"status": "Active",
"recurrences": workflow.frequency != "one_time"
})
def modify_workflow(self, wf=None, data={}):
if not wf:
_, wf = self.generate_workflow()
wf = self._session_add(wf)
obj_name = "workflow"
obj_dict = builder.json.publish(wf)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
default = {obj_name: obj_dict}
response, workflow = self.modify(wf, obj_name, default)
return response, workflow
def modify_object(self, obj, data={}):
obj = self._session_add(obj)
obj_name = obj._inflector.table_singular
obj_dict = builder.json.publish(obj)
builder.json.publish_representation(obj_dict)
obj_dict.update(data)
obj_data = {obj_name: obj_dict}
response, generated_object = self.modify(obj, obj_name, obj_data)
return response, generated_object
def _session_add(self, obj):
""" Sometimes tests throw conflicting state present error."""
try:
db.session.add(obj)
return obj
except:
return obj.__class__.query.get(obj.id)
| _, task_group = self.generate_task_group() | conditional_block |
gen_models.py | import csv
def model_name(table_name):
|
def quote(s):
assert '"' not in s
return '"' + s + '"'
with open('schema.csv') as f:
lines = list(csv.DictReader(f))
print('from django.db import models')
table = None
for line in lines:
if line['table'] == 'ccontent':
continue
if line['table'] != table:
table = line['table']
print()
print()
print(f'class {model_name(table)}(models.Model):')
print('# class Meta:')
print('# verbose_name = "TODO"')
print()
if line['type'] == 'retired':
continue
options = []
if line['primary_key'] == 'True':
options.append(('primary_key', 'True'))
if line['db_column']:
options.append(('db_column', quote(line['db_column'])))
if line['type'] in ['ForeignKey', 'OneToOneField']:
options.append(('to', quote(model_name(line['to']))))
options.append(('on_delete', 'models.CASCADE'))
if 'prevcd' in line['db_column'] or 'uomcd' in line['db_column']:
options.append(('related_name', quote('+')))
elif line['type'] == 'CharField':
options.append(('max_length', line['max_length']))
elif line['type'] == 'DecimalField':
options.append(('max_digits', line['max_digits']))
options.append(('decimal_places', line['decimal_places']))
if line['optional'] == 'Y':
if line['type'] != 'BooleanField' and line['primary_key'] != 'True':
options.append(('null', 'True'))
options.append(('help_text', quote(line['descr'])))
print(f' {line["field"]} = models.{line["type"]}(')
for k, v in options:
print(f' {k}={v},')
print(' )')
| if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_')) | identifier_body |
gen_models.py | import csv
def model_name(table_name):
if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_'))
def | (s):
assert '"' not in s
return '"' + s + '"'
with open('schema.csv') as f:
lines = list(csv.DictReader(f))
print('from django.db import models')
table = None
for line in lines:
if line['table'] == 'ccontent':
continue
if line['table'] != table:
table = line['table']
print()
print()
print(f'class {model_name(table)}(models.Model):')
print('# class Meta:')
print('# verbose_name = "TODO"')
print()
if line['type'] == 'retired':
continue
options = []
if line['primary_key'] == 'True':
options.append(('primary_key', 'True'))
if line['db_column']:
options.append(('db_column', quote(line['db_column'])))
if line['type'] in ['ForeignKey', 'OneToOneField']:
options.append(('to', quote(model_name(line['to']))))
options.append(('on_delete', 'models.CASCADE'))
if 'prevcd' in line['db_column'] or 'uomcd' in line['db_column']:
options.append(('related_name', quote('+')))
elif line['type'] == 'CharField':
options.append(('max_length', line['max_length']))
elif line['type'] == 'DecimalField':
options.append(('max_digits', line['max_digits']))
options.append(('decimal_places', line['decimal_places']))
if line['optional'] == 'Y':
if line['type'] != 'BooleanField' and line['primary_key'] != 'True':
options.append(('null', 'True'))
options.append(('help_text', quote(line['descr'])))
print(f' {line["field"]} = models.{line["type"]}(')
for k, v in options:
print(f' {k}={v},')
print(' )')
| quote | identifier_name |
gen_models.py | import csv
def model_name(table_name):
if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_'))
def quote(s):
assert '"' not in s
return '"' + s + '"'
with open('schema.csv') as f:
lines = list(csv.DictReader(f))
print('from django.db import models')
table = None
for line in lines:
if line['table'] == 'ccontent':
continue
if line['table'] != table:
table = line['table']
print()
print()
print(f'class {model_name(table)}(models.Model):')
print('# class Meta:')
print('# verbose_name = "TODO"')
print()
if line['type'] == 'retired':
continue
options = []
if line['primary_key'] == 'True':
options.append(('primary_key', 'True'))
if line['db_column']:
|
if line['type'] in ['ForeignKey', 'OneToOneField']:
options.append(('to', quote(model_name(line['to']))))
options.append(('on_delete', 'models.CASCADE'))
if 'prevcd' in line['db_column'] or 'uomcd' in line['db_column']:
options.append(('related_name', quote('+')))
elif line['type'] == 'CharField':
options.append(('max_length', line['max_length']))
elif line['type'] == 'DecimalField':
options.append(('max_digits', line['max_digits']))
options.append(('decimal_places', line['decimal_places']))
if line['optional'] == 'Y':
if line['type'] != 'BooleanField' and line['primary_key'] != 'True':
options.append(('null', 'True'))
options.append(('help_text', quote(line['descr'])))
print(f' {line["field"]} = models.{line["type"]}(')
for k, v in options:
print(f' {k}={v},')
print(' )')
| options.append(('db_column', quote(line['db_column']))) | conditional_block |
gen_models.py | import csv
def model_name(table_name):
if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_'))
def quote(s):
assert '"' not in s
return '"' + s + '"'
with open('schema.csv') as f:
lines = list(csv.DictReader(f))
print('from django.db import models')
table = None
for line in lines:
if line['table'] == 'ccontent':
continue
if line['table'] != table:
table = line['table']
print()
print()
print(f'class {model_name(table)}(models.Model):')
print('# class Meta:')
print('# verbose_name = "TODO"')
print()
if line['type'] == 'retired':
continue
options = []
if line['primary_key'] == 'True':
options.append(('primary_key', 'True'))
if line['db_column']:
options.append(('db_column', quote(line['db_column'])))
if line['type'] in ['ForeignKey', 'OneToOneField']:
options.append(('to', quote(model_name(line['to']))))
options.append(('on_delete', 'models.CASCADE'))
if 'prevcd' in line['db_column'] or 'uomcd' in line['db_column']:
options.append(('related_name', quote('+')))
elif line['type'] == 'CharField':
options.append(('max_length', line['max_length']))
elif line['type'] == 'DecimalField':
options.append(('max_digits', line['max_digits']))
options.append(('decimal_places', line['decimal_places']))
if line['optional'] == 'Y': | if line['type'] != 'BooleanField' and line['primary_key'] != 'True':
options.append(('null', 'True'))
options.append(('help_text', quote(line['descr'])))
print(f' {line["field"]} = models.{line["type"]}(')
for k, v in options:
print(f' {k}={v},')
print(' )') | random_line_split |
|
fold.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed |
use clean::*;
use std::iter::Extendable;
use std::mem::{replace, swap};
pub trait DocFolder {
fn fold_item(&mut self, item: Item) -> Option<Item> {
self.fold_item_recur(item)
}
/// don't override!
fn fold_item_recur(&mut self, item: Item) -> Option<Item> {
let Item { attrs, name, source, visibility, def_id, inner } = item;
let inner = inner;
let inner = match inner {
StructItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.fields);
let num_fields = foo.len();
i.fields.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
i.fields_stripped |= num_fields != i.fields.len();
StructItem(i)
},
ModuleItem(i) => {
ModuleItem(self.fold_mod(i))
},
EnumItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.variants);
let num_variants = foo.len();
i.variants.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
i.variants_stripped |= num_variants != i.variants.len();
EnumItem(i)
},
TraitItem(mut i) => {
fn vtrm<T: DocFolder>(this: &mut T, trm: TraitMethod) -> Option<TraitMethod> {
match trm {
Required(it) => {
match this.fold_item(it) {
Some(x) => return Some(Required(x)),
None => return None,
}
},
Provided(it) => {
match this.fold_item(it) {
Some(x) => return Some(Provided(x)),
None => return None,
}
},
}
}
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| vtrm(self, x)));
TraitItem(i)
},
ImplItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
ImplItem(i)
},
VariantItem(i) => {
let i2 = i.clone(); // this clone is small
match i.kind {
StructVariant(mut j) => {
let mut foo = Vec::new(); swap(&mut foo, &mut j.fields);
let num_fields = foo.len();
let c = |x| self.fold_item(x);
j.fields.extend(foo.move_iter().filter_map(c));
j.fields_stripped |= num_fields != j.fields.len();
VariantItem(Variant {kind: StructVariant(j), ..i2})
},
_ => VariantItem(i2)
}
},
x => x
};
Some(Item { attrs: attrs, name: name, source: source, inner: inner,
visibility: visibility, def_id: def_id })
}
fn fold_mod(&mut self, m: Module) -> Module {
Module {
is_crate: m.is_crate,
items: m.items.move_iter().filter_map(|i| self.fold_item(i)).collect()
}
}
fn fold_crate(&mut self, mut c: Crate) -> Crate {
c.module = match replace(&mut c.module, None) {
Some(module) => self.fold_item(module), None => None
};
return c;
}
} | // except according to those terms. | random_line_split |
fold.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use clean::*;
use std::iter::Extendable;
use std::mem::{replace, swap};
pub trait DocFolder {
fn fold_item(&mut self, item: Item) -> Option<Item> {
self.fold_item_recur(item)
}
/// don't override!
fn fold_item_recur(&mut self, item: Item) -> Option<Item> {
let Item { attrs, name, source, visibility, def_id, inner } = item;
let inner = inner;
let inner = match inner {
StructItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.fields);
let num_fields = foo.len();
i.fields.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
i.fields_stripped |= num_fields != i.fields.len();
StructItem(i)
},
ModuleItem(i) => {
ModuleItem(self.fold_mod(i))
},
EnumItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.variants);
let num_variants = foo.len();
i.variants.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
i.variants_stripped |= num_variants != i.variants.len();
EnumItem(i)
},
TraitItem(mut i) => {
fn vtrm<T: DocFolder>(this: &mut T, trm: TraitMethod) -> Option<TraitMethod> {
match trm {
Required(it) => {
match this.fold_item(it) {
Some(x) => return Some(Required(x)),
None => return None,
}
},
Provided(it) => {
match this.fold_item(it) {
Some(x) => return Some(Provided(x)),
None => return None,
}
},
}
}
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| vtrm(self, x)));
TraitItem(i)
},
ImplItem(mut i) => | ,
VariantItem(i) => {
let i2 = i.clone(); // this clone is small
match i.kind {
StructVariant(mut j) => {
let mut foo = Vec::new(); swap(&mut foo, &mut j.fields);
let num_fields = foo.len();
let c = |x| self.fold_item(x);
j.fields.extend(foo.move_iter().filter_map(c));
j.fields_stripped |= num_fields != j.fields.len();
VariantItem(Variant {kind: StructVariant(j), ..i2})
},
_ => VariantItem(i2)
}
},
x => x
};
Some(Item { attrs: attrs, name: name, source: source, inner: inner,
visibility: visibility, def_id: def_id })
}
fn fold_mod(&mut self, m: Module) -> Module {
Module {
is_crate: m.is_crate,
items: m.items.move_iter().filter_map(|i| self.fold_item(i)).collect()
}
}
fn fold_crate(&mut self, mut c: Crate) -> Crate {
c.module = match replace(&mut c.module, None) {
Some(module) => self.fold_item(module), None => None
};
return c;
}
}
| {
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
ImplItem(i)
} | conditional_block |
fold.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use clean::*;
use std::iter::Extendable;
use std::mem::{replace, swap};
pub trait DocFolder {
fn fold_item(&mut self, item: Item) -> Option<Item> {
self.fold_item_recur(item)
}
/// don't override!
fn fold_item_recur(&mut self, item: Item) -> Option<Item> {
let Item { attrs, name, source, visibility, def_id, inner } = item;
let inner = inner;
let inner = match inner {
StructItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.fields);
let num_fields = foo.len();
i.fields.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
i.fields_stripped |= num_fields != i.fields.len();
StructItem(i)
},
ModuleItem(i) => {
ModuleItem(self.fold_mod(i))
},
EnumItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.variants);
let num_variants = foo.len();
i.variants.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
i.variants_stripped |= num_variants != i.variants.len();
EnumItem(i)
},
TraitItem(mut i) => {
fn vtrm<T: DocFolder>(this: &mut T, trm: TraitMethod) -> Option<TraitMethod> {
match trm {
Required(it) => {
match this.fold_item(it) {
Some(x) => return Some(Required(x)),
None => return None,
}
},
Provided(it) => {
match this.fold_item(it) {
Some(x) => return Some(Provided(x)),
None => return None,
}
},
}
}
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| vtrm(self, x)));
TraitItem(i)
},
ImplItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
ImplItem(i)
},
VariantItem(i) => {
let i2 = i.clone(); // this clone is small
match i.kind {
StructVariant(mut j) => {
let mut foo = Vec::new(); swap(&mut foo, &mut j.fields);
let num_fields = foo.len();
let c = |x| self.fold_item(x);
j.fields.extend(foo.move_iter().filter_map(c));
j.fields_stripped |= num_fields != j.fields.len();
VariantItem(Variant {kind: StructVariant(j), ..i2})
},
_ => VariantItem(i2)
}
},
x => x
};
Some(Item { attrs: attrs, name: name, source: source, inner: inner,
visibility: visibility, def_id: def_id })
}
fn fold_mod(&mut self, m: Module) -> Module |
fn fold_crate(&mut self, mut c: Crate) -> Crate {
c.module = match replace(&mut c.module, None) {
Some(module) => self.fold_item(module), None => None
};
return c;
}
}
| {
Module {
is_crate: m.is_crate,
items: m.items.move_iter().filter_map(|i| self.fold_item(i)).collect()
}
} | identifier_body |
fold.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use clean::*;
use std::iter::Extendable;
use std::mem::{replace, swap};
pub trait DocFolder {
fn fold_item(&mut self, item: Item) -> Option<Item> {
self.fold_item_recur(item)
}
/// don't override!
fn fold_item_recur(&mut self, item: Item) -> Option<Item> {
let Item { attrs, name, source, visibility, def_id, inner } = item;
let inner = inner;
let inner = match inner {
StructItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.fields);
let num_fields = foo.len();
i.fields.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
i.fields_stripped |= num_fields != i.fields.len();
StructItem(i)
},
ModuleItem(i) => {
ModuleItem(self.fold_mod(i))
},
EnumItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.variants);
let num_variants = foo.len();
i.variants.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
i.variants_stripped |= num_variants != i.variants.len();
EnumItem(i)
},
TraitItem(mut i) => {
fn | <T: DocFolder>(this: &mut T, trm: TraitMethod) -> Option<TraitMethod> {
match trm {
Required(it) => {
match this.fold_item(it) {
Some(x) => return Some(Required(x)),
None => return None,
}
},
Provided(it) => {
match this.fold_item(it) {
Some(x) => return Some(Provided(x)),
None => return None,
}
},
}
}
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| vtrm(self, x)));
TraitItem(i)
},
ImplItem(mut i) => {
let mut foo = Vec::new(); swap(&mut foo, &mut i.methods);
i.methods.extend(foo.move_iter().filter_map(|x| self.fold_item(x)));
ImplItem(i)
},
VariantItem(i) => {
let i2 = i.clone(); // this clone is small
match i.kind {
StructVariant(mut j) => {
let mut foo = Vec::new(); swap(&mut foo, &mut j.fields);
let num_fields = foo.len();
let c = |x| self.fold_item(x);
j.fields.extend(foo.move_iter().filter_map(c));
j.fields_stripped |= num_fields != j.fields.len();
VariantItem(Variant {kind: StructVariant(j), ..i2})
},
_ => VariantItem(i2)
}
},
x => x
};
Some(Item { attrs: attrs, name: name, source: source, inner: inner,
visibility: visibility, def_id: def_id })
}
fn fold_mod(&mut self, m: Module) -> Module {
Module {
is_crate: m.is_crate,
items: m.items.move_iter().filter_map(|i| self.fold_item(i)).collect()
}
}
fn fold_crate(&mut self, mut c: Crate) -> Crate {
c.module = match replace(&mut c.module, None) {
Some(module) => self.fold_item(module), None => None
};
return c;
}
}
| vtrm | identifier_name |
issue-17718-static-unsafe-interior.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use std::cell::UnsafeCell;
struct MyUnsafe<T> {
value: UnsafeCell<T>
}
impl<T> MyUnsafe<T> {
fn forbidden(&self) {}
}
enum UnsafeEnum<T> {
VariantSafe,
VariantUnsafe(UnsafeCell<T>)
}
static STATIC1: UnsafeEnum<int> = VariantSafe;
static STATIC2: UnsafeCell<int> = UnsafeCell { value: 1 };
const CONST: UnsafeCell<int> = UnsafeCell { value: 1 };
static STATIC3: MyUnsafe<int> = MyUnsafe{value: CONST};
static STATIC4: &'static UnsafeCell<int> = &STATIC2;
struct Wrap<T> {
value: T
}
static UNSAFE: UnsafeCell<int> = UnsafeCell{value: 1};
static WRAPPED_UNSAFE: Wrap<&'static UnsafeCell<int>> = Wrap { value: &UNSAFE };
fn main() {
let a = &STATIC1;
STATIC3.forbidden()
} | // 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 | random_line_split |
issue-17718-static-unsafe-interior.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.
use std::kinds::marker;
use std::cell::UnsafeCell;
struct MyUnsafe<T> {
value: UnsafeCell<T>
}
impl<T> MyUnsafe<T> {
fn forbidden(&self) {}
}
enum | <T> {
VariantSafe,
VariantUnsafe(UnsafeCell<T>)
}
static STATIC1: UnsafeEnum<int> = VariantSafe;
static STATIC2: UnsafeCell<int> = UnsafeCell { value: 1 };
const CONST: UnsafeCell<int> = UnsafeCell { value: 1 };
static STATIC3: MyUnsafe<int> = MyUnsafe{value: CONST};
static STATIC4: &'static UnsafeCell<int> = &STATIC2;
struct Wrap<T> {
value: T
}
static UNSAFE: UnsafeCell<int> = UnsafeCell{value: 1};
static WRAPPED_UNSAFE: Wrap<&'static UnsafeCell<int>> = Wrap { value: &UNSAFE };
fn main() {
let a = &STATIC1;
STATIC3.forbidden()
}
| UnsafeEnum | identifier_name |
forms.py | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = ContactUs
fields = '__all__'
widgets = {
'email': forms.EmailInput({'required': 'required',
'placeholder': 'Email'}),
'message': forms.Textarea(attrs={'required': 'required',
'placeholder': 'Message'})
}
def | (self):
first_name = self.cleaned_data['first_name']
if not first_name.isalpha():
raise forms.ValidationError("Introdu un prenume valid")
return first_name
def clean_email(self):
email = self.cleaned_data['email']
if validate_email(email):
raise forms.ValidationError("Adresa de email nu e valida")
return email
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
if not last_name.isalpha():
raise forms.ValidationError("Introdu un nume corect")
return last_name
def clean_message(self):
message = self.cleaned_data['message']
if len(message) < 50:
raise forms.ValidationError(
"Mesajul tau e prea scurt!"
"Trebuie sa contina minim 50 de caractere")
return message | clean_first_name | identifier_name |
forms.py | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField() | fields = '__all__'
widgets = {
'email': forms.EmailInput({'required': 'required',
'placeholder': 'Email'}),
'message': forms.Textarea(attrs={'required': 'required',
'placeholder': 'Message'})
}
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
if not first_name.isalpha():
raise forms.ValidationError("Introdu un prenume valid")
return first_name
def clean_email(self):
email = self.cleaned_data['email']
if validate_email(email):
raise forms.ValidationError("Adresa de email nu e valida")
return email
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
if not last_name.isalpha():
raise forms.ValidationError("Introdu un nume corect")
return last_name
def clean_message(self):
message = self.cleaned_data['message']
if len(message) < 50:
raise forms.ValidationError(
"Mesajul tau e prea scurt!"
"Trebuie sa contina minim 50 de caractere")
return message |
class Meta:
model = ContactUs | random_line_split |
forms.py | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = ContactUs
fields = '__all__'
widgets = {
'email': forms.EmailInput({'required': 'required',
'placeholder': 'Email'}),
'message': forms.Textarea(attrs={'required': 'required',
'placeholder': 'Message'})
}
def clean_first_name(self):
|
def clean_email(self):
email = self.cleaned_data['email']
if validate_email(email):
raise forms.ValidationError("Adresa de email nu e valida")
return email
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
if not last_name.isalpha():
raise forms.ValidationError("Introdu un nume corect")
return last_name
def clean_message(self):
message = self.cleaned_data['message']
if len(message) < 50:
raise forms.ValidationError(
"Mesajul tau e prea scurt!"
"Trebuie sa contina minim 50 de caractere")
return message | first_name = self.cleaned_data['first_name']
if not first_name.isalpha():
raise forms.ValidationError("Introdu un prenume valid")
return first_name | identifier_body |
forms.py | from django.core.validators import validate_email
from django import forms
from captcha.fields import ReCaptchaField
from .models import ContactUs
class CreateContact(forms.ModelForm):
captcha = ReCaptchaField()
class Meta:
model = ContactUs
fields = '__all__'
widgets = {
'email': forms.EmailInput({'required': 'required',
'placeholder': 'Email'}),
'message': forms.Textarea(attrs={'required': 'required',
'placeholder': 'Message'})
}
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
if not first_name.isalpha():
raise forms.ValidationError("Introdu un prenume valid")
return first_name
def clean_email(self):
email = self.cleaned_data['email']
if validate_email(email):
raise forms.ValidationError("Adresa de email nu e valida")
return email
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
if not last_name.isalpha():
raise forms.ValidationError("Introdu un nume corect")
return last_name
def clean_message(self):
message = self.cleaned_data['message']
if len(message) < 50:
|
return message | raise forms.ValidationError(
"Mesajul tau e prea scurt!"
"Trebuie sa contina minim 50 de caractere") | conditional_block |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use bytecode_source_map::utils::{remap_owned_loc_to_loc, source_map_from_file, OwnedLoc};
use move_bytecode_viewer::{
bytecode_viewer::BytecodeViewer, source_viewer::ModuleViewer,
tui::tui_interface::start_tui_with_interface, viewer::Viewer,
};
use std::{fs, path::Path};
use structopt::StructOpt;
use vm::file_format::CompiledModule;
#[derive(Debug, StructOpt)]
#[structopt(
name = "Move Bytecode Explorer",
about = "Explore Move bytecode and how the source code compiles to it"
)]
struct Args {
/// The path to the module binary
#[structopt(long = "module-path", short = "b")]
pub module_binary_path: String,
/// The path to the source file
#[structopt(long = "source-path", short = "s")]
pub source_file_path: String,
}
pub fn | () {
let args = Args::from_args();
let source_map_extension = "mvsm";
let bytecode_bytes = fs::read(&args.module_binary_path).expect("Unable to read bytecode file");
let compiled_module =
CompiledModule::deserialize(&bytecode_bytes).expect("Module blob can't be deserialized");
let source_map = source_map_from_file::<OwnedLoc>(
&Path::new(&args.module_binary_path).with_extension(source_map_extension),
)
.map(remap_owned_loc_to_loc)
.unwrap();
let source_path = Path::new(&args.source_file_path);
let module_viewer =
ModuleViewer::new(compiled_module.clone(), source_map.clone(), &source_path);
let bytecode_viewer = BytecodeViewer::new(source_map, compiled_module);
let interface = Viewer::new(module_viewer, bytecode_viewer);
start_tui_with_interface(interface).unwrap();
}
| main | identifier_name |
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use bytecode_source_map::utils::{remap_owned_loc_to_loc, source_map_from_file, OwnedLoc};
use move_bytecode_viewer::{
bytecode_viewer::BytecodeViewer, source_viewer::ModuleViewer,
tui::tui_interface::start_tui_with_interface, viewer::Viewer,
};
use std::{fs, path::Path};
use structopt::StructOpt;
use vm::file_format::CompiledModule;
#[derive(Debug, StructOpt)]
#[structopt(
name = "Move Bytecode Explorer",
about = "Explore Move bytecode and how the source code compiles to it"
)]
struct Args {
/// The path to the module binary
#[structopt(long = "module-path", short = "b")]
pub module_binary_path: String,
/// The path to the source file
#[structopt(long = "source-path", short = "s")]
pub source_file_path: String,
}
pub fn main() | {
let args = Args::from_args();
let source_map_extension = "mvsm";
let bytecode_bytes = fs::read(&args.module_binary_path).expect("Unable to read bytecode file");
let compiled_module =
CompiledModule::deserialize(&bytecode_bytes).expect("Module blob can't be deserialized");
let source_map = source_map_from_file::<OwnedLoc>(
&Path::new(&args.module_binary_path).with_extension(source_map_extension),
)
.map(remap_owned_loc_to_loc)
.unwrap();
let source_path = Path::new(&args.source_file_path);
let module_viewer =
ModuleViewer::new(compiled_module.clone(), source_map.clone(), &source_path);
let bytecode_viewer = BytecodeViewer::new(source_map, compiled_module);
let interface = Viewer::new(module_viewer, bytecode_viewer);
start_tui_with_interface(interface).unwrap();
} | identifier_body |
|
main.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use bytecode_source_map::utils::{remap_owned_loc_to_loc, source_map_from_file, OwnedLoc};
use move_bytecode_viewer::{
bytecode_viewer::BytecodeViewer, source_viewer::ModuleViewer,
tui::tui_interface::start_tui_with_interface, viewer::Viewer,
};
| use structopt::StructOpt;
use vm::file_format::CompiledModule;
#[derive(Debug, StructOpt)]
#[structopt(
name = "Move Bytecode Explorer",
about = "Explore Move bytecode and how the source code compiles to it"
)]
struct Args {
/// The path to the module binary
#[structopt(long = "module-path", short = "b")]
pub module_binary_path: String,
/// The path to the source file
#[structopt(long = "source-path", short = "s")]
pub source_file_path: String,
}
pub fn main() {
let args = Args::from_args();
let source_map_extension = "mvsm";
let bytecode_bytes = fs::read(&args.module_binary_path).expect("Unable to read bytecode file");
let compiled_module =
CompiledModule::deserialize(&bytecode_bytes).expect("Module blob can't be deserialized");
let source_map = source_map_from_file::<OwnedLoc>(
&Path::new(&args.module_binary_path).with_extension(source_map_extension),
)
.map(remap_owned_loc_to_loc)
.unwrap();
let source_path = Path::new(&args.source_file_path);
let module_viewer =
ModuleViewer::new(compiled_module.clone(), source_map.clone(), &source_path);
let bytecode_viewer = BytecodeViewer::new(source_map, compiled_module);
let interface = Viewer::new(module_viewer, bytecode_viewer);
start_tui_with_interface(interface).unwrap();
} | use std::{fs, path::Path}; | random_line_split |
gann.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def print_usage():
print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark>
Gann sub square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark> -r "<left>;<bottom>;<right>;<up>"
input date format: "dd/MM/yyyy"
"""
def main(argv):
cell_size = 30
date_format = "%d/%m/%Y"
# --------------------------------------
output_file_name = ''
marks_file_name = ''
square_size = -1
date_a = None
date_b = None
left, bot, right, up = 0, 0, 0, 0
# --------------------------------------
try:
opts, args = getopt.getopt(argv, "ho:s:a:b:m:r:", ["ofile=", "size=", "a_date=", "b_date=", "mfile=", "rect="])
except getopt.GetoptError:
print_usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print_usage()
sys.exit()
elif opt in ("-o", "--ofile"):
output_file_name = arg
elif opt in ("-s", "--size"):
square_size = int(arg)
elif opt in ("-a", "--a_date"):
date_a = datetime.strptime(arg, date_format)
elif opt in ("-b", "--b_date"):
date_b = datetime.strptime(arg, date_format)
elif opt in ("-m", "--mfile"):
marks_file_name = arg
elif opt in ("-r", "--rect"):
rect = arg.split(';')
try:
left, bot, right, up = int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3])
except ValueError as e:
print 'Failed to parse range!'
if output_file_name == '':
print_usage()
sys.exit(2)
if square_size != -1:
# classic Gann square
# Info
print "Cells: %i" % (square_size * square_size)
print "Square size: %i" % square_size
print "Cell size: %i" % cell_size
print "Building..."
stream = open(output_file_name, 'w')
create_gann_square_classic(square_size, cell_size, stream)
stream.close()
elif date_a and date_b:
# date based Gann square
delta = date_b - date_a
square_size = int(math.ceil(math.sqrt(delta.days)))
if square_size % 2 == 0:
square_size += 1
# Info
print "Cells: %i" % (square_size * square_size)
print "Square size: %i" % square_size
print "Cell size: %i" % cell_size
# Process
print "Loading data..."
marks = load_marks(marks_file_name)
print "Building..."
stream = open(output_file_name, 'w') | else:
print_usage()
sys.exit(2)
print "Done. See {0}".format(output_file_name)
if __name__ == "__main__":
main(sys.argv[1:]) | if (left != 0 or bot != 0 or right != 0 or up != 0) and left < right and bot < up:
create_gann_sub_square_dates((left, bot, right+1, up+1), cell_size, date_a, marks, stream)
else:
create_gann_square_dates(square_size, cell_size, date_a, marks, stream)
stream.close() | random_line_split |
gann.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def | ():
print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark>
Gann sub square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark> -r "<left>;<bottom>;<right>;<up>"
input date format: "dd/MM/yyyy"
"""
def main(argv):
cell_size = 30
date_format = "%d/%m/%Y"
# --------------------------------------
output_file_name = ''
marks_file_name = ''
square_size = -1
date_a = None
date_b = None
left, bot, right, up = 0, 0, 0, 0
# --------------------------------------
try:
opts, args = getopt.getopt(argv, "ho:s:a:b:m:r:", ["ofile=", "size=", "a_date=", "b_date=", "mfile=", "rect="])
except getopt.GetoptError:
print_usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print_usage()
sys.exit()
elif opt in ("-o", "--ofile"):
output_file_name = arg
elif opt in ("-s", "--size"):
square_size = int(arg)
elif opt in ("-a", "--a_date"):
date_a = datetime.strptime(arg, date_format)
elif opt in ("-b", "--b_date"):
date_b = datetime.strptime(arg, date_format)
elif opt in ("-m", "--mfile"):
marks_file_name = arg
elif opt in ("-r", "--rect"):
rect = arg.split(';')
try:
left, bot, right, up = int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3])
except ValueError as e:
print 'Failed to parse range!'
if output_file_name == '':
print_usage()
sys.exit(2)
if square_size != -1:
# classic Gann square
# Info
print "Cells: %i" % (square_size * square_size)
print "Square size: %i" % square_size
print "Cell size: %i" % cell_size
print "Building..."
stream = open(output_file_name, 'w')
create_gann_square_classic(square_size, cell_size, stream)
stream.close()
elif date_a and date_b:
# date based Gann square
delta = date_b - date_a
square_size = int(math.ceil(math.sqrt(delta.days)))
if square_size % 2 == 0:
square_size += 1
# Info
print "Cells: %i" % (square_size * square_size)
print "Square size: %i" % square_size
print "Cell size: %i" % cell_size
# Process
print "Loading data..."
marks = load_marks(marks_file_name)
print "Building..."
stream = open(output_file_name, 'w')
if (left != 0 or bot != 0 or right != 0 or up != 0) and left < right and bot < up:
create_gann_sub_square_dates((left, bot, right+1, up+1), cell_size, date_a, marks, stream)
else:
create_gann_square_dates(square_size, cell_size, date_a, marks, stream)
stream.close()
else:
print_usage()
sys.exit(2)
print "Done. See {0}".format(output_file_name)
if __name__ == "__main__":
main(sys.argv[1:]) | print_usage | identifier_name |
gann.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def print_usage():
|
def main(argv):
cell_size = 30
date_format = "%d/%m/%Y"
# --------------------------------------
output_file_name = ''
marks_file_name = ''
square_size = -1
date_a = None
date_b = None
left, bot, right, up = 0, 0, 0, 0
# --------------------------------------
try:
opts, args = getopt.getopt(argv, "ho:s:a:b:m:r:", ["ofile=", "size=", "a_date=", "b_date=", "mfile=", "rect="])
except getopt.GetoptError:
print_usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print_usage()
sys.exit()
elif opt in ("-o", "--ofile"):
output_file_name = arg
elif opt in ("-s", "--size"):
square_size = int(arg)
elif opt in ("-a", "--a_date"):
date_a = datetime.strptime(arg, date_format)
elif opt in ("-b", "--b_date"):
date_b = datetime.strptime(arg, date_format)
elif opt in ("-m", "--mfile"):
marks_file_name = arg
elif opt in ("-r", "--rect"):
rect = arg.split(';')
try:
left, bot, right, up = int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3])
except ValueError as e:
print 'Failed to parse range!'
if output_file_name == '':
print_usage()
sys.exit(2)
if square_size != -1:
# classic Gann square
# Info
print "Cells: %i" % (square_size * square_size)
print "Square size: %i" % square_size
print "Cell size: %i" % cell_size
print "Building..."
stream = open(output_file_name, 'w')
create_gann_square_classic(square_size, cell_size, stream)
stream.close()
elif date_a and date_b:
# date based Gann square
delta = date_b - date_a
square_size = int(math.ceil(math.sqrt(delta.days)))
if square_size % 2 == 0:
square_size += 1
# Info
print "Cells: %i" % (square_size * square_size)
print "Square size: %i" % square_size
print "Cell size: %i" % cell_size
# Process
print "Loading data..."
marks = load_marks(marks_file_name)
print "Building..."
stream = open(output_file_name, 'w')
if (left != 0 or bot != 0 or right != 0 or up != 0) and left < right and bot < up:
create_gann_sub_square_dates((left, bot, right+1, up+1), cell_size, date_a, marks, stream)
else:
create_gann_square_dates(square_size, cell_size, date_a, marks, stream)
stream.close()
else:
print_usage()
sys.exit(2)
print "Done. See {0}".format(output_file_name)
if __name__ == "__main__":
main(sys.argv[1:]) | print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark>
Gann sub square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark> -r "<left>;<bottom>;<right>;<up>"
input date format: "dd/MM/yyyy"
""" | identifier_body |
gann.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def print_usage():
print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark>
Gann sub square based on date: gann.py -o <output file name> -a <base date> -b <final date> -m <path to list of dates to mark> -r "<left>;<bottom>;<right>;<up>"
input date format: "dd/MM/yyyy"
"""
def main(argv):
cell_size = 30
date_format = "%d/%m/%Y"
# --------------------------------------
output_file_name = ''
marks_file_name = ''
square_size = -1
date_a = None
date_b = None
left, bot, right, up = 0, 0, 0, 0
# --------------------------------------
try:
opts, args = getopt.getopt(argv, "ho:s:a:b:m:r:", ["ofile=", "size=", "a_date=", "b_date=", "mfile=", "rect="])
except getopt.GetoptError:
print_usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print_usage()
sys.exit()
elif opt in ("-o", "--ofile"):
output_file_name = arg
elif opt in ("-s", "--size"):
square_size = int(arg)
elif opt in ("-a", "--a_date"):
date_a = datetime.strptime(arg, date_format)
elif opt in ("-b", "--b_date"):
|
elif opt in ("-m", "--mfile"):
marks_file_name = arg
elif opt in ("-r", "--rect"):
rect = arg.split(';')
try:
left, bot, right, up = int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3])
except ValueError as e:
print 'Failed to parse range!'
if output_file_name == '':
print_usage()
sys.exit(2)
if square_size != -1:
# classic Gann square
# Info
print "Cells: %i" % (square_size * square_size)
print "Square size: %i" % square_size
print "Cell size: %i" % cell_size
print "Building..."
stream = open(output_file_name, 'w')
create_gann_square_classic(square_size, cell_size, stream)
stream.close()
elif date_a and date_b:
# date based Gann square
delta = date_b - date_a
square_size = int(math.ceil(math.sqrt(delta.days)))
if square_size % 2 == 0:
square_size += 1
# Info
print "Cells: %i" % (square_size * square_size)
print "Square size: %i" % square_size
print "Cell size: %i" % cell_size
# Process
print "Loading data..."
marks = load_marks(marks_file_name)
print "Building..."
stream = open(output_file_name, 'w')
if (left != 0 or bot != 0 or right != 0 or up != 0) and left < right and bot < up:
create_gann_sub_square_dates((left, bot, right+1, up+1), cell_size, date_a, marks, stream)
else:
create_gann_square_dates(square_size, cell_size, date_a, marks, stream)
stream.close()
else:
print_usage()
sys.exit(2)
print "Done. See {0}".format(output_file_name)
if __name__ == "__main__":
main(sys.argv[1:]) | date_b = datetime.strptime(arg, date_format) | conditional_block |
manual_flatten.rs | use super::utils::make_iterator_snippet;
use super::MANUAL_FLATTEN;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::higher;
use clippy_utils::visitors::is_local_used;
use clippy_utils::{is_lang_ctor, path_to_local_id};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::LangItem::{OptionSome, ResultOk};
use rustc_hir::{Expr, ExprKind, Pat, PatKind, StmtKind};
use rustc_lint::LateContext;
use rustc_middle::ty;
use rustc_span::source_map::Span;
/// Check for unnecessary `if let` usage in a for loop where only the `Some` or `Ok` variant of the
/// iterator element is used.
pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
pat: &'tcx Pat<'_>,
arg: &'tcx Expr<'_>,
body: &'tcx Expr<'_>,
span: Span,
) {
if let ExprKind::Block(block, _) = body.kind {
// Ensure the `if let` statement is the only expression or statement in the for-loop
let inner_expr = if block.stmts.len() == 1 && block.expr.is_none() {
let match_stmt = &block.stmts[0];
if let StmtKind::Semi(inner_expr) = match_stmt.kind | else {
None
}
} else if block.stmts.is_empty() {
block.expr
} else {
None
};
if_chain! {
if let Some(inner_expr) = inner_expr;
if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else: None })
= higher::IfLet::hir(cx, inner_expr);
// Ensure match_expr in `if let` statement is the same as the pat from the for-loop
if let PatKind::Binding(_, pat_hir_id, _, _) = pat.kind;
if path_to_local_id(let_expr, pat_hir_id);
// Ensure the `if let` statement is for the `Some` variant of `Option` or the `Ok` variant of `Result`
if let PatKind::TupleStruct(ref qpath, _, _) = let_pat.kind;
let some_ctor = is_lang_ctor(cx, qpath, OptionSome);
let ok_ctor = is_lang_ctor(cx, qpath, ResultOk);
if some_ctor || ok_ctor;
// Ensure epxr in `if let` is not used afterwards
if !is_local_used(cx, if_then, pat_hir_id);
then {
let if_let_type = if some_ctor { "Some" } else { "Ok" };
// Prepare the error message
let msg = format!("unnecessary `if let` since only the `{}` variant of the iterator element is used", if_let_type);
// Prepare the help message
let mut applicability = Applicability::MaybeIncorrect;
let arg_snippet = make_iterator_snippet(cx, arg, &mut applicability);
let copied = match cx.typeck_results().expr_ty(let_expr).kind() {
ty::Ref(_, inner, _) => match inner.kind() {
ty::Ref(..) => ".copied()",
_ => ""
}
_ => ""
};
span_lint_and_then(
cx,
MANUAL_FLATTEN,
span,
&msg,
|diag| {
let sugg = format!("{}{}.flatten()", arg_snippet, copied);
diag.span_suggestion(
arg.span,
"try",
sugg,
Applicability::MaybeIncorrect,
);
diag.span_help(
inner_expr.span,
"...and remove the `if let` statement in the for loop",
);
}
);
}
}
}
}
| {
Some(inner_expr)
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.