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 |
|---|---|---|---|---|
app.py | import sys
sys.path.append('../..')
import web
from web.contrib.template import render_jinja
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from social.utils import setting_name
from social.apps.webpy_app.utils import psa, backends
from social.apps.webpy_app import app as social_app
import local_settings
web.config.debug = False
web.config[setting_name('USER_MODEL')] = 'models.User'
web.config[setting_name('AUTHENTICATION_BACKENDS')] = (
'social.backends.open_id.OpenIdAuth',
'social.backends.google.GoogleOpenId', | 'social.backends.stripe.StripeOAuth2',
'social.backends.persona.PersonaAuth',
'social.backends.facebook.FacebookOAuth2',
'social.backends.facebook.FacebookAppOAuth2',
'social.backends.yahoo.YahooOAuth',
'social.backends.angel.AngelOAuth2',
'social.backends.behance.BehanceOAuth2',
'social.backends.bitbucket.BitbucketOAuth',
'social.backends.box.BoxOAuth2',
'social.backends.linkedin.LinkedinOAuth',
'social.backends.github.GithubOAuth2',
'social.backends.foursquare.FoursquareOAuth2',
'social.backends.instagram.InstagramOAuth2',
'social.backends.live.LiveOAuth2',
'social.backends.vk.VKOAuth2',
'social.backends.dailymotion.DailymotionOAuth2',
'social.backends.disqus.DisqusOAuth2',
'social.backends.dropbox.DropboxOAuth',
'social.backends.eveonline.EVEOnlineOAuth2',
'social.backends.evernote.EvernoteSandboxOAuth',
'social.backends.fitbit.FitbitOAuth2',
'social.backends.flickr.FlickrOAuth',
'social.backends.livejournal.LiveJournalOpenId',
'social.backends.soundcloud.SoundcloudOAuth2',
'social.backends.thisismyjam.ThisIsMyJamOAuth1',
'social.backends.stocktwits.StocktwitsOAuth2',
'social.backends.tripit.TripItOAuth',
'social.backends.clef.ClefOAuth2',
'social.backends.twilio.TwilioAuth',
'social.backends.xing.XingOAuth',
'social.backends.yandex.YandexOAuth2',
'social.backends.podio.PodioOAuth2',
'social.backends.mineid.MineIDOAuth2',
'social.backends.wunderlist.WunderlistOAuth2',
'social.backends.upwork.UpworkOAuth',
)
web.config[setting_name('LOGIN_REDIRECT_URL')] = '/done/'
urls = (
'^/$', 'main',
'^/done/$', 'done',
'', social_app.app_social
)
render = render_jinja('templates/')
class main(object):
def GET(self):
return render.home()
class done(social_app.BaseViewClass):
def GET(self):
user = self.get_current_user()
return render.done(user=user, backends=backends(user))
engine = create_engine('sqlite:///test.db', echo=True)
def load_sqla(handler):
web.ctx.orm = scoped_session(sessionmaker(bind=engine))
try:
return handler()
except web.HTTPError:
web.ctx.orm.commit()
raise
except:
web.ctx.orm.rollback()
raise
finally:
web.ctx.orm.commit()
# web.ctx.orm.expunge_all()
Session = sessionmaker(bind=engine)
Session.configure(bind=engine)
app = web.application(urls, locals())
app.add_processor(load_sqla)
session = web.session.Session(app, web.session.DiskStore('sessions'))
web.db_session = Session()
web.web_session = session
if __name__ == "__main__":
app.run() | 'social.backends.google.GoogleOAuth2',
'social.backends.google.GoogleOAuth',
'social.backends.twitter.TwitterOAuth',
'social.backends.yahoo.YahooOpenId', | random_line_split |
csvsql.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit import CSVKitWriter
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate SQL statements for one or more CSV files, create execute those statements directly on a database, and execute one or more SQL queries.'
override_flags = ['l', 'f']
def add_arguments(self):
self.argparser.add_argument(metavar="FILE", nargs='*', dest='input_paths', default=['-'],
help='The CSV file(s) to operate on. If omitted, will accept input on STDIN.')
self.argparser.add_argument('-y', '--snifflimit', dest='snifflimit', type=int,
help='Limit CSV dialect sniffing to the specified number of bytes. Specify "0" to disable sniffing entirely.')
self.argparser.add_argument('-i', '--dialect', dest='dialect', choices=sql.DIALECTS,
help='Dialect of SQL to generate. Only valid when --db is not specified.')
self.argparser.add_argument('--db', dest='connection_string',
help='If present, a sqlalchemy connection string to use to directly execute generated SQL on a database.')
self.argparser.add_argument('--query', default=None,
help='Execute one or more SQL queries delimited by ";" and output the result of the last query as CSV.')
self.argparser.add_argument('--insert', dest='insert', action='store_true',
help='In addition to creating the table, also insert the data into the table. Only valid when --db is specified.')
self.argparser.add_argument('--tables', dest='table_names',
help='Specify one or more names for the tables to be created. If omitted, the filename (minus extension) or "stdin" will be used.')
self.argparser.add_argument('--no-constraints', dest='no_constraints', action='store_true',
help='Generate a schema without length limits or null checks. Useful when sampling big tables.')
self.argparser.add_argument('--no-create', dest='no_create', action='store_true',
help='Skip creating a table. Only valid when --insert is specified.')
self.argparser.add_argument('--blanks', dest='blanks', action='store_true',
help='Do not coerce empty strings to NULL values.')
self.argparser.add_argument('--no-inference', dest='no_inference', action='store_true',
help='Disable type inference when parsing the input.')
self.argparser.add_argument('--db-schema', dest='db_schema',
help='Optional name of database schema to create table(s) in.')
def main(self):
connection_string = self.args.connection_string
do_insert = self.args.insert
query = self.args.query
self.input_files = []
for path in self.args.input_paths:
|
if self.args.table_names:
table_names = self.args.table_names.split(',')
else:
table_names = []
# If one or more filenames are specified, we need to add stdin ourselves (if available)
if sys.stdin not in self.input_files:
try:
if not sys.stdin.isatty():
self.input_files.insert(0, oepn("/dev/stdin", "r", encoding="utf-8"))
except:
pass
# Create an SQLite database in memory if no connection string is specified
if query and not connection_string:
connection_string = "sqlite:///:memory:"
do_insert = True
if self.args.dialect and connection_string:
self.argparser.error('The --dialect option is only valid when --db is not specified.')
if do_insert and not connection_string:
self.argparser.error('The --insert option is only valid when --db is also specified.')
if self.args.no_create and not do_insert:
self.argparser.error('The --no-create option is only valid --insert is also specified.')
# Establish database validity before reading CSV files
if connection_string:
try:
engine, metadata = sql.get_connection(connection_string)
except ImportError:
raise ImportError('You don\'t appear to have the necessary database backend installed for connection string you\'re trying to use. Available backends include:\n\nPostgresql:\tpip install psycopg2\nMySQL:\t\tpip install MySQL-python\n\nFor details on connection strings and other backends, please see the SQLAlchemy documentation on dialects at: \n\nhttp://www.sqlalchemy.org/docs/dialects/\n\n')
conn = engine.connect()
trans = conn.begin()
for f in self.input_files:
try:
# Try to use name specified via --table
table_name = table_names.pop(0)
except IndexError:
if f == sys.stdin:
table_name = "stdin"
else:
# Use filename as table name
table_name = os.path.splitext(os.path.split(f.name)[1])[0]
csv_table = table.Table.from_csv(
f,
name=table_name,
snifflimit=self.args.snifflimit,
blanks_as_nulls=(not self.args.blanks),
infer_types=(not self.args.no_inference),
no_header_row=self.args.no_header_row,
**self.reader_kwargs
)
f.close()
if connection_string:
sql_table = sql.make_table(
csv_table,
table_name,
self.args.no_constraints,
self.args.db_schema,
metadata
)
# Create table
if not self.args.no_create:
sql_table.create()
# Insert data
if do_insert and csv_table.count_rows() > 0:
insert = sql_table.insert()
headers = csv_table.headers()
conn.execute(insert, [dict(zip(headers, row)) for row in csv_table.to_rows()])
# Output SQL statements
else:
sql_table = sql.make_table(csv_table, table_name, self.args.no_constraints)
self.output_file.write('%s\n' % sql.make_create_table_statement(sql_table, dialect=self.args.dialect))
if connection_string:
if query:
# Execute specified SQL queries
queries = query.split(';')
rows = None
for q in queries:
if q:
rows = conn.execute(q)
# Output result of last query as CSV
try:
output = CSVKitWriter(self.output_file, **self.writer_kwargs)
if not self.args.no_header_row:
output.writerow(rows._metadata.keys)
for row in rows:
output.writerow(row)
except AttributeError:
pass
trans.commit()
conn.close()
def launch_new_instance():
utility = CSVSQL()
utility.main()
if __name__ == "__main__":
launch_new_instance()
| self.input_files.append(self._open_input_file(path)) | conditional_block |
csvsql.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit import CSVKitWriter
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate SQL statements for one or more CSV files, create execute those statements directly on a database, and execute one or more SQL queries.'
override_flags = ['l', 'f']
def add_arguments(self):
self.argparser.add_argument(metavar="FILE", nargs='*', dest='input_paths', default=['-'],
help='The CSV file(s) to operate on. If omitted, will accept input on STDIN.')
self.argparser.add_argument('-y', '--snifflimit', dest='snifflimit', type=int,
help='Limit CSV dialect sniffing to the specified number of bytes. Specify "0" to disable sniffing entirely.')
self.argparser.add_argument('-i', '--dialect', dest='dialect', choices=sql.DIALECTS,
help='Dialect of SQL to generate. Only valid when --db is not specified.')
self.argparser.add_argument('--db', dest='connection_string',
help='If present, a sqlalchemy connection string to use to directly execute generated SQL on a database.')
self.argparser.add_argument('--query', default=None,
help='Execute one or more SQL queries delimited by ";" and output the result of the last query as CSV.')
self.argparser.add_argument('--insert', dest='insert', action='store_true',
help='In addition to creating the table, also insert the data into the table. Only valid when --db is specified.')
self.argparser.add_argument('--tables', dest='table_names',
help='Specify one or more names for the tables to be created. If omitted, the filename (minus extension) or "stdin" will be used.')
self.argparser.add_argument('--no-constraints', dest='no_constraints', action='store_true',
help='Generate a schema without length limits or null checks. Useful when sampling big tables.')
self.argparser.add_argument('--no-create', dest='no_create', action='store_true',
help='Skip creating a table. Only valid when --insert is specified.')
self.argparser.add_argument('--blanks', dest='blanks', action='store_true',
help='Do not coerce empty strings to NULL values.')
self.argparser.add_argument('--no-inference', dest='no_inference', action='store_true',
help='Disable type inference when parsing the input.')
self.argparser.add_argument('--db-schema', dest='db_schema',
help='Optional name of database schema to create table(s) in.')
def main(self):
connection_string = self.args.connection_string
do_insert = self.args.insert
query = self.args.query
self.input_files = []
for path in self.args.input_paths:
self.input_files.append(self._open_input_file(path))
if self.args.table_names:
table_names = self.args.table_names.split(',')
else:
table_names = []
# If one or more filenames are specified, we need to add stdin ourselves (if available)
if sys.stdin not in self.input_files:
try:
if not sys.stdin.isatty():
self.input_files.insert(0, oepn("/dev/stdin", "r", encoding="utf-8"))
except:
pass
# Create an SQLite database in memory if no connection string is specified
if query and not connection_string:
connection_string = "sqlite:///:memory:"
do_insert = True
if self.args.dialect and connection_string:
self.argparser.error('The --dialect option is only valid when --db is not specified.')
if do_insert and not connection_string:
self.argparser.error('The --insert option is only valid when --db is also specified.')
if self.args.no_create and not do_insert:
self.argparser.error('The --no-create option is only valid --insert is also specified.')
# Establish database validity before reading CSV files
if connection_string:
try:
engine, metadata = sql.get_connection(connection_string)
except ImportError:
raise ImportError('You don\'t appear to have the necessary database backend installed for connection string you\'re trying to use. Available backends include:\n\nPostgresql:\tpip install psycopg2\nMySQL:\t\tpip install MySQL-python\n\nFor details on connection strings and other backends, please see the SQLAlchemy documentation on dialects at: \n\nhttp://www.sqlalchemy.org/docs/dialects/\n\n')
conn = engine.connect()
trans = conn.begin()
for f in self.input_files:
try:
# Try to use name specified via --table
table_name = table_names.pop(0)
except IndexError:
if f == sys.stdin:
table_name = "stdin"
else:
# Use filename as table name
table_name = os.path.splitext(os.path.split(f.name)[1])[0]
csv_table = table.Table.from_csv(
f,
name=table_name,
snifflimit=self.args.snifflimit,
blanks_as_nulls=(not self.args.blanks),
infer_types=(not self.args.no_inference),
no_header_row=self.args.no_header_row,
**self.reader_kwargs
)
f.close()
if connection_string:
sql_table = sql.make_table(
csv_table,
table_name,
self.args.no_constraints,
self.args.db_schema,
metadata
)
# Create table
if not self.args.no_create:
sql_table.create()
# Insert data
if do_insert and csv_table.count_rows() > 0:
insert = sql_table.insert()
headers = csv_table.headers()
conn.execute(insert, [dict(zip(headers, row)) for row in csv_table.to_rows()])
# Output SQL statements
else:
sql_table = sql.make_table(csv_table, table_name, self.args.no_constraints)
self.output_file.write('%s\n' % sql.make_create_table_statement(sql_table, dialect=self.args.dialect))
if connection_string:
if query:
# Execute specified SQL queries
queries = query.split(';')
rows = None
for q in queries:
if q:
rows = conn.execute(q)
# Output result of last query as CSV
try:
output = CSVKitWriter(self.output_file, **self.writer_kwargs)
if not self.args.no_header_row:
output.writerow(rows._metadata.keys)
for row in rows:
output.writerow(row)
except AttributeError:
pass
trans.commit()
conn.close()
def launch_new_instance():
|
if __name__ == "__main__":
launch_new_instance()
| utility = CSVSQL()
utility.main() | identifier_body |
csvsql.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit import CSVKitWriter
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate SQL statements for one or more CSV files, create execute those statements directly on a database, and execute one or more SQL queries.'
override_flags = ['l', 'f']
def add_arguments(self):
self.argparser.add_argument(metavar="FILE", nargs='*', dest='input_paths', default=['-'],
help='The CSV file(s) to operate on. If omitted, will accept input on STDIN.')
self.argparser.add_argument('-y', '--snifflimit', dest='snifflimit', type=int,
help='Limit CSV dialect sniffing to the specified number of bytes. Specify "0" to disable sniffing entirely.')
self.argparser.add_argument('-i', '--dialect', dest='dialect', choices=sql.DIALECTS,
help='Dialect of SQL to generate. Only valid when --db is not specified.')
self.argparser.add_argument('--db', dest='connection_string',
help='If present, a sqlalchemy connection string to use to directly execute generated SQL on a database.')
self.argparser.add_argument('--query', default=None,
help='Execute one or more SQL queries delimited by ";" and output the result of the last query as CSV.')
self.argparser.add_argument('--insert', dest='insert', action='store_true',
help='In addition to creating the table, also insert the data into the table. Only valid when --db is specified.')
self.argparser.add_argument('--tables', dest='table_names',
help='Specify one or more names for the tables to be created. If omitted, the filename (minus extension) or "stdin" will be used.')
self.argparser.add_argument('--no-constraints', dest='no_constraints', action='store_true',
help='Generate a schema without length limits or null checks. Useful when sampling big tables.')
self.argparser.add_argument('--no-create', dest='no_create', action='store_true',
help='Skip creating a table. Only valid when --insert is specified.')
self.argparser.add_argument('--blanks', dest='blanks', action='store_true',
help='Do not coerce empty strings to NULL values.')
self.argparser.add_argument('--no-inference', dest='no_inference', action='store_true',
help='Disable type inference when parsing the input.')
self.argparser.add_argument('--db-schema', dest='db_schema',
help='Optional name of database schema to create table(s) in.')
def main(self):
connection_string = self.args.connection_string
do_insert = self.args.insert
query = self.args.query
self.input_files = []
| if self.args.table_names:
table_names = self.args.table_names.split(',')
else:
table_names = []
# If one or more filenames are specified, we need to add stdin ourselves (if available)
if sys.stdin not in self.input_files:
try:
if not sys.stdin.isatty():
self.input_files.insert(0, oepn("/dev/stdin", "r", encoding="utf-8"))
except:
pass
# Create an SQLite database in memory if no connection string is specified
if query and not connection_string:
connection_string = "sqlite:///:memory:"
do_insert = True
if self.args.dialect and connection_string:
self.argparser.error('The --dialect option is only valid when --db is not specified.')
if do_insert and not connection_string:
self.argparser.error('The --insert option is only valid when --db is also specified.')
if self.args.no_create and not do_insert:
self.argparser.error('The --no-create option is only valid --insert is also specified.')
# Establish database validity before reading CSV files
if connection_string:
try:
engine, metadata = sql.get_connection(connection_string)
except ImportError:
raise ImportError('You don\'t appear to have the necessary database backend installed for connection string you\'re trying to use. Available backends include:\n\nPostgresql:\tpip install psycopg2\nMySQL:\t\tpip install MySQL-python\n\nFor details on connection strings and other backends, please see the SQLAlchemy documentation on dialects at: \n\nhttp://www.sqlalchemy.org/docs/dialects/\n\n')
conn = engine.connect()
trans = conn.begin()
for f in self.input_files:
try:
# Try to use name specified via --table
table_name = table_names.pop(0)
except IndexError:
if f == sys.stdin:
table_name = "stdin"
else:
# Use filename as table name
table_name = os.path.splitext(os.path.split(f.name)[1])[0]
csv_table = table.Table.from_csv(
f,
name=table_name,
snifflimit=self.args.snifflimit,
blanks_as_nulls=(not self.args.blanks),
infer_types=(not self.args.no_inference),
no_header_row=self.args.no_header_row,
**self.reader_kwargs
)
f.close()
if connection_string:
sql_table = sql.make_table(
csv_table,
table_name,
self.args.no_constraints,
self.args.db_schema,
metadata
)
# Create table
if not self.args.no_create:
sql_table.create()
# Insert data
if do_insert and csv_table.count_rows() > 0:
insert = sql_table.insert()
headers = csv_table.headers()
conn.execute(insert, [dict(zip(headers, row)) for row in csv_table.to_rows()])
# Output SQL statements
else:
sql_table = sql.make_table(csv_table, table_name, self.args.no_constraints)
self.output_file.write('%s\n' % sql.make_create_table_statement(sql_table, dialect=self.args.dialect))
if connection_string:
if query:
# Execute specified SQL queries
queries = query.split(';')
rows = None
for q in queries:
if q:
rows = conn.execute(q)
# Output result of last query as CSV
try:
output = CSVKitWriter(self.output_file, **self.writer_kwargs)
if not self.args.no_header_row:
output.writerow(rows._metadata.keys)
for row in rows:
output.writerow(row)
except AttributeError:
pass
trans.commit()
conn.close()
def launch_new_instance():
utility = CSVSQL()
utility.main()
if __name__ == "__main__":
launch_new_instance() | for path in self.args.input_paths:
self.input_files.append(self._open_input_file(path))
| random_line_split |
csvsql.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from csvkit import sql
from csvkit import table
from csvkit import CSVKitWriter
from csvkit.cli import CSVKitUtility
class CSVSQL(CSVKitUtility):
description = 'Generate SQL statements for one or more CSV files, create execute those statements directly on a database, and execute one or more SQL queries.'
override_flags = ['l', 'f']
def add_arguments(self):
self.argparser.add_argument(metavar="FILE", nargs='*', dest='input_paths', default=['-'],
help='The CSV file(s) to operate on. If omitted, will accept input on STDIN.')
self.argparser.add_argument('-y', '--snifflimit', dest='snifflimit', type=int,
help='Limit CSV dialect sniffing to the specified number of bytes. Specify "0" to disable sniffing entirely.')
self.argparser.add_argument('-i', '--dialect', dest='dialect', choices=sql.DIALECTS,
help='Dialect of SQL to generate. Only valid when --db is not specified.')
self.argparser.add_argument('--db', dest='connection_string',
help='If present, a sqlalchemy connection string to use to directly execute generated SQL on a database.')
self.argparser.add_argument('--query', default=None,
help='Execute one or more SQL queries delimited by ";" and output the result of the last query as CSV.')
self.argparser.add_argument('--insert', dest='insert', action='store_true',
help='In addition to creating the table, also insert the data into the table. Only valid when --db is specified.')
self.argparser.add_argument('--tables', dest='table_names',
help='Specify one or more names for the tables to be created. If omitted, the filename (minus extension) or "stdin" will be used.')
self.argparser.add_argument('--no-constraints', dest='no_constraints', action='store_true',
help='Generate a schema without length limits or null checks. Useful when sampling big tables.')
self.argparser.add_argument('--no-create', dest='no_create', action='store_true',
help='Skip creating a table. Only valid when --insert is specified.')
self.argparser.add_argument('--blanks', dest='blanks', action='store_true',
help='Do not coerce empty strings to NULL values.')
self.argparser.add_argument('--no-inference', dest='no_inference', action='store_true',
help='Disable type inference when parsing the input.')
self.argparser.add_argument('--db-schema', dest='db_schema',
help='Optional name of database schema to create table(s) in.')
def main(self):
connection_string = self.args.connection_string
do_insert = self.args.insert
query = self.args.query
self.input_files = []
for path in self.args.input_paths:
self.input_files.append(self._open_input_file(path))
if self.args.table_names:
table_names = self.args.table_names.split(',')
else:
table_names = []
# If one or more filenames are specified, we need to add stdin ourselves (if available)
if sys.stdin not in self.input_files:
try:
if not sys.stdin.isatty():
self.input_files.insert(0, oepn("/dev/stdin", "r", encoding="utf-8"))
except:
pass
# Create an SQLite database in memory if no connection string is specified
if query and not connection_string:
connection_string = "sqlite:///:memory:"
do_insert = True
if self.args.dialect and connection_string:
self.argparser.error('The --dialect option is only valid when --db is not specified.')
if do_insert and not connection_string:
self.argparser.error('The --insert option is only valid when --db is also specified.')
if self.args.no_create and not do_insert:
self.argparser.error('The --no-create option is only valid --insert is also specified.')
# Establish database validity before reading CSV files
if connection_string:
try:
engine, metadata = sql.get_connection(connection_string)
except ImportError:
raise ImportError('You don\'t appear to have the necessary database backend installed for connection string you\'re trying to use. Available backends include:\n\nPostgresql:\tpip install psycopg2\nMySQL:\t\tpip install MySQL-python\n\nFor details on connection strings and other backends, please see the SQLAlchemy documentation on dialects at: \n\nhttp://www.sqlalchemy.org/docs/dialects/\n\n')
conn = engine.connect()
trans = conn.begin()
for f in self.input_files:
try:
# Try to use name specified via --table
table_name = table_names.pop(0)
except IndexError:
if f == sys.stdin:
table_name = "stdin"
else:
# Use filename as table name
table_name = os.path.splitext(os.path.split(f.name)[1])[0]
csv_table = table.Table.from_csv(
f,
name=table_name,
snifflimit=self.args.snifflimit,
blanks_as_nulls=(not self.args.blanks),
infer_types=(not self.args.no_inference),
no_header_row=self.args.no_header_row,
**self.reader_kwargs
)
f.close()
if connection_string:
sql_table = sql.make_table(
csv_table,
table_name,
self.args.no_constraints,
self.args.db_schema,
metadata
)
# Create table
if not self.args.no_create:
sql_table.create()
# Insert data
if do_insert and csv_table.count_rows() > 0:
insert = sql_table.insert()
headers = csv_table.headers()
conn.execute(insert, [dict(zip(headers, row)) for row in csv_table.to_rows()])
# Output SQL statements
else:
sql_table = sql.make_table(csv_table, table_name, self.args.no_constraints)
self.output_file.write('%s\n' % sql.make_create_table_statement(sql_table, dialect=self.args.dialect))
if connection_string:
if query:
# Execute specified SQL queries
queries = query.split(';')
rows = None
for q in queries:
if q:
rows = conn.execute(q)
# Output result of last query as CSV
try:
output = CSVKitWriter(self.output_file, **self.writer_kwargs)
if not self.args.no_header_row:
output.writerow(rows._metadata.keys)
for row in rows:
output.writerow(row)
except AttributeError:
pass
trans.commit()
conn.close()
def | ():
utility = CSVSQL()
utility.main()
if __name__ == "__main__":
launch_new_instance()
| launch_new_instance | identifier_name |
erdfparser.js | /**
* Copyright (c) 2006
*
* Philipp Berger, Martin Czuchra, Gero Decker, Ole Eckermann, Lutz Gericke,
* Alexander Hold, Alexander Koglin, Oliver Kopp, Stefan Krumnow,
* Matthias Kunze, Philipp Maschke, Falko Menge, Christoph Neijenhuis,
* Hagen Overdick, Zhen Peng, Nicolas Peters, Kerstin Pfitzner, Daniel Polak,
* Steffen Ryll, Kai Schlichting, Jan-Felix Schwarz, Daniel Taschik,
* Willi Tscheschner, Björn Wagner, Sven Wagner-Boysen, Matthias Weidlich
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
**/
var ERDF = {
LITERAL: 0x01,
RESOURCE: 0x02,
DELIMITERS: ['.', '-'],
HASH: '#',
HYPHEN: "-",
schemas: [],
callback: undefined,
log: undefined,
init: function(callback) {
// init logging.
//ERDF.log = Log4js.getLogger("oryx");
//ERDF.log.setLevel(Log4js.Level.ALL);
//ERDF.log.addAppender(new ConsoleAppender(ERDF.log, false));
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("ERDF Parser is initialized.");
// register callbacks and default schemas.
ERDF.callback = callback;
ERDF.registerSchema('schema', XMLNS.SCHEMA);
ERDF.registerSchema('rdfs', XMLNS.RDFS);
},
run: function() {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("ERDF Parser is running.");
// do the work.
return ERDF._checkProfile() && ERDF.parse();
},
parse: function() {
//(ERDF.log.isDebugEnabled())
// ERDF.log.debug("Begin parsing document metadata.");
// time measuring
ERDF.__startTime = new Date();
var bodies = document.getElementsByTagNameNS(XMLNS.XHTML, 'body');
var subject = {type: ERDF.RESOURCE, value: ''};
var result = ERDF._parseDocumentMetadata() &&
ERDF._parseFromTag(bodies[0], subject);
// time measuring
ERDF.__stopTime = new Date();
var duration = (ERDF.__stopTime - ERDF.__startTime)/1000.;
//alert('ERDF parsing took ' + duration + ' s.');
return result;
},
_parseDocumentMetadata: function() {
// get links from head element.
var heads = document.getElementsByTagNameNS(XMLNS.XHTML, 'head');
var links = heads[0].getElementsByTagNameNS(XMLNS.XHTML, 'link');
var metas = heads[0].getElementsByTagNameNS(XMLNS.XHTML, 'meta');
// process links first, since they could contain schema definitions.
$A(links).each(function(link) {
var properties = link.getAttribute('rel');
var reversedProperties = link.getAttribute('rev');
var value = link.getAttribute('href');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
properties,
ERDF.RESOURCE, value);
ERDF._parseTriplesFrom(
ERDF.RESOURCE, value,
reversedProperties,
ERDF.RESOURCE, '');
});
// continue with metas.
$A(metas).each(function(meta) {
var property = meta.getAttribute('name');
var value = meta.getAttribute('content');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
property,
ERDF.LITERAL, value);
});
return true;
},
_parseFromTag: function(node, subject, depth) {
// avoid parsing non-xhtml content.
if(!node || !node.namespaceURI || node.namespaceURI != XMLNS.XHTML) { return; }
// housekeeping.
if(!depth) depth=0;
var id = node.getAttribute('id');
// some logging.
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace(">".times(depth) + " Parsing " + node.nodeName + " ("+node.nodeType+") for data on " +
// ((subject.type == ERDF.RESOURCE) ? ('<' + subject.value + '>') : '') +
// ((subject.type == ERDF.LITERAL) ? '"' + subject.value + '"' : ''));
/* triple finding! */
// in a-tags...
if(node.nodeName.endsWith(':a') || node.nodeName == 'a') {
var properties = node.getAttribute('rel');
var reversedProperties = node.getAttribute('rev');
var value = node.getAttribute('href');
var title = node.getAttribute('title');
var content = node.textContent;
// rel triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.RESOURCE, value,
function(triple) {
var label = title? title : content;
// label triples
ERDF._parseTriplesFrom(
triple.object.type, triple.object.value,
'rdfs.label',
ERDF.LITERAL, label);
});
// rev triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
reversedProperties,
ERDF.RESOURCE, '');
// type triples
ERDF._parseTypeTriplesFrom(
subject.type, subject.value,
properties);
// in img-tags...
} else if(node.nodeName.endsWith(':img') || node.nodeName == 'img') {
var properties = node.getAttribute('class');
var value = node.getAttribute('src');
var alt = node.getAttribute('alt');
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.RESOURCE, value,
function(triple) {
var label = alt;
// label triples
ERDF._parseTriplesFrom(
triple.object.type, triple.object.value,
'rdfs.label',
ERDF.LITERAL, label);
});
}
// in every tag
var properties = node.getAttribute('class');
var title = node.getAttribute('title');
var content = node.textContent;
var label = title ? title : content;
// regular triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.LITERAL, label);
if(id) subject = {type: ERDF.RESOURCE, value: ERDF.HASH+id};
// type triples
ERDF._parseTypeTriplesFrom(
subject.type, subject.value,
properties);
// parse all children that are element nodes.
var children = node.childNodes;
if(children) $A(children).each(function(_node) {
if(_node.nodeType == _node.ELEMENT_NODE)
ERDF._parseFromTag(_node, subject, depth+1); });
},
_parseTriplesFrom: function(subjectType, subject, properties,
objectType, object, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( function(schema) {
return false || ERDF.DELIMITERS.find( function(delimiter) {
return property.startsWith(schema.prefix + delimiter);
});
});
if(schema && object) { | });
},
_parseTypeTriplesFrom: function(subjectType, subject, properties, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( function(schema) {
return false || ERDF.DELIMITERS.find( function(delimiter) {
return property.startsWith(ERDF.HYPHEN + schema.prefix + delimiter);
});
});
if(schema && subject) {
property = property.substring(schema.prefix.length+2, property.length);
var triple = ERDF.registerTriple(
(subjectType == ERDF.RESOURCE) ?
new ERDF.Resource(subject) :
new ERDF.Literal(subject),
{prefix: 'rdf', name: 'type'},
new ERDF.Resource(schema.namespace+property));
if(callback) callback(triple);
}
});
},
/**
* Checks for ERDF profile declaration in head of document.
*/
_checkProfile: function() {
// get profiles from head element.
var heads = document.getElementsByTagNameNS(XMLNS.XHTML, 'head');
var profiles = heads[0].getAttribute("profile");
var found = false;
// if erdf profile is contained.
if(profiles && profiles.split(" ").member(XMLNS.ERDF)) {
// pass check.
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Found ERDF profile " + XMLNS.ERDF);
return true;
} else {
// otherwise fail check.
//if(ERDF.log.isFatalEnabled())
// ERDF.log.fatal("No ERDF profile found.");
return false;
}
},
__stripHashes: function(s) {
return (s && (typeof s.substring == 'function') && s.substring(0, 1)=='#') ? s.substring(1, s.length) : s;
},
registerSchema: function(prefix, namespace) {
// TODO check whether already registered, if so, complain.
ERDF.schemas.push({
prefix: prefix,
namespace: namespace
});
//if(ERDF.log.isDebugEnabled())
// ERDF.log.debug("Prefix '"+prefix+"' for '"+namespace+"' registered.");
},
registerTriple: function(subject, predicate, object) {
// if prefix is schema, this is a schema definition.
if(predicate.prefix.toLowerCase() == 'schema')
this.registerSchema(predicate.name, object.value);
var triple = new ERDF.Triple(subject, predicate, object);
ERDF.callback(triple);
//if(ERDF.log.isInfoEnabled())
// ERDF.log.info(triple)
// return the registered triple.
return triple;
},
__enhanceObject: function() {
/* Resource state querying methods */
this.isResource = function() {
return this.type == ERDF.RESOURCE };
this.isLocal = function() {
return this.isResource() && this.value.startsWith('#') };
this.isCurrentDocument = function() {
return this.isResource() && (this.value == '') };
/* Resource getter methods.*/
this.getId = function() {
return this.isLocal() ? ERDF.__stripHashes(this.value) : false; };
/* Liiteral state querying methods */
this.isLiteral = function() {
return this.type == ERDF.LIITERAL };
},
serialize: function(literal) {
if(!literal){
return "";
}else if(literal.constructor == String) {
return literal;
} else if(literal.constructor == Boolean) {
return literal? 'true':'false';
} else {
return literal.toString();
}
}
};
ERDF.Triple = function(subject, predicate, object) {
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.toString = function() {
return "[ERDF.Triple] " +
this.subject.toString() + ' ' +
this.predicate.prefix + ':' + this.predicate.name + ' ' +
this.object.toString();
};
};
ERDF.Resource = function(uri) {
this.type = ERDF.RESOURCE;
this.value = uri;
ERDF.__enhanceObject.apply(this);
this.toString = function() {
return '<' + this.value + '>';
}
};
ERDF.Literal = function(literal) {
this.type = ERDF.LITERAL;
this.value = ERDF.serialize(literal);
ERDF.__enhanceObject.apply(this);
this.toString = function() {
return '"' + this.value + '"';
}
}; |
property = property.substring(
schema.prefix.length+1, property.length);
var triple = ERDF.registerTriple(
new ERDF.Resource(subject),
{prefix: schema.prefix, name: property},
(objectType == ERDF.RESOURCE) ?
new ERDF.Resource(object) :
new ERDF.Literal(object));
if(callback) callback(triple);
}
| conditional_block |
erdfparser.js | /**
* Copyright (c) 2006
*
* Philipp Berger, Martin Czuchra, Gero Decker, Ole Eckermann, Lutz Gericke,
* Alexander Hold, Alexander Koglin, Oliver Kopp, Stefan Krumnow,
* Matthias Kunze, Philipp Maschke, Falko Menge, Christoph Neijenhuis,
* Hagen Overdick, Zhen Peng, Nicolas Peters, Kerstin Pfitzner, Daniel Polak,
* Steffen Ryll, Kai Schlichting, Jan-Felix Schwarz, Daniel Taschik,
* Willi Tscheschner, Björn Wagner, Sven Wagner-Boysen, Matthias Weidlich
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
**/
var ERDF = {
LITERAL: 0x01,
RESOURCE: 0x02,
DELIMITERS: ['.', '-'],
HASH: '#',
HYPHEN: "-",
schemas: [],
callback: undefined,
log: undefined,
init: function(callback) {
// init logging.
//ERDF.log = Log4js.getLogger("oryx");
//ERDF.log.setLevel(Log4js.Level.ALL);
//ERDF.log.addAppender(new ConsoleAppender(ERDF.log, false));
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("ERDF Parser is initialized.");
// register callbacks and default schemas.
ERDF.callback = callback;
ERDF.registerSchema('schema', XMLNS.SCHEMA);
ERDF.registerSchema('rdfs', XMLNS.RDFS);
},
run: function() {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("ERDF Parser is running.");
// do the work.
return ERDF._checkProfile() && ERDF.parse();
},
parse: function() {
//(ERDF.log.isDebugEnabled())
// ERDF.log.debug("Begin parsing document metadata.");
// time measuring
ERDF.__startTime = new Date();
var bodies = document.getElementsByTagNameNS(XMLNS.XHTML, 'body');
var subject = {type: ERDF.RESOURCE, value: ''};
var result = ERDF._parseDocumentMetadata() &&
ERDF._parseFromTag(bodies[0], subject);
// time measuring
ERDF.__stopTime = new Date();
var duration = (ERDF.__stopTime - ERDF.__startTime)/1000.;
//alert('ERDF parsing took ' + duration + ' s.');
return result;
},
_parseDocumentMetadata: function() {
// get links from head element.
var heads = document.getElementsByTagNameNS(XMLNS.XHTML, 'head');
var links = heads[0].getElementsByTagNameNS(XMLNS.XHTML, 'link');
var metas = heads[0].getElementsByTagNameNS(XMLNS.XHTML, 'meta');
// process links first, since they could contain schema definitions.
$A(links).each(function(link) {
var properties = link.getAttribute('rel');
var reversedProperties = link.getAttribute('rev');
var value = link.getAttribute('href');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
properties,
ERDF.RESOURCE, value);
ERDF._parseTriplesFrom(
ERDF.RESOURCE, value,
reversedProperties,
ERDF.RESOURCE, '');
});
// continue with metas.
$A(metas).each(function(meta) {
var property = meta.getAttribute('name'); | var value = meta.getAttribute('content');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
property,
ERDF.LITERAL, value);
});
return true;
},
_parseFromTag: function(node, subject, depth) {
// avoid parsing non-xhtml content.
if(!node || !node.namespaceURI || node.namespaceURI != XMLNS.XHTML) { return; }
// housekeeping.
if(!depth) depth=0;
var id = node.getAttribute('id');
// some logging.
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace(">".times(depth) + " Parsing " + node.nodeName + " ("+node.nodeType+") for data on " +
// ((subject.type == ERDF.RESOURCE) ? ('<' + subject.value + '>') : '') +
// ((subject.type == ERDF.LITERAL) ? '"' + subject.value + '"' : ''));
/* triple finding! */
// in a-tags...
if(node.nodeName.endsWith(':a') || node.nodeName == 'a') {
var properties = node.getAttribute('rel');
var reversedProperties = node.getAttribute('rev');
var value = node.getAttribute('href');
var title = node.getAttribute('title');
var content = node.textContent;
// rel triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.RESOURCE, value,
function(triple) {
var label = title? title : content;
// label triples
ERDF._parseTriplesFrom(
triple.object.type, triple.object.value,
'rdfs.label',
ERDF.LITERAL, label);
});
// rev triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
reversedProperties,
ERDF.RESOURCE, '');
// type triples
ERDF._parseTypeTriplesFrom(
subject.type, subject.value,
properties);
// in img-tags...
} else if(node.nodeName.endsWith(':img') || node.nodeName == 'img') {
var properties = node.getAttribute('class');
var value = node.getAttribute('src');
var alt = node.getAttribute('alt');
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.RESOURCE, value,
function(triple) {
var label = alt;
// label triples
ERDF._parseTriplesFrom(
triple.object.type, triple.object.value,
'rdfs.label',
ERDF.LITERAL, label);
});
}
// in every tag
var properties = node.getAttribute('class');
var title = node.getAttribute('title');
var content = node.textContent;
var label = title ? title : content;
// regular triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.LITERAL, label);
if(id) subject = {type: ERDF.RESOURCE, value: ERDF.HASH+id};
// type triples
ERDF._parseTypeTriplesFrom(
subject.type, subject.value,
properties);
// parse all children that are element nodes.
var children = node.childNodes;
if(children) $A(children).each(function(_node) {
if(_node.nodeType == _node.ELEMENT_NODE)
ERDF._parseFromTag(_node, subject, depth+1); });
},
_parseTriplesFrom: function(subjectType, subject, properties,
objectType, object, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( function(schema) {
return false || ERDF.DELIMITERS.find( function(delimiter) {
return property.startsWith(schema.prefix + delimiter);
});
});
if(schema && object) {
property = property.substring(
schema.prefix.length+1, property.length);
var triple = ERDF.registerTriple(
new ERDF.Resource(subject),
{prefix: schema.prefix, name: property},
(objectType == ERDF.RESOURCE) ?
new ERDF.Resource(object) :
new ERDF.Literal(object));
if(callback) callback(triple);
}
});
},
_parseTypeTriplesFrom: function(subjectType, subject, properties, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( function(schema) {
return false || ERDF.DELIMITERS.find( function(delimiter) {
return property.startsWith(ERDF.HYPHEN + schema.prefix + delimiter);
});
});
if(schema && subject) {
property = property.substring(schema.prefix.length+2, property.length);
var triple = ERDF.registerTriple(
(subjectType == ERDF.RESOURCE) ?
new ERDF.Resource(subject) :
new ERDF.Literal(subject),
{prefix: 'rdf', name: 'type'},
new ERDF.Resource(schema.namespace+property));
if(callback) callback(triple);
}
});
},
/**
* Checks for ERDF profile declaration in head of document.
*/
_checkProfile: function() {
// get profiles from head element.
var heads = document.getElementsByTagNameNS(XMLNS.XHTML, 'head');
var profiles = heads[0].getAttribute("profile");
var found = false;
// if erdf profile is contained.
if(profiles && profiles.split(" ").member(XMLNS.ERDF)) {
// pass check.
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Found ERDF profile " + XMLNS.ERDF);
return true;
} else {
// otherwise fail check.
//if(ERDF.log.isFatalEnabled())
// ERDF.log.fatal("No ERDF profile found.");
return false;
}
},
__stripHashes: function(s) {
return (s && (typeof s.substring == 'function') && s.substring(0, 1)=='#') ? s.substring(1, s.length) : s;
},
registerSchema: function(prefix, namespace) {
// TODO check whether already registered, if so, complain.
ERDF.schemas.push({
prefix: prefix,
namespace: namespace
});
//if(ERDF.log.isDebugEnabled())
// ERDF.log.debug("Prefix '"+prefix+"' for '"+namespace+"' registered.");
},
registerTriple: function(subject, predicate, object) {
// if prefix is schema, this is a schema definition.
if(predicate.prefix.toLowerCase() == 'schema')
this.registerSchema(predicate.name, object.value);
var triple = new ERDF.Triple(subject, predicate, object);
ERDF.callback(triple);
//if(ERDF.log.isInfoEnabled())
// ERDF.log.info(triple)
// return the registered triple.
return triple;
},
__enhanceObject: function() {
/* Resource state querying methods */
this.isResource = function() {
return this.type == ERDF.RESOURCE };
this.isLocal = function() {
return this.isResource() && this.value.startsWith('#') };
this.isCurrentDocument = function() {
return this.isResource() && (this.value == '') };
/* Resource getter methods.*/
this.getId = function() {
return this.isLocal() ? ERDF.__stripHashes(this.value) : false; };
/* Liiteral state querying methods */
this.isLiteral = function() {
return this.type == ERDF.LIITERAL };
},
serialize: function(literal) {
if(!literal){
return "";
}else if(literal.constructor == String) {
return literal;
} else if(literal.constructor == Boolean) {
return literal? 'true':'false';
} else {
return literal.toString();
}
}
};
ERDF.Triple = function(subject, predicate, object) {
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.toString = function() {
return "[ERDF.Triple] " +
this.subject.toString() + ' ' +
this.predicate.prefix + ':' + this.predicate.name + ' ' +
this.object.toString();
};
};
ERDF.Resource = function(uri) {
this.type = ERDF.RESOURCE;
this.value = uri;
ERDF.__enhanceObject.apply(this);
this.toString = function() {
return '<' + this.value + '>';
}
};
ERDF.Literal = function(literal) {
this.type = ERDF.LITERAL;
this.value = ERDF.serialize(literal);
ERDF.__enhanceObject.apply(this);
this.toString = function() {
return '"' + this.value + '"';
}
}; | random_line_split | |
platemanager.py | '''
Created on 05.11.2013
@author: gena
'''
from __future__ import print_function
from PyQt4 import QtCore
from escore.plate import Plate
from escore.approximations import indexByName
class PlateRecord(object):
def | (self, plate, name,path):
self.plate=plate
self.name=name
self.path=path
class PlateManager(QtCore.QObject):
'''
PlateManager holds all plates, and handles related actions,
such as plate open,save,close,select, etc
'''
signalPlateListUpdated=QtCore.pyqtSignal(QtCore.QStringList)
signalCurrentPlateSet=QtCore.pyqtSignal(object)
signalCurrentIndexChanged=QtCore.pyqtSignal(int)
signalApproximationSelected = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(PlateManager, self).__init__(parent)
self.plates=[]
self.currentPlateIndex = -1
self.defaultApproximationIndex=0
def getFileInfo(self,fileName):
fileInfo=QtCore.QFileInfo(fileName)
return fileInfo.baseName(), fileInfo.dir()
def openPlate(self, fileName):
plates = Plate.loadFromFile(fileName)
for number,plate in enumerate(plates):
plate.setParent(self)
if plate.approximation is None:
print("set default approximation for plate",self.defaultApproximationIndex)
plate.setApproximation(self.defaultApproximationIndex)
name,path = self.getFileInfo(fileName)
if len(plates)>1:
name+='_'+str(number+1)
plateRecord=PlateRecord(plate,name,path)
self.plates.append(plateRecord)
plate.signalApplyReference.connect(self.applyReference)
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
self.setCurrentPlate(0)
def setApproximation(self, index):
if self.defaultApproximationIndex==index:
return
self.defaultApproximationIndex=index
if self.currentPlateIndex >= 0 :
self.plates[self.currentPlateIndex].plate.setApproximation(index)
self.signalApproximationSelected.emit(index)
def openPlates(self, fileNameList):
for fileName in fileNameList :
self.openPlate(fileName)
def savePlateAs(self,fileName):
if self.currentPlateIndex < 0 :
return
plateRecord=self.plates[self.currentPlateIndex]
plateRecord.plate.saveToFile(fileName)
plateRecord.name,plateRecord.path = self.getFileInfo(fileName)
self.signalPlateListUpdated.emit(self.names())
def savePlateWithDefaultName(self, index):
plateRecord=self.plates[index]
fileInfo=QtCore.QFileInfo(plateRecord.path,plateRecord.name+'.csv')
plateRecord.plate.saveToFile(fileInfo.filePath())
def savePlate(self):
if self.currentPlateIndex < 0 :
return
self.savePlateWithDefaultName(self.currentPlateIndex)
def saveAllPlates(self):
for index in range(len(self.plates)):
self.savePlateWithDefaultName(index)
def removePlate(self):
if self.currentPlateIndex < 0 :
return
self.signalCurrentPlateSet.emit(None)
self.plates[self.currentPlateIndex].plate.signalApplyReference.disconnect()
del self.plates[self.currentPlateIndex]
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
self.setCurrentPlate(0)
def isDirty(self):
return self.plates[self.currentPlateIndex].plate.dirty
def isEmpty(self):
return self.plates == []
def names(self):
return QtCore.QStringList([QtCore.QString(record.name) for record in self.plates])
def setCurrentPlate(self, index):
if self.currentPlateIndex == index :
return
self.currentPlateIndex = index
if index >= 0:
plate = self.plates[index].plate
appindex= indexByName(plate.approximation.name)
self.defaultApproximationIndex = appindex
self.signalApproximationSelected.emit(appindex)
else :
plate = None
self.signalCurrentIndexChanged.emit(self.currentPlateIndex)
self.signalCurrentPlateSet.emit(plate)
def applyReference(self, reference):
print('Applying reference to all plates')
sender = self.sender()
for plateRecord in self.plates:
plate = plateRecord.plate
if not plate is sender:
plate.setReference(reference)
| __init__ | identifier_name |
platemanager.py | '''
Created on 05.11.2013
@author: gena
'''
from __future__ import print_function
from PyQt4 import QtCore
from escore.plate import Plate
from escore.approximations import indexByName
class PlateRecord(object):
def __init__(self, plate, name,path):
self.plate=plate
self.name=name
self.path=path
class PlateManager(QtCore.QObject):
'''
PlateManager holds all plates, and handles related actions,
such as plate open,save,close,select, etc
'''
signalPlateListUpdated=QtCore.pyqtSignal(QtCore.QStringList)
signalCurrentPlateSet=QtCore.pyqtSignal(object)
signalCurrentIndexChanged=QtCore.pyqtSignal(int)
signalApproximationSelected = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(PlateManager, self).__init__(parent)
self.plates=[]
self.currentPlateIndex = -1
self.defaultApproximationIndex=0
def getFileInfo(self,fileName):
fileInfo=QtCore.QFileInfo(fileName)
return fileInfo.baseName(), fileInfo.dir()
def openPlate(self, fileName):
plates = Plate.loadFromFile(fileName)
for number,plate in enumerate(plates):
plate.setParent(self)
if plate.approximation is None:
print("set default approximation for plate",self.defaultApproximationIndex)
plate.setApproximation(self.defaultApproximationIndex)
name,path = self.getFileInfo(fileName)
if len(plates)>1:
name+='_'+str(number+1)
plateRecord=PlateRecord(plate,name,path)
self.plates.append(plateRecord)
plate.signalApplyReference.connect(self.applyReference)
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
self.setCurrentPlate(0)
def setApproximation(self, index):
if self.defaultApproximationIndex==index:
return
self.defaultApproximationIndex=index
if self.currentPlateIndex >= 0 :
self.plates[self.currentPlateIndex].plate.setApproximation(index)
self.signalApproximationSelected.emit(index)
def openPlates(self, fileNameList):
for fileName in fileNameList :
self.openPlate(fileName)
def savePlateAs(self,fileName):
if self.currentPlateIndex < 0 :
return
plateRecord=self.plates[self.currentPlateIndex]
plateRecord.plate.saveToFile(fileName)
plateRecord.name,plateRecord.path = self.getFileInfo(fileName)
self.signalPlateListUpdated.emit(self.names())
def savePlateWithDefaultName(self, index):
plateRecord=self.plates[index]
fileInfo=QtCore.QFileInfo(plateRecord.path,plateRecord.name+'.csv')
plateRecord.plate.saveToFile(fileInfo.filePath())
def savePlate(self):
if self.currentPlateIndex < 0 :
return
self.savePlateWithDefaultName(self.currentPlateIndex)
def saveAllPlates(self):
for index in range(len(self.plates)):
self.savePlateWithDefaultName(index)
def removePlate(self):
|
def isDirty(self):
return self.plates[self.currentPlateIndex].plate.dirty
def isEmpty(self):
return self.plates == []
def names(self):
return QtCore.QStringList([QtCore.QString(record.name) for record in self.plates])
def setCurrentPlate(self, index):
if self.currentPlateIndex == index :
return
self.currentPlateIndex = index
if index >= 0:
plate = self.plates[index].plate
appindex= indexByName(plate.approximation.name)
self.defaultApproximationIndex = appindex
self.signalApproximationSelected.emit(appindex)
else :
plate = None
self.signalCurrentIndexChanged.emit(self.currentPlateIndex)
self.signalCurrentPlateSet.emit(plate)
def applyReference(self, reference):
print('Applying reference to all plates')
sender = self.sender()
for plateRecord in self.plates:
plate = plateRecord.plate
if not plate is sender:
plate.setReference(reference)
| if self.currentPlateIndex < 0 :
return
self.signalCurrentPlateSet.emit(None)
self.plates[self.currentPlateIndex].plate.signalApplyReference.disconnect()
del self.plates[self.currentPlateIndex]
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
self.setCurrentPlate(0) | identifier_body |
platemanager.py | '''
Created on 05.11.2013
@author: gena
'''
from __future__ import print_function
from PyQt4 import QtCore
from escore.plate import Plate
from escore.approximations import indexByName
class PlateRecord(object):
def __init__(self, plate, name,path):
self.plate=plate
self.name=name
self.path=path
class PlateManager(QtCore.QObject):
'''
PlateManager holds all plates, and handles related actions, | such as plate open,save,close,select, etc
'''
signalPlateListUpdated=QtCore.pyqtSignal(QtCore.QStringList)
signalCurrentPlateSet=QtCore.pyqtSignal(object)
signalCurrentIndexChanged=QtCore.pyqtSignal(int)
signalApproximationSelected = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(PlateManager, self).__init__(parent)
self.plates=[]
self.currentPlateIndex = -1
self.defaultApproximationIndex=0
def getFileInfo(self,fileName):
fileInfo=QtCore.QFileInfo(fileName)
return fileInfo.baseName(), fileInfo.dir()
def openPlate(self, fileName):
plates = Plate.loadFromFile(fileName)
for number,plate in enumerate(plates):
plate.setParent(self)
if plate.approximation is None:
print("set default approximation for plate",self.defaultApproximationIndex)
plate.setApproximation(self.defaultApproximationIndex)
name,path = self.getFileInfo(fileName)
if len(plates)>1:
name+='_'+str(number+1)
plateRecord=PlateRecord(plate,name,path)
self.plates.append(plateRecord)
plate.signalApplyReference.connect(self.applyReference)
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
self.setCurrentPlate(0)
def setApproximation(self, index):
if self.defaultApproximationIndex==index:
return
self.defaultApproximationIndex=index
if self.currentPlateIndex >= 0 :
self.plates[self.currentPlateIndex].plate.setApproximation(index)
self.signalApproximationSelected.emit(index)
def openPlates(self, fileNameList):
for fileName in fileNameList :
self.openPlate(fileName)
def savePlateAs(self,fileName):
if self.currentPlateIndex < 0 :
return
plateRecord=self.plates[self.currentPlateIndex]
plateRecord.plate.saveToFile(fileName)
plateRecord.name,plateRecord.path = self.getFileInfo(fileName)
self.signalPlateListUpdated.emit(self.names())
def savePlateWithDefaultName(self, index):
plateRecord=self.plates[index]
fileInfo=QtCore.QFileInfo(plateRecord.path,plateRecord.name+'.csv')
plateRecord.plate.saveToFile(fileInfo.filePath())
def savePlate(self):
if self.currentPlateIndex < 0 :
return
self.savePlateWithDefaultName(self.currentPlateIndex)
def saveAllPlates(self):
for index in range(len(self.plates)):
self.savePlateWithDefaultName(index)
def removePlate(self):
if self.currentPlateIndex < 0 :
return
self.signalCurrentPlateSet.emit(None)
self.plates[self.currentPlateIndex].plate.signalApplyReference.disconnect()
del self.plates[self.currentPlateIndex]
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
self.setCurrentPlate(0)
def isDirty(self):
return self.plates[self.currentPlateIndex].plate.dirty
def isEmpty(self):
return self.plates == []
def names(self):
return QtCore.QStringList([QtCore.QString(record.name) for record in self.plates])
def setCurrentPlate(self, index):
if self.currentPlateIndex == index :
return
self.currentPlateIndex = index
if index >= 0:
plate = self.plates[index].plate
appindex= indexByName(plate.approximation.name)
self.defaultApproximationIndex = appindex
self.signalApproximationSelected.emit(appindex)
else :
plate = None
self.signalCurrentIndexChanged.emit(self.currentPlateIndex)
self.signalCurrentPlateSet.emit(plate)
def applyReference(self, reference):
print('Applying reference to all plates')
sender = self.sender()
for plateRecord in self.plates:
plate = plateRecord.plate
if not plate is sender:
plate.setReference(reference) | random_line_split | |
platemanager.py | '''
Created on 05.11.2013
@author: gena
'''
from __future__ import print_function
from PyQt4 import QtCore
from escore.plate import Plate
from escore.approximations import indexByName
class PlateRecord(object):
def __init__(self, plate, name,path):
self.plate=plate
self.name=name
self.path=path
class PlateManager(QtCore.QObject):
'''
PlateManager holds all plates, and handles related actions,
such as plate open,save,close,select, etc
'''
signalPlateListUpdated=QtCore.pyqtSignal(QtCore.QStringList)
signalCurrentPlateSet=QtCore.pyqtSignal(object)
signalCurrentIndexChanged=QtCore.pyqtSignal(int)
signalApproximationSelected = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(PlateManager, self).__init__(parent)
self.plates=[]
self.currentPlateIndex = -1
self.defaultApproximationIndex=0
def getFileInfo(self,fileName):
fileInfo=QtCore.QFileInfo(fileName)
return fileInfo.baseName(), fileInfo.dir()
def openPlate(self, fileName):
plates = Plate.loadFromFile(fileName)
for number,plate in enumerate(plates):
plate.setParent(self)
if plate.approximation is None:
print("set default approximation for plate",self.defaultApproximationIndex)
plate.setApproximation(self.defaultApproximationIndex)
name,path = self.getFileInfo(fileName)
if len(plates)>1:
name+='_'+str(number+1)
plateRecord=PlateRecord(plate,name,path)
self.plates.append(plateRecord)
plate.signalApplyReference.connect(self.applyReference)
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
self.setCurrentPlate(0)
def setApproximation(self, index):
if self.defaultApproximationIndex==index:
return
self.defaultApproximationIndex=index
if self.currentPlateIndex >= 0 :
self.plates[self.currentPlateIndex].plate.setApproximation(index)
self.signalApproximationSelected.emit(index)
def openPlates(self, fileNameList):
for fileName in fileNameList :
self.openPlate(fileName)
def savePlateAs(self,fileName):
if self.currentPlateIndex < 0 :
return
plateRecord=self.plates[self.currentPlateIndex]
plateRecord.plate.saveToFile(fileName)
plateRecord.name,plateRecord.path = self.getFileInfo(fileName)
self.signalPlateListUpdated.emit(self.names())
def savePlateWithDefaultName(self, index):
plateRecord=self.plates[index]
fileInfo=QtCore.QFileInfo(plateRecord.path,plateRecord.name+'.csv')
plateRecord.plate.saveToFile(fileInfo.filePath())
def savePlate(self):
if self.currentPlateIndex < 0 :
return
self.savePlateWithDefaultName(self.currentPlateIndex)
def saveAllPlates(self):
for index in range(len(self.plates)):
self.savePlateWithDefaultName(index)
def removePlate(self):
if self.currentPlateIndex < 0 :
return
self.signalCurrentPlateSet.emit(None)
self.plates[self.currentPlateIndex].plate.signalApplyReference.disconnect()
del self.plates[self.currentPlateIndex]
self.signalPlateListUpdated.emit(self.names())
if not self.isEmpty():
self.setCurrentPlate(0)
def isDirty(self):
return self.plates[self.currentPlateIndex].plate.dirty
def isEmpty(self):
return self.plates == []
def names(self):
return QtCore.QStringList([QtCore.QString(record.name) for record in self.plates])
def setCurrentPlate(self, index):
if self.currentPlateIndex == index :
return
self.currentPlateIndex = index
if index >= 0:
plate = self.plates[index].plate
appindex= indexByName(plate.approximation.name)
self.defaultApproximationIndex = appindex
self.signalApproximationSelected.emit(appindex)
else :
plate = None
self.signalCurrentIndexChanged.emit(self.currentPlateIndex)
self.signalCurrentPlateSet.emit(plate)
def applyReference(self, reference):
print('Applying reference to all plates')
sender = self.sender()
for plateRecord in self.plates:
| plate = plateRecord.plate
if not plate is sender:
plate.setReference(reference) | conditional_block | |
classStateFixtureReselectMocked.tsx | import { StateMock } from '@react-mock/state';
import React from 'react';
import { createValues } from '../../fixtureState';
import { uuid } from '../../util';
import { testFixtureLoader } from '../testHelpers';
import { Counter } from '../testHelpers/components';
import { anyClassState, anyProps } from '../testHelpers/fixtureState';
import { wrapFixtures } from '../testHelpers/wrapFixture';
const rendererId = uuid();
const fixtures = wrapFixtures({
first: (
<StateMock state={{ count: 5 }}>
<Counter /> | </StateMock>
),
});
const fixtureId = { path: 'first' };
// NOTE: This is a regression test that was created for a bug that initally
// slipped unnoticed in https://github.com/react-cosmos/react-cosmos/pull/893.
// Because element refs from unmounted FixtureCapture instances were
// incorrectly reused, component state was no longer picked up after
// FixtureCapture remounted. This was related to the refactor of
// FixtureCapture/attachChildRefs in
// https://github.com/react-cosmos/react-cosmos/commit/56494b6ea10785cc3db8dda7a7fbcad62c8e1c12
testFixtureLoader(
'captures initial state after re-selecting fixture',
{ rendererId, fixtures },
async ({ selectFixture, fixtureStateChange }) => {
await selectFixture({ rendererId, fixtureId, fixtureState: {} });
await selectFixture({ rendererId, fixtureId, fixtureState: {} });
await fixtureStateChange({
rendererId,
fixtureId,
fixtureState: {
props: [anyProps()],
classState: [
anyClassState({
values: createValues({ count: 5 }),
}),
],
},
});
}
); | random_line_split | |
gradient_boosting_regression_example.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Gradient Boosted Trees Regression Example.
"""
from __future__ import print_function
import sys
from pyspark import SparkContext
# $example on$
from pyspark.mllib.tree import GradientBoostedTrees, GradientBoostedTreesModel
from pyspark.mllib.util import MLUtils | # $example on$
# Load and parse the data file.
data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.randomSplit([0.7, 0.3])
# Train a GradientBoostedTrees model.
# Notes: (a) Empty categoricalFeaturesInfo indicates all features are continuous.
# (b) Use more iterations in practice.
model = GradientBoostedTrees.trainRegressor(trainingData,
categoricalFeaturesInfo={}, numIterations=3)
# Evaluate model on test instances and compute test error
predictions = model.predict(testData.map(lambda x: x.features))
labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)
testMSE = labelsAndPredictions.map(lambda (v, p): (v - p) * (v - p)).sum() /\
float(testData.count())
print('Test Mean Squared Error = ' + str(testMSE))
print('Learned regression GBT model:')
print(model.toDebugString())
# Save and load model
model.save(sc, "target/tmp/myGradientBoostingRegressionModel")
sameModel = GradientBoostedTreesModel.load(sc, "target/tmp/myGradientBoostingRegressionModel")
# $example off$ | # $example off$
if __name__ == "__main__":
sc = SparkContext(appName="PythonGradientBoostedTreesRegressionExample") | random_line_split |
gradient_boosting_regression_example.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Gradient Boosted Trees Regression Example.
"""
from __future__ import print_function
import sys
from pyspark import SparkContext
# $example on$
from pyspark.mllib.tree import GradientBoostedTrees, GradientBoostedTreesModel
from pyspark.mllib.util import MLUtils
# $example off$
if __name__ == "__main__":
| sc = SparkContext(appName="PythonGradientBoostedTreesRegressionExample")
# $example on$
# Load and parse the data file.
data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
# Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.randomSplit([0.7, 0.3])
# Train a GradientBoostedTrees model.
# Notes: (a) Empty categoricalFeaturesInfo indicates all features are continuous.
# (b) Use more iterations in practice.
model = GradientBoostedTrees.trainRegressor(trainingData,
categoricalFeaturesInfo={}, numIterations=3)
# Evaluate model on test instances and compute test error
predictions = model.predict(testData.map(lambda x: x.features))
labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)
testMSE = labelsAndPredictions.map(lambda (v, p): (v - p) * (v - p)).sum() /\
float(testData.count())
print('Test Mean Squared Error = ' + str(testMSE))
print('Learned regression GBT model:')
print(model.toDebugString())
# Save and load model
model.save(sc, "target/tmp/myGradientBoostingRegressionModel")
sameModel = GradientBoostedTreesModel.load(sc, "target/tmp/myGradientBoostingRegressionModel")
# $example off$ | conditional_block | |
associated-types-eq-3.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.
// Test equality constraints on associated types. Check we get type errors
// where we should.
pub trait Foo {
type A;
fn boo(&self) -> <Self as Foo>::A;
}
struct Bar;
impl Foo for isize {
type A = usize;
fn boo(&self) -> usize {
42
}
}
fn foo1<I: Foo<A=Bar>>(x: I) {
let _: Bar = x.boo();
}
fn foo2<I: Foo>(x: I) {
let _: Bar = x.boo();
//~^ ERROR mismatched types
//~| expected `Bar`
//~| found `<I as Foo>::A`
//~| expected struct `Bar`
//~| found associated type
}
pub fn baz(x: &Foo<A=Bar>) {
let _: Bar = x.boo();
}
pub fn main() {
let a = 42;
foo1(a);
//~^ ERROR type mismatch resolving
//~| expected usize
//~| found struct `Bar` | baz(&a);
//~^ ERROR type mismatch resolving
//~| expected usize
//~| found struct `Bar`
} | random_line_split | |
associated-types-eq-3.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.
// Test equality constraints on associated types. Check we get type errors
// where we should.
pub trait Foo {
type A;
fn boo(&self) -> <Self as Foo>::A;
}
struct Bar;
impl Foo for isize {
type A = usize;
fn boo(&self) -> usize {
42
}
}
fn foo1<I: Foo<A=Bar>>(x: I) {
let _: Bar = x.boo();
}
fn foo2<I: Foo>(x: I) {
let _: Bar = x.boo();
//~^ ERROR mismatched types
//~| expected `Bar`
//~| found `<I as Foo>::A`
//~| expected struct `Bar`
//~| found associated type
}
pub fn baz(x: &Foo<A=Bar>) {
let _: Bar = x.boo();
}
pub fn | () {
let a = 42;
foo1(a);
//~^ ERROR type mismatch resolving
//~| expected usize
//~| found struct `Bar`
baz(&a);
//~^ ERROR type mismatch resolving
//~| expected usize
//~| found struct `Bar`
}
| main | identifier_name |
util.py | # Copyright 2013-2021 Aerospike, 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.
import json
import re
from lib.utils import util
def parse_record(parent_field, record):
field_names = []
field_values = []
for name in record:
if isinstance(record[name], dict):
new_parent_field = parent_field.copy()
new_parent_field.append(name)
names = " ".join(new_parent_field)
if "converted" in record[name]:
field_names.append(names)
field_values.append(record[name]["converted"])
elif "raw" in record[name]:
field_names.append(names)
field_values.append(record[name]["raw"])
else:
# Must have subgroups:
sub_names, sub_values = parse_record(new_parent_field, record[name])
field_names.extend(sub_names)
field_values.extend(sub_values)
else:
raise Exception("Unhandled parsing")
return field_names, field_values
def parse_output(actual_out={}, horizontal=False, header_len=2, merge_header=True):
"""
commmon parser for all show commands will return tuple of following
@param heading : first line of output
@param header: Second line of output
@param params: list of parameters
"""
title = actual_out["title"]
description = actual_out.get("description", "")
data_names = {}
data_values = []
num_records = 0
for group in actual_out["groups"]:
for record in group["records"]:
temp_names, temp_values = parse_record([], record)
# We assume every record has the same set of names
if len(data_names) == 0:
data_names = temp_names
data_values.append(temp_values)
num_records += 1
return title, description, data_names, data_values, num_records
def get_separate_output(in_str=""):
_regex = re.compile(r"((?<=^{).*?(?=^}))", re.MULTILINE | re.DOTALL)
out = re.findall(_regex, in_str)
ls = []
for item in out:
item = remove_escape_sequence(item)
item = "{" + item + "}"
ls.append(json.loads(item))
return ls
def capture_separate_and_parse_output(rc, commands):
actual_stdout = util.capture_stdout(rc.execute, commands)
separated_stdout = get_separate_output(actual_stdout)
result = parse_output(separated_stdout[0])
return result
def get_merged_header(*lines):
h = [[_f for _f in _h.split(" ") if _f] for _h in lines]
header = []
if len(h) == 0 or any(len(h[i]) != len(h[i + 1]) for i in range(len(h) - 1)):
return header
for idx in range(len(h[0])):
header_i = h[0][idx]
for jdx in range(len(h) - 1):
if h[jdx + 1][idx] == ".":
break
header_i += " " + h[jdx + 1][idx]
header.append(header_i)
return header
def check_for_subset(actual_list, expected_sub_list):
if not expected_sub_list:
return True
if not actual_list:
return False
for i in expected_sub_list:
if isinstance(i, tuple):
found = False
for s_i in i:
if s_i is None:
found = True
break
if s_i in actual_list:
found = True
break
if not found:
print(i, actual_list)
return False
else:
if i not in actual_list:
print(i)
return False
return True
# Checks that a single expected list has a subset equal to actual_list.
def check_for_subset_in_list_of_lists(actual_list, list_of_expected_sub_lists):
for expected_list in list_of_expected_sub_lists:
if check_for_subset(actual_list, expected_list):
return True
return False
def remove_escape_sequence(line):
ansi_escape = re.compile(r"(\x9b|\x1b\[)[0-?]*[ -\/]*[@-~]")
return ansi_escape.sub("", line)
def check_for_types(actual_lists, expected_types):
def is_float(x):
try:
float(x)
if "." in x:
return True
return False
except ValueError:
return False
def is_int(x):
|
def is_bool(x):
if x in ("True", "true", "False", "false"):
return True
return False
def check_list_against_types(a_list):
if a_list is None or expected_types is None:
return False
if len(a_list) == len(expected_types):
for idx in range(len(a_list)):
typ = expected_types[idx]
val = a_list[idx]
if typ == int:
if not is_int(val):
return False
elif typ == float:
if not is_float(val):
return False
elif typ == bool:
if not is_bool(val):
return False
elif typ == str:
if any([is_bool(val), is_int(val), is_float(val)]):
return False
else:
raise Exception("Type is not yet handles in test_util.py", typ)
return True
return False
for actual_list in actual_lists:
if not check_list_against_types(actual_list):
return False
return True
| try:
int(x)
if "." in x:
return False
return True
except ValueError:
return False | identifier_body |
util.py | # Copyright 2013-2021 Aerospike, 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.
import json
import re
from lib.utils import util
def parse_record(parent_field, record):
field_names = []
field_values = []
for name in record:
if isinstance(record[name], dict):
new_parent_field = parent_field.copy()
new_parent_field.append(name)
names = " ".join(new_parent_field)
if "converted" in record[name]:
field_names.append(names)
field_values.append(record[name]["converted"])
elif "raw" in record[name]:
field_names.append(names)
field_values.append(record[name]["raw"])
else:
# Must have subgroups:
sub_names, sub_values = parse_record(new_parent_field, record[name])
field_names.extend(sub_names)
field_values.extend(sub_values)
else:
raise Exception("Unhandled parsing")
return field_names, field_values
def parse_output(actual_out={}, horizontal=False, header_len=2, merge_header=True):
"""
commmon parser for all show commands will return tuple of following
@param heading : first line of output
@param header: Second line of output
@param params: list of parameters
"""
title = actual_out["title"]
description = actual_out.get("description", "")
data_names = {}
data_values = []
num_records = 0
for group in actual_out["groups"]:
for record in group["records"]:
temp_names, temp_values = parse_record([], record)
# We assume every record has the same set of names
if len(data_names) == 0:
data_names = temp_names
data_values.append(temp_values)
num_records += 1
return title, description, data_names, data_values, num_records
def get_separate_output(in_str=""):
_regex = re.compile(r"((?<=^{).*?(?=^}))", re.MULTILINE | re.DOTALL)
out = re.findall(_regex, in_str)
ls = []
for item in out:
item = remove_escape_sequence(item)
item = "{" + item + "}"
ls.append(json.loads(item))
return ls
def capture_separate_and_parse_output(rc, commands):
actual_stdout = util.capture_stdout(rc.execute, commands)
separated_stdout = get_separate_output(actual_stdout)
result = parse_output(separated_stdout[0])
return result
def get_merged_header(*lines):
h = [[_f for _f in _h.split(" ") if _f] for _h in lines]
header = []
if len(h) == 0 or any(len(h[i]) != len(h[i + 1]) for i in range(len(h) - 1)):
return header
for idx in range(len(h[0])):
header_i = h[0][idx]
for jdx in range(len(h) - 1):
if h[jdx + 1][idx] == ".":
break
header_i += " " + h[jdx + 1][idx]
header.append(header_i)
return header
def check_for_subset(actual_list, expected_sub_list):
if not expected_sub_list:
return True
if not actual_list:
return False
for i in expected_sub_list:
if isinstance(i, tuple):
found = False
for s_i in i:
if s_i is None:
found = True
break
if s_i in actual_list:
found = True
break
if not found:
print(i, actual_list)
return False
else:
if i not in actual_list:
print(i)
return False
return True
# Checks that a single expected list has a subset equal to actual_list.
def check_for_subset_in_list_of_lists(actual_list, list_of_expected_sub_lists):
for expected_list in list_of_expected_sub_lists:
if check_for_subset(actual_list, expected_list):
return True
return False
def remove_escape_sequence(line):
ansi_escape = re.compile(r"(\x9b|\x1b\[)[0-?]*[ -\/]*[@-~]")
return ansi_escape.sub("", line)
def check_for_types(actual_lists, expected_types):
def is_float(x):
try:
float(x)
if "." in x:
return True
return False
except ValueError:
return False
def | (x):
try:
int(x)
if "." in x:
return False
return True
except ValueError:
return False
def is_bool(x):
if x in ("True", "true", "False", "false"):
return True
return False
def check_list_against_types(a_list):
if a_list is None or expected_types is None:
return False
if len(a_list) == len(expected_types):
for idx in range(len(a_list)):
typ = expected_types[idx]
val = a_list[idx]
if typ == int:
if not is_int(val):
return False
elif typ == float:
if not is_float(val):
return False
elif typ == bool:
if not is_bool(val):
return False
elif typ == str:
if any([is_bool(val), is_int(val), is_float(val)]):
return False
else:
raise Exception("Type is not yet handles in test_util.py", typ)
return True
return False
for actual_list in actual_lists:
if not check_list_against_types(actual_list):
return False
return True
| is_int | identifier_name |
util.py | # Copyright 2013-2021 Aerospike, 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.
import json
import re
from lib.utils import util
def parse_record(parent_field, record): | field_values = []
for name in record:
if isinstance(record[name], dict):
new_parent_field = parent_field.copy()
new_parent_field.append(name)
names = " ".join(new_parent_field)
if "converted" in record[name]:
field_names.append(names)
field_values.append(record[name]["converted"])
elif "raw" in record[name]:
field_names.append(names)
field_values.append(record[name]["raw"])
else:
# Must have subgroups:
sub_names, sub_values = parse_record(new_parent_field, record[name])
field_names.extend(sub_names)
field_values.extend(sub_values)
else:
raise Exception("Unhandled parsing")
return field_names, field_values
def parse_output(actual_out={}, horizontal=False, header_len=2, merge_header=True):
"""
commmon parser for all show commands will return tuple of following
@param heading : first line of output
@param header: Second line of output
@param params: list of parameters
"""
title = actual_out["title"]
description = actual_out.get("description", "")
data_names = {}
data_values = []
num_records = 0
for group in actual_out["groups"]:
for record in group["records"]:
temp_names, temp_values = parse_record([], record)
# We assume every record has the same set of names
if len(data_names) == 0:
data_names = temp_names
data_values.append(temp_values)
num_records += 1
return title, description, data_names, data_values, num_records
def get_separate_output(in_str=""):
_regex = re.compile(r"((?<=^{).*?(?=^}))", re.MULTILINE | re.DOTALL)
out = re.findall(_regex, in_str)
ls = []
for item in out:
item = remove_escape_sequence(item)
item = "{" + item + "}"
ls.append(json.loads(item))
return ls
def capture_separate_and_parse_output(rc, commands):
actual_stdout = util.capture_stdout(rc.execute, commands)
separated_stdout = get_separate_output(actual_stdout)
result = parse_output(separated_stdout[0])
return result
def get_merged_header(*lines):
h = [[_f for _f in _h.split(" ") if _f] for _h in lines]
header = []
if len(h) == 0 or any(len(h[i]) != len(h[i + 1]) for i in range(len(h) - 1)):
return header
for idx in range(len(h[0])):
header_i = h[0][idx]
for jdx in range(len(h) - 1):
if h[jdx + 1][idx] == ".":
break
header_i += " " + h[jdx + 1][idx]
header.append(header_i)
return header
def check_for_subset(actual_list, expected_sub_list):
if not expected_sub_list:
return True
if not actual_list:
return False
for i in expected_sub_list:
if isinstance(i, tuple):
found = False
for s_i in i:
if s_i is None:
found = True
break
if s_i in actual_list:
found = True
break
if not found:
print(i, actual_list)
return False
else:
if i not in actual_list:
print(i)
return False
return True
# Checks that a single expected list has a subset equal to actual_list.
def check_for_subset_in_list_of_lists(actual_list, list_of_expected_sub_lists):
for expected_list in list_of_expected_sub_lists:
if check_for_subset(actual_list, expected_list):
return True
return False
def remove_escape_sequence(line):
ansi_escape = re.compile(r"(\x9b|\x1b\[)[0-?]*[ -\/]*[@-~]")
return ansi_escape.sub("", line)
def check_for_types(actual_lists, expected_types):
def is_float(x):
try:
float(x)
if "." in x:
return True
return False
except ValueError:
return False
def is_int(x):
try:
int(x)
if "." in x:
return False
return True
except ValueError:
return False
def is_bool(x):
if x in ("True", "true", "False", "false"):
return True
return False
def check_list_against_types(a_list):
if a_list is None or expected_types is None:
return False
if len(a_list) == len(expected_types):
for idx in range(len(a_list)):
typ = expected_types[idx]
val = a_list[idx]
if typ == int:
if not is_int(val):
return False
elif typ == float:
if not is_float(val):
return False
elif typ == bool:
if not is_bool(val):
return False
elif typ == str:
if any([is_bool(val), is_int(val), is_float(val)]):
return False
else:
raise Exception("Type is not yet handles in test_util.py", typ)
return True
return False
for actual_list in actual_lists:
if not check_list_against_types(actual_list):
return False
return True | field_names = [] | random_line_split |
util.py | # Copyright 2013-2021 Aerospike, 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.
import json
import re
from lib.utils import util
def parse_record(parent_field, record):
field_names = []
field_values = []
for name in record:
if isinstance(record[name], dict):
new_parent_field = parent_field.copy()
new_parent_field.append(name)
names = " ".join(new_parent_field)
if "converted" in record[name]:
field_names.append(names)
field_values.append(record[name]["converted"])
elif "raw" in record[name]:
field_names.append(names)
field_values.append(record[name]["raw"])
else:
# Must have subgroups:
sub_names, sub_values = parse_record(new_parent_field, record[name])
field_names.extend(sub_names)
field_values.extend(sub_values)
else:
raise Exception("Unhandled parsing")
return field_names, field_values
def parse_output(actual_out={}, horizontal=False, header_len=2, merge_header=True):
"""
commmon parser for all show commands will return tuple of following
@param heading : first line of output
@param header: Second line of output
@param params: list of parameters
"""
title = actual_out["title"]
description = actual_out.get("description", "")
data_names = {}
data_values = []
num_records = 0
for group in actual_out["groups"]:
for record in group["records"]:
|
return title, description, data_names, data_values, num_records
def get_separate_output(in_str=""):
_regex = re.compile(r"((?<=^{).*?(?=^}))", re.MULTILINE | re.DOTALL)
out = re.findall(_regex, in_str)
ls = []
for item in out:
item = remove_escape_sequence(item)
item = "{" + item + "}"
ls.append(json.loads(item))
return ls
def capture_separate_and_parse_output(rc, commands):
actual_stdout = util.capture_stdout(rc.execute, commands)
separated_stdout = get_separate_output(actual_stdout)
result = parse_output(separated_stdout[0])
return result
def get_merged_header(*lines):
h = [[_f for _f in _h.split(" ") if _f] for _h in lines]
header = []
if len(h) == 0 or any(len(h[i]) != len(h[i + 1]) for i in range(len(h) - 1)):
return header
for idx in range(len(h[0])):
header_i = h[0][idx]
for jdx in range(len(h) - 1):
if h[jdx + 1][idx] == ".":
break
header_i += " " + h[jdx + 1][idx]
header.append(header_i)
return header
def check_for_subset(actual_list, expected_sub_list):
if not expected_sub_list:
return True
if not actual_list:
return False
for i in expected_sub_list:
if isinstance(i, tuple):
found = False
for s_i in i:
if s_i is None:
found = True
break
if s_i in actual_list:
found = True
break
if not found:
print(i, actual_list)
return False
else:
if i not in actual_list:
print(i)
return False
return True
# Checks that a single expected list has a subset equal to actual_list.
def check_for_subset_in_list_of_lists(actual_list, list_of_expected_sub_lists):
for expected_list in list_of_expected_sub_lists:
if check_for_subset(actual_list, expected_list):
return True
return False
def remove_escape_sequence(line):
ansi_escape = re.compile(r"(\x9b|\x1b\[)[0-?]*[ -\/]*[@-~]")
return ansi_escape.sub("", line)
def check_for_types(actual_lists, expected_types):
def is_float(x):
try:
float(x)
if "." in x:
return True
return False
except ValueError:
return False
def is_int(x):
try:
int(x)
if "." in x:
return False
return True
except ValueError:
return False
def is_bool(x):
if x in ("True", "true", "False", "false"):
return True
return False
def check_list_against_types(a_list):
if a_list is None or expected_types is None:
return False
if len(a_list) == len(expected_types):
for idx in range(len(a_list)):
typ = expected_types[idx]
val = a_list[idx]
if typ == int:
if not is_int(val):
return False
elif typ == float:
if not is_float(val):
return False
elif typ == bool:
if not is_bool(val):
return False
elif typ == str:
if any([is_bool(val), is_int(val), is_float(val)]):
return False
else:
raise Exception("Type is not yet handles in test_util.py", typ)
return True
return False
for actual_list in actual_lists:
if not check_list_against_types(actual_list):
return False
return True
| temp_names, temp_values = parse_record([], record)
# We assume every record has the same set of names
if len(data_names) == 0:
data_names = temp_names
data_values.append(temp_values)
num_records += 1 | conditional_block |
test_large_ops.py | # Copyright 2013 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from tempest_lib import exceptions as lib_exc
from tempest.common import fixed_network
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempest import config
from tempest.scenario import manager
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class TestLargeOpsScenario(manager.ScenarioTest):
"""
Test large operations.
This test below:
* Spin up multiple instances in one nova call, and repeat three times
* as a regular user
* TODO: same thing for cinder
"""
@classmethod
def skip_checks(cls):
super(TestLargeOpsScenario, cls).skip_checks()
if CONF.scenario.large_ops_number < 1:
raise cls.skipException("large_ops_number not set to multiple "
"instances")
@classmethod
def setup_credentials(cls):
cls.set_network_resources()
super(TestLargeOpsScenario, cls).setup_credentials()
@classmethod
def | (cls):
super(TestLargeOpsScenario, cls).resource_setup()
# list of cleanup calls to be executed in reverse order
cls._cleanup_resources = []
@classmethod
def resource_cleanup(cls):
while cls._cleanup_resources:
function, args, kwargs = cls._cleanup_resources.pop(-1)
try:
function(*args, **kwargs)
except lib_exc.NotFound:
pass
super(TestLargeOpsScenario, cls).resource_cleanup()
@classmethod
def addCleanupClass(cls, function, *arguments, **keywordArguments):
cls._cleanup_resources.append((function, arguments, keywordArguments))
def _wait_for_server_status(self, status):
for server in self.servers:
# Make sure nova list keeps working throughout the build process
self.servers_client.list_servers()
waiters.wait_for_server_status(self.servers_client,
server['id'], status)
def nova_boot(self):
name = data_utils.rand_name('scenario-server')
flavor_id = CONF.compute.flavor_ref
# Explicitly create secgroup to avoid cleanup at the end of testcases.
# Since no traffic is tested, we don't need to actually add rules to
# secgroup
secgroup = self.security_groups_client.create_security_group(
name='secgroup-%s' % name, description='secgroup-desc-%s' % name)
self.addCleanupClass(self.security_groups_client.delete_security_group,
secgroup['id'])
create_kwargs = {
'min_count': CONF.scenario.large_ops_number,
'security_groups': [{'name': secgroup['name']}]
}
network = self.get_tenant_network()
create_kwargs = fixed_network.set_networks_kwarg(network,
create_kwargs)
#self.servers_client.create_server(
self.create_server(
name,
'',
flavor_id,
**create_kwargs)
# needed because of bug 1199788
params = {'name': name}
server_list = self.servers_client.list_servers(**params)
self.servers = server_list['servers']
for server in self.servers:
# after deleting all servers - wait for all servers to clear
# before cleanup continues
self.addCleanupClass(self.servers_client.
wait_for_server_termination,
server['id'])
for server in self.servers:
self.addCleanupClass(self.servers_client.delete_server,
server['id'])
self._wait_for_server_status('ACTIVE')
def _large_ops_scenario(self):
#self.glance_image_create()
self.nova_boot()
@test.idempotent_id('14ba0e78-2ed9-4d17-9659-a48f4756ecb3')
@test.services('compute', 'image')
def test_large_ops_scenario_1(self):
self._large_ops_scenario()
@test.idempotent_id('b9b79b88-32aa-42db-8f8f-dcc8f4b4ccfe')
@test.services('compute', 'image')
def test_large_ops_scenario_2(self):
self._large_ops_scenario()
@test.idempotent_id('3aab7e82-2de3-419a-9da1-9f3a070668fb')
@test.services('compute', 'image')
def test_large_ops_scenario_3(self):
self._large_ops_scenario()
| resource_setup | identifier_name |
test_large_ops.py | # Copyright 2013 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from tempest_lib import exceptions as lib_exc
from tempest.common import fixed_network
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempest import config
from tempest.scenario import manager
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class TestLargeOpsScenario(manager.ScenarioTest):
"""
Test large operations.
This test below:
* Spin up multiple instances in one nova call, and repeat three times
* as a regular user
* TODO: same thing for cinder
"""
@classmethod
def skip_checks(cls):
super(TestLargeOpsScenario, cls).skip_checks()
if CONF.scenario.large_ops_number < 1:
raise cls.skipException("large_ops_number not set to multiple "
"instances")
@classmethod
def setup_credentials(cls):
cls.set_network_resources()
super(TestLargeOpsScenario, cls).setup_credentials()
@classmethod
def resource_setup(cls):
super(TestLargeOpsScenario, cls).resource_setup()
# list of cleanup calls to be executed in reverse order
cls._cleanup_resources = []
@classmethod
def resource_cleanup(cls):
while cls._cleanup_resources:
function, args, kwargs = cls._cleanup_resources.pop(-1)
try:
function(*args, **kwargs)
except lib_exc.NotFound:
pass
super(TestLargeOpsScenario, cls).resource_cleanup()
@classmethod
def addCleanupClass(cls, function, *arguments, **keywordArguments):
cls._cleanup_resources.append((function, arguments, keywordArguments))
def _wait_for_server_status(self, status):
for server in self.servers:
# Make sure nova list keeps working throughout the build process
self.servers_client.list_servers()
waiters.wait_for_server_status(self.servers_client,
server['id'], status)
def nova_boot(self):
name = data_utils.rand_name('scenario-server')
flavor_id = CONF.compute.flavor_ref
# Explicitly create secgroup to avoid cleanup at the end of testcases.
# Since no traffic is tested, we don't need to actually add rules to
# secgroup
secgroup = self.security_groups_client.create_security_group(
name='secgroup-%s' % name, description='secgroup-desc-%s' % name) | }
network = self.get_tenant_network()
create_kwargs = fixed_network.set_networks_kwarg(network,
create_kwargs)
#self.servers_client.create_server(
self.create_server(
name,
'',
flavor_id,
**create_kwargs)
# needed because of bug 1199788
params = {'name': name}
server_list = self.servers_client.list_servers(**params)
self.servers = server_list['servers']
for server in self.servers:
# after deleting all servers - wait for all servers to clear
# before cleanup continues
self.addCleanupClass(self.servers_client.
wait_for_server_termination,
server['id'])
for server in self.servers:
self.addCleanupClass(self.servers_client.delete_server,
server['id'])
self._wait_for_server_status('ACTIVE')
def _large_ops_scenario(self):
#self.glance_image_create()
self.nova_boot()
@test.idempotent_id('14ba0e78-2ed9-4d17-9659-a48f4756ecb3')
@test.services('compute', 'image')
def test_large_ops_scenario_1(self):
self._large_ops_scenario()
@test.idempotent_id('b9b79b88-32aa-42db-8f8f-dcc8f4b4ccfe')
@test.services('compute', 'image')
def test_large_ops_scenario_2(self):
self._large_ops_scenario()
@test.idempotent_id('3aab7e82-2de3-419a-9da1-9f3a070668fb')
@test.services('compute', 'image')
def test_large_ops_scenario_3(self):
self._large_ops_scenario() | self.addCleanupClass(self.security_groups_client.delete_security_group,
secgroup['id'])
create_kwargs = {
'min_count': CONF.scenario.large_ops_number,
'security_groups': [{'name': secgroup['name']}] | random_line_split |
test_large_ops.py | # Copyright 2013 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from tempest_lib import exceptions as lib_exc
from tempest.common import fixed_network
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempest import config
from tempest.scenario import manager
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class TestLargeOpsScenario(manager.ScenarioTest):
| """
Test large operations.
This test below:
* Spin up multiple instances in one nova call, and repeat three times
* as a regular user
* TODO: same thing for cinder
"""
@classmethod
def skip_checks(cls):
super(TestLargeOpsScenario, cls).skip_checks()
if CONF.scenario.large_ops_number < 1:
raise cls.skipException("large_ops_number not set to multiple "
"instances")
@classmethod
def setup_credentials(cls):
cls.set_network_resources()
super(TestLargeOpsScenario, cls).setup_credentials()
@classmethod
def resource_setup(cls):
super(TestLargeOpsScenario, cls).resource_setup()
# list of cleanup calls to be executed in reverse order
cls._cleanup_resources = []
@classmethod
def resource_cleanup(cls):
while cls._cleanup_resources:
function, args, kwargs = cls._cleanup_resources.pop(-1)
try:
function(*args, **kwargs)
except lib_exc.NotFound:
pass
super(TestLargeOpsScenario, cls).resource_cleanup()
@classmethod
def addCleanupClass(cls, function, *arguments, **keywordArguments):
cls._cleanup_resources.append((function, arguments, keywordArguments))
def _wait_for_server_status(self, status):
for server in self.servers:
# Make sure nova list keeps working throughout the build process
self.servers_client.list_servers()
waiters.wait_for_server_status(self.servers_client,
server['id'], status)
def nova_boot(self):
name = data_utils.rand_name('scenario-server')
flavor_id = CONF.compute.flavor_ref
# Explicitly create secgroup to avoid cleanup at the end of testcases.
# Since no traffic is tested, we don't need to actually add rules to
# secgroup
secgroup = self.security_groups_client.create_security_group(
name='secgroup-%s' % name, description='secgroup-desc-%s' % name)
self.addCleanupClass(self.security_groups_client.delete_security_group,
secgroup['id'])
create_kwargs = {
'min_count': CONF.scenario.large_ops_number,
'security_groups': [{'name': secgroup['name']}]
}
network = self.get_tenant_network()
create_kwargs = fixed_network.set_networks_kwarg(network,
create_kwargs)
#self.servers_client.create_server(
self.create_server(
name,
'',
flavor_id,
**create_kwargs)
# needed because of bug 1199788
params = {'name': name}
server_list = self.servers_client.list_servers(**params)
self.servers = server_list['servers']
for server in self.servers:
# after deleting all servers - wait for all servers to clear
# before cleanup continues
self.addCleanupClass(self.servers_client.
wait_for_server_termination,
server['id'])
for server in self.servers:
self.addCleanupClass(self.servers_client.delete_server,
server['id'])
self._wait_for_server_status('ACTIVE')
def _large_ops_scenario(self):
#self.glance_image_create()
self.nova_boot()
@test.idempotent_id('14ba0e78-2ed9-4d17-9659-a48f4756ecb3')
@test.services('compute', 'image')
def test_large_ops_scenario_1(self):
self._large_ops_scenario()
@test.idempotent_id('b9b79b88-32aa-42db-8f8f-dcc8f4b4ccfe')
@test.services('compute', 'image')
def test_large_ops_scenario_2(self):
self._large_ops_scenario()
@test.idempotent_id('3aab7e82-2de3-419a-9da1-9f3a070668fb')
@test.services('compute', 'image')
def test_large_ops_scenario_3(self):
self._large_ops_scenario() | identifier_body | |
test_large_ops.py | # Copyright 2013 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from tempest_lib import exceptions as lib_exc
from tempest.common import fixed_network
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempest import config
from tempest.scenario import manager
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class TestLargeOpsScenario(manager.ScenarioTest):
"""
Test large operations.
This test below:
* Spin up multiple instances in one nova call, and repeat three times
* as a regular user
* TODO: same thing for cinder
"""
@classmethod
def skip_checks(cls):
super(TestLargeOpsScenario, cls).skip_checks()
if CONF.scenario.large_ops_number < 1:
|
@classmethod
def setup_credentials(cls):
cls.set_network_resources()
super(TestLargeOpsScenario, cls).setup_credentials()
@classmethod
def resource_setup(cls):
super(TestLargeOpsScenario, cls).resource_setup()
# list of cleanup calls to be executed in reverse order
cls._cleanup_resources = []
@classmethod
def resource_cleanup(cls):
while cls._cleanup_resources:
function, args, kwargs = cls._cleanup_resources.pop(-1)
try:
function(*args, **kwargs)
except lib_exc.NotFound:
pass
super(TestLargeOpsScenario, cls).resource_cleanup()
@classmethod
def addCleanupClass(cls, function, *arguments, **keywordArguments):
cls._cleanup_resources.append((function, arguments, keywordArguments))
def _wait_for_server_status(self, status):
for server in self.servers:
# Make sure nova list keeps working throughout the build process
self.servers_client.list_servers()
waiters.wait_for_server_status(self.servers_client,
server['id'], status)
def nova_boot(self):
name = data_utils.rand_name('scenario-server')
flavor_id = CONF.compute.flavor_ref
# Explicitly create secgroup to avoid cleanup at the end of testcases.
# Since no traffic is tested, we don't need to actually add rules to
# secgroup
secgroup = self.security_groups_client.create_security_group(
name='secgroup-%s' % name, description='secgroup-desc-%s' % name)
self.addCleanupClass(self.security_groups_client.delete_security_group,
secgroup['id'])
create_kwargs = {
'min_count': CONF.scenario.large_ops_number,
'security_groups': [{'name': secgroup['name']}]
}
network = self.get_tenant_network()
create_kwargs = fixed_network.set_networks_kwarg(network,
create_kwargs)
#self.servers_client.create_server(
self.create_server(
name,
'',
flavor_id,
**create_kwargs)
# needed because of bug 1199788
params = {'name': name}
server_list = self.servers_client.list_servers(**params)
self.servers = server_list['servers']
for server in self.servers:
# after deleting all servers - wait for all servers to clear
# before cleanup continues
self.addCleanupClass(self.servers_client.
wait_for_server_termination,
server['id'])
for server in self.servers:
self.addCleanupClass(self.servers_client.delete_server,
server['id'])
self._wait_for_server_status('ACTIVE')
def _large_ops_scenario(self):
#self.glance_image_create()
self.nova_boot()
@test.idempotent_id('14ba0e78-2ed9-4d17-9659-a48f4756ecb3')
@test.services('compute', 'image')
def test_large_ops_scenario_1(self):
self._large_ops_scenario()
@test.idempotent_id('b9b79b88-32aa-42db-8f8f-dcc8f4b4ccfe')
@test.services('compute', 'image')
def test_large_ops_scenario_2(self):
self._large_ops_scenario()
@test.idempotent_id('3aab7e82-2de3-419a-9da1-9f3a070668fb')
@test.services('compute', 'image')
def test_large_ops_scenario_3(self):
self._large_ops_scenario()
| raise cls.skipException("large_ops_number not set to multiple "
"instances") | conditional_block |
trait-inheritance-auto.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.
// run-pass
#![allow(dead_code)]
// Testing that this impl turns A into a Quux, because
// A is already a Foo Bar Baz
impl<T:Foo + Bar + Baz> Quux for T { }
trait Foo { fn f(&self) -> isize; }
trait Bar { fn g(&self) -> isize; }
trait Baz { fn h(&self) -> isize; }
trait Quux: Foo + Bar + Baz { }
struct A { x: isize }
impl Foo for A { fn f(&self) -> isize { 10 } }
impl Bar for A { fn g(&self) -> isize { 20 } }
impl Baz for A { fn h(&self) -> isize { 30 } }
fn | <T:Quux>(a: &T) {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| f | identifier_name |
trait-inheritance-auto.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.
// run-pass
#![allow(dead_code)]
// Testing that this impl turns A into a Quux, because
// A is already a Foo Bar Baz
impl<T:Foo + Bar + Baz> Quux for T { }
trait Foo { fn f(&self) -> isize; }
trait Bar { fn g(&self) -> isize; } |
trait Quux: Foo + Bar + Baz { }
struct A { x: isize }
impl Foo for A { fn f(&self) -> isize { 10 } }
impl Bar for A { fn g(&self) -> isize { 20 } }
impl Baz for A { fn h(&self) -> isize { 30 } }
fn f<T:Quux>(a: &T) {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
} | trait Baz { fn h(&self) -> isize; } | random_line_split |
trait-inheritance-auto.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.
// run-pass
#![allow(dead_code)]
// Testing that this impl turns A into a Quux, because
// A is already a Foo Bar Baz
impl<T:Foo + Bar + Baz> Quux for T { }
trait Foo { fn f(&self) -> isize; }
trait Bar { fn g(&self) -> isize; }
trait Baz { fn h(&self) -> isize; }
trait Quux: Foo + Bar + Baz { }
struct A { x: isize }
impl Foo for A { fn f(&self) -> isize { 10 } }
impl Bar for A { fn g(&self) -> isize { 20 } }
impl Baz for A { fn h(&self) -> isize | }
fn f<T:Quux>(a: &T) {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| { 30 } | identifier_body |
stylesheet.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use {Namespace, Prefix};
use context::QuirksMode;
use cssparser::{Parser, ParserInput, RuleListParser};
use error_reporting::{ContextualParseError, ParseErrorReporter};
use fallible::FallibleVec;
use fxhash::FxHashMap;
use invalidation::media_queries::{MediaListKey, ToMediaListKey};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use media_queries::{Device, MediaList};
use parking_lot::RwLock;
use parser::ParserContext;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard};
use std::mem;
use std::sync::atomic::{AtomicBool, Ordering};
use style_traits::ParsingMode;
use stylesheets::{CssRule, CssRules, Origin, UrlExtraData};
use stylesheets::loader::StylesheetLoader;
use stylesheets::rule_parser::{State, TopLevelRuleParser};
use stylesheets::rules_iterator::{EffectiveRules, EffectiveRulesIterator};
use stylesheets::rules_iterator::{NestedRuleIterationCondition, RulesIterator};
use use_counters::UseCounters;
/// This structure holds the user-agent and user stylesheets.
pub struct | {
/// The lock used for user-agent stylesheets.
pub shared_lock: SharedRwLock,
/// The user or user agent stylesheets.
pub user_or_user_agent_stylesheets: Vec<DocumentStyleSheet>,
/// The quirks mode stylesheet.
pub quirks_mode_stylesheet: DocumentStyleSheet,
}
/// A set of namespaces applying to a given stylesheet.
///
/// The namespace id is used in gecko
#[derive(Clone, Debug, Default, MallocSizeOf)]
#[allow(missing_docs)]
pub struct Namespaces {
pub default: Option<Namespace>,
pub prefixes: FxHashMap<Prefix, Namespace>,
}
/// The contents of a given stylesheet. This effectively maps to a
/// StyleSheetInner in Gecko.
#[derive(Debug)]
pub struct StylesheetContents {
/// List of rules in the order they were found (important for
/// cascading order)
pub rules: Arc<Locked<CssRules>>,
/// The origin of this stylesheet.
pub origin: Origin,
/// The url data this stylesheet should use.
pub url_data: RwLock<UrlExtraData>,
/// The namespaces that apply to this stylesheet.
pub namespaces: RwLock<Namespaces>,
/// The quirks mode of this stylesheet.
pub quirks_mode: QuirksMode,
/// This stylesheet's source map URL.
pub source_map_url: RwLock<Option<String>>,
/// This stylesheet's source URL.
pub source_url: RwLock<Option<String>>,
}
impl StylesheetContents {
/// Parse a given CSS string, with a given url-data, origin, and
/// quirks mode.
pub fn from_str(
css: &str,
url_data: UrlExtraData,
origin: Origin,
shared_lock: &SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
use_counters: Option<&UseCounters>,
) -> Self {
let namespaces = RwLock::new(Namespaces::default());
let (rules, source_map_url, source_url) = Stylesheet::parse_rules(
css,
&url_data,
origin,
&mut *namespaces.write(),
&shared_lock,
stylesheet_loader,
error_reporter,
quirks_mode,
line_number_offset,
use_counters,
);
Self {
rules: CssRules::new(rules, &shared_lock),
origin: origin,
url_data: RwLock::new(url_data),
namespaces: namespaces,
quirks_mode: quirks_mode,
source_map_url: RwLock::new(source_map_url),
source_url: RwLock::new(source_url),
}
}
/// Returns a reference to the list of rules.
#[inline]
pub fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
&self.rules.read_with(guard).0
}
/// Measure heap usage.
#[cfg(feature = "gecko")]
pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
// Measurement of other fields may be added later.
self.rules.unconditional_shallow_size_of(ops) +
self.rules.read_with(guard).size_of(guard, ops)
}
}
impl DeepCloneWithLock for StylesheetContents {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
// Make a deep clone of the rules, using the new lock.
let rules = self
.rules
.read_with(guard)
.deep_clone_with_lock(lock, guard, params);
Self {
rules: Arc::new(lock.wrap(rules)),
quirks_mode: self.quirks_mode,
origin: self.origin,
url_data: RwLock::new((*self.url_data.read()).clone()),
namespaces: RwLock::new((*self.namespaces.read()).clone()),
source_map_url: RwLock::new((*self.source_map_url.read()).clone()),
source_url: RwLock::new((*self.source_url.read()).clone()),
}
}
}
/// The structure servo uses to represent a stylesheet.
#[derive(Debug)]
pub struct Stylesheet {
/// The contents of this stylesheet.
pub contents: StylesheetContents,
/// The lock used for objects inside this stylesheet
pub shared_lock: SharedRwLock,
/// List of media associated with the Stylesheet.
pub media: Arc<Locked<MediaList>>,
/// Whether this stylesheet should be disabled.
pub disabled: AtomicBool,
}
macro_rules! rule_filter {
($( $method: ident($variant:ident => $rule_type: ident), )+) => {
$(
#[allow(missing_docs)]
fn $method<F>(&self, device: &Device, guard: &SharedRwLockReadGuard, mut f: F)
where F: FnMut(&::stylesheets::$rule_type),
{
use stylesheets::CssRule;
for rule in self.effective_rules(device, guard) {
if let CssRule::$variant(ref lock) = *rule {
let rule = lock.read_with(guard);
f(&rule)
}
}
}
)+
}
}
/// A trait to represent a given stylesheet in a document.
pub trait StylesheetInDocument: ::std::fmt::Debug {
/// Get the stylesheet origin.
fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin;
/// Get the stylesheet quirks mode.
fn quirks_mode(&self, guard: &SharedRwLockReadGuard) -> QuirksMode;
/// Get whether this stylesheet is enabled.
fn enabled(&self) -> bool;
/// Get the media associated with this stylesheet.
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList>;
/// Returns a reference to the list of rules in this stylesheet.
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule];
/// Return an iterator using the condition `C`.
#[inline]
fn iter_rules<'a, 'b, C>(
&'a self,
device: &'a Device,
guard: &'a SharedRwLockReadGuard<'b>,
) -> RulesIterator<'a, 'b, C>
where
C: NestedRuleIterationCondition,
{
RulesIterator::new(device, self.quirks_mode(guard), guard, self.rules(guard))
}
/// Returns whether the style-sheet applies for the current device.
fn is_effective_for_device(&self, device: &Device, guard: &SharedRwLockReadGuard) -> bool {
match self.media(guard) {
Some(medialist) => medialist.evaluate(device, self.quirks_mode(guard)),
None => true,
}
}
/// Return an iterator over the effective rules within the style-sheet, as
/// according to the supplied `Device`.
#[inline]
fn effective_rules<'a, 'b>(
&'a self,
device: &'a Device,
guard: &'a SharedRwLockReadGuard<'b>,
) -> EffectiveRulesIterator<'a, 'b> {
self.iter_rules::<EffectiveRules>(device, guard)
}
rule_filter! {
effective_style_rules(Style => StyleRule),
effective_media_rules(Media => MediaRule),
effective_font_face_rules(FontFace => FontFaceRule),
effective_font_face_feature_values_rules(FontFeatureValues => FontFeatureValuesRule),
effective_counter_style_rules(CounterStyle => CounterStyleRule),
effective_viewport_rules(Viewport => ViewportRule),
effective_keyframes_rules(Keyframes => KeyframesRule),
effective_supports_rules(Supports => SupportsRule),
effective_page_rules(Page => PageRule),
effective_document_rules(Document => DocumentRule),
}
}
impl StylesheetInDocument for Stylesheet {
fn origin(&self, _guard: &SharedRwLockReadGuard) -> Origin {
self.contents.origin
}
fn quirks_mode(&self, _guard: &SharedRwLockReadGuard) -> QuirksMode {
self.contents.quirks_mode
}
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
Some(self.media.read_with(guard))
}
fn enabled(&self) -> bool {
!self.disabled()
}
#[inline]
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
self.contents.rules(guard)
}
}
/// A simple wrapper over an `Arc<Stylesheet>`, with pointer comparison, and
/// suitable for its use in a `StylesheetSet`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct DocumentStyleSheet(
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] pub Arc<Stylesheet>,
);
impl PartialEq for DocumentStyleSheet {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl ToMediaListKey for DocumentStyleSheet {
fn to_media_list_key(&self) -> MediaListKey {
self.0.to_media_list_key()
}
}
impl StylesheetInDocument for DocumentStyleSheet {
fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin {
self.0.origin(guard)
}
fn quirks_mode(&self, guard: &SharedRwLockReadGuard) -> QuirksMode {
self.0.quirks_mode(guard)
}
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
self.0.media(guard)
}
fn enabled(&self) -> bool {
self.0.enabled()
}
#[inline]
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
self.0.rules(guard)
}
}
impl Stylesheet {
/// Updates an empty stylesheet from a given string of text.
pub fn update_from_str(
existing: &Stylesheet,
css: &str,
url_data: UrlExtraData,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
line_number_offset: u32,
) {
let namespaces = RwLock::new(Namespaces::default());
// FIXME: Consider adding use counters to Servo?
let (rules, source_map_url, source_url) = Self::parse_rules(
css,
&url_data,
existing.contents.origin,
&mut *namespaces.write(),
&existing.shared_lock,
stylesheet_loader,
error_reporter,
existing.contents.quirks_mode,
line_number_offset,
/* use_counters = */ None,
);
*existing.contents.url_data.write() = url_data;
mem::swap(
&mut *existing.contents.namespaces.write(),
&mut *namespaces.write(),
);
// Acquire the lock *after* parsing, to minimize the exclusive section.
let mut guard = existing.shared_lock.write();
*existing.contents.rules.write_with(&mut guard) = CssRules(rules);
*existing.contents.source_map_url.write() = source_map_url;
*existing.contents.source_url.write() = source_url;
}
fn parse_rules(
css: &str,
url_data: &UrlExtraData,
origin: Origin,
namespaces: &mut Namespaces,
shared_lock: &SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
use_counters: Option<&UseCounters>,
) -> (Vec<CssRule>, Option<String>, Option<String>) {
let mut rules = Vec::new();
let mut input = ParserInput::new_with_line_number_offset(css, line_number_offset);
let mut input = Parser::new(&mut input);
let context = ParserContext::new(
origin,
url_data,
None,
ParsingMode::DEFAULT,
quirks_mode,
error_reporter,
use_counters,
);
let rule_parser = TopLevelRuleParser {
shared_lock,
loader: stylesheet_loader,
context,
state: State::Start,
dom_error: None,
insert_rule_context: None,
namespaces,
};
{
let mut iter = RuleListParser::new_for_stylesheet(&mut input, rule_parser);
while let Some(result) = iter.next() {
match result {
Ok(rule) => {
// Use a fallible push here, and if it fails, just
// fall out of the loop. This will cause the page to
// be shown incorrectly, but it's better than OOMing.
if rules.try_push(rule).is_err() {
break;
}
},
Err((error, slice)) => {
let location = error.location;
let error = ContextualParseError::InvalidRule(slice, error);
iter.parser.context.log_css_error(location, error);
},
}
}
}
let source_map_url = input.current_source_map_url().map(String::from);
let source_url = input.current_source_url().map(String::from);
(rules, source_map_url, source_url)
}
/// Creates an empty stylesheet and parses it with a given base url, origin
/// and media.
///
/// Effectively creates a new stylesheet and forwards the hard work to
/// `Stylesheet::update_from_str`.
pub fn from_str(
css: &str,
url_data: UrlExtraData,
origin: Origin,
media: Arc<Locked<MediaList>>,
shared_lock: SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
) -> Self {
// FIXME: Consider adding use counters to Servo?
let contents = StylesheetContents::from_str(
css,
url_data,
origin,
&shared_lock,
stylesheet_loader,
error_reporter,
quirks_mode,
line_number_offset,
/* use_counters = */ None,
);
Stylesheet {
contents,
shared_lock,
media,
disabled: AtomicBool::new(false),
}
}
/// Returns whether the stylesheet has been explicitly disabled through the
/// CSSOM.
pub fn disabled(&self) -> bool {
self.disabled.load(Ordering::SeqCst)
}
/// Records that the stylesheet has been explicitly disabled through the
/// CSSOM.
///
/// Returns whether the the call resulted in a change in disabled state.
///
/// Disabled stylesheets remain in the document, but their rules are not
/// added to the Stylist.
pub fn set_disabled(&self, disabled: bool) -> bool {
self.disabled.swap(disabled, Ordering::SeqCst) != disabled
}
}
#[cfg(feature = "servo")]
impl Clone for Stylesheet {
fn clone(&self) -> Self {
// Create a new lock for our clone.
let lock = self.shared_lock.clone();
let guard = self.shared_lock.read();
// Make a deep clone of the media, using the new lock.
let media = self.media.read_with(&guard).clone();
let media = Arc::new(lock.wrap(media));
let contents = self
.contents
.deep_clone_with_lock(&lock, &guard, &DeepCloneParams);
Stylesheet {
contents,
media: media,
shared_lock: lock,
disabled: AtomicBool::new(self.disabled.load(Ordering::SeqCst)),
}
}
}
| UserAgentStylesheets | identifier_name |
stylesheet.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use {Namespace, Prefix};
use context::QuirksMode;
use cssparser::{Parser, ParserInput, RuleListParser};
use error_reporting::{ContextualParseError, ParseErrorReporter};
use fallible::FallibleVec;
use fxhash::FxHashMap;
use invalidation::media_queries::{MediaListKey, ToMediaListKey};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use media_queries::{Device, MediaList};
use parking_lot::RwLock;
use parser::ParserContext;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard};
use std::mem;
use std::sync::atomic::{AtomicBool, Ordering};
use style_traits::ParsingMode;
use stylesheets::{CssRule, CssRules, Origin, UrlExtraData};
use stylesheets::loader::StylesheetLoader;
use stylesheets::rule_parser::{State, TopLevelRuleParser};
use stylesheets::rules_iterator::{EffectiveRules, EffectiveRulesIterator};
use stylesheets::rules_iterator::{NestedRuleIterationCondition, RulesIterator};
use use_counters::UseCounters;
/// This structure holds the user-agent and user stylesheets.
pub struct UserAgentStylesheets {
/// The lock used for user-agent stylesheets.
pub shared_lock: SharedRwLock,
/// The user or user agent stylesheets.
pub user_or_user_agent_stylesheets: Vec<DocumentStyleSheet>,
/// The quirks mode stylesheet.
pub quirks_mode_stylesheet: DocumentStyleSheet,
}
/// A set of namespaces applying to a given stylesheet.
///
/// The namespace id is used in gecko
#[derive(Clone, Debug, Default, MallocSizeOf)]
#[allow(missing_docs)]
pub struct Namespaces {
pub default: Option<Namespace>,
pub prefixes: FxHashMap<Prefix, Namespace>,
}
/// The contents of a given stylesheet. This effectively maps to a
/// StyleSheetInner in Gecko.
#[derive(Debug)]
pub struct StylesheetContents {
/// List of rules in the order they were found (important for
/// cascading order)
pub rules: Arc<Locked<CssRules>>,
/// The origin of this stylesheet.
pub origin: Origin,
/// The url data this stylesheet should use.
pub url_data: RwLock<UrlExtraData>,
/// The namespaces that apply to this stylesheet.
pub namespaces: RwLock<Namespaces>,
/// The quirks mode of this stylesheet.
pub quirks_mode: QuirksMode,
/// This stylesheet's source map URL.
pub source_map_url: RwLock<Option<String>>,
/// This stylesheet's source URL.
pub source_url: RwLock<Option<String>>,
}
impl StylesheetContents {
/// Parse a given CSS string, with a given url-data, origin, and
/// quirks mode.
pub fn from_str(
css: &str,
url_data: UrlExtraData,
origin: Origin,
shared_lock: &SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
use_counters: Option<&UseCounters>,
) -> Self {
let namespaces = RwLock::new(Namespaces::default());
let (rules, source_map_url, source_url) = Stylesheet::parse_rules(
css,
&url_data,
origin,
&mut *namespaces.write(),
&shared_lock,
stylesheet_loader,
error_reporter,
quirks_mode,
line_number_offset,
use_counters,
);
Self {
rules: CssRules::new(rules, &shared_lock),
origin: origin,
url_data: RwLock::new(url_data),
namespaces: namespaces,
quirks_mode: quirks_mode,
source_map_url: RwLock::new(source_map_url),
source_url: RwLock::new(source_url),
}
}
/// Returns a reference to the list of rules.
#[inline]
pub fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
&self.rules.read_with(guard).0
}
/// Measure heap usage.
#[cfg(feature = "gecko")]
pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
// Measurement of other fields may be added later.
self.rules.unconditional_shallow_size_of(ops) +
self.rules.read_with(guard).size_of(guard, ops)
}
}
impl DeepCloneWithLock for StylesheetContents {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
// Make a deep clone of the rules, using the new lock.
let rules = self
.rules
.read_with(guard)
.deep_clone_with_lock(lock, guard, params);
Self {
rules: Arc::new(lock.wrap(rules)),
quirks_mode: self.quirks_mode,
origin: self.origin,
url_data: RwLock::new((*self.url_data.read()).clone()),
namespaces: RwLock::new((*self.namespaces.read()).clone()),
source_map_url: RwLock::new((*self.source_map_url.read()).clone()),
source_url: RwLock::new((*self.source_url.read()).clone()),
}
}
}
/// The structure servo uses to represent a stylesheet.
#[derive(Debug)]
pub struct Stylesheet {
/// The contents of this stylesheet.
pub contents: StylesheetContents,
/// The lock used for objects inside this stylesheet
pub shared_lock: SharedRwLock,
/// List of media associated with the Stylesheet.
pub media: Arc<Locked<MediaList>>,
/// Whether this stylesheet should be disabled.
pub disabled: AtomicBool,
}
macro_rules! rule_filter {
($( $method: ident($variant:ident => $rule_type: ident), )+) => {
$(
#[allow(missing_docs)]
fn $method<F>(&self, device: &Device, guard: &SharedRwLockReadGuard, mut f: F)
where F: FnMut(&::stylesheets::$rule_type),
{
use stylesheets::CssRule;
for rule in self.effective_rules(device, guard) {
if let CssRule::$variant(ref lock) = *rule {
let rule = lock.read_with(guard);
f(&rule)
}
}
}
)+
}
}
/// A trait to represent a given stylesheet in a document.
pub trait StylesheetInDocument: ::std::fmt::Debug {
/// Get the stylesheet origin.
fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin;
/// Get the stylesheet quirks mode.
fn quirks_mode(&self, guard: &SharedRwLockReadGuard) -> QuirksMode;
/// Get whether this stylesheet is enabled.
fn enabled(&self) -> bool;
/// Get the media associated with this stylesheet.
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList>;
/// Returns a reference to the list of rules in this stylesheet.
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule];
/// Return an iterator using the condition `C`.
#[inline]
fn iter_rules<'a, 'b, C>(
&'a self,
device: &'a Device,
guard: &'a SharedRwLockReadGuard<'b>,
) -> RulesIterator<'a, 'b, C>
where
C: NestedRuleIterationCondition,
{
RulesIterator::new(device, self.quirks_mode(guard), guard, self.rules(guard))
}
/// Returns whether the style-sheet applies for the current device.
fn is_effective_for_device(&self, device: &Device, guard: &SharedRwLockReadGuard) -> bool {
match self.media(guard) {
Some(medialist) => medialist.evaluate(device, self.quirks_mode(guard)),
None => true,
}
}
/// Return an iterator over the effective rules within the style-sheet, as
/// according to the supplied `Device`.
#[inline]
fn effective_rules<'a, 'b>(
&'a self,
device: &'a Device,
guard: &'a SharedRwLockReadGuard<'b>,
) -> EffectiveRulesIterator<'a, 'b> {
self.iter_rules::<EffectiveRules>(device, guard)
}
rule_filter! {
effective_style_rules(Style => StyleRule),
effective_media_rules(Media => MediaRule),
effective_font_face_rules(FontFace => FontFaceRule),
effective_font_face_feature_values_rules(FontFeatureValues => FontFeatureValuesRule),
effective_counter_style_rules(CounterStyle => CounterStyleRule),
effective_viewport_rules(Viewport => ViewportRule),
effective_keyframes_rules(Keyframes => KeyframesRule),
effective_supports_rules(Supports => SupportsRule),
effective_page_rules(Page => PageRule),
effective_document_rules(Document => DocumentRule),
}
}
impl StylesheetInDocument for Stylesheet {
fn origin(&self, _guard: &SharedRwLockReadGuard) -> Origin {
self.contents.origin
}
fn quirks_mode(&self, _guard: &SharedRwLockReadGuard) -> QuirksMode {
self.contents.quirks_mode
}
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
Some(self.media.read_with(guard))
}
fn enabled(&self) -> bool {
!self.disabled()
}
#[inline]
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
self.contents.rules(guard)
}
}
/// A simple wrapper over an `Arc<Stylesheet>`, with pointer comparison, and
/// suitable for its use in a `StylesheetSet`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct DocumentStyleSheet(
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] pub Arc<Stylesheet>,
);
| Arc::ptr_eq(&self.0, &other.0)
}
}
impl ToMediaListKey for DocumentStyleSheet {
fn to_media_list_key(&self) -> MediaListKey {
self.0.to_media_list_key()
}
}
impl StylesheetInDocument for DocumentStyleSheet {
fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin {
self.0.origin(guard)
}
fn quirks_mode(&self, guard: &SharedRwLockReadGuard) -> QuirksMode {
self.0.quirks_mode(guard)
}
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
self.0.media(guard)
}
fn enabled(&self) -> bool {
self.0.enabled()
}
#[inline]
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
self.0.rules(guard)
}
}
impl Stylesheet {
/// Updates an empty stylesheet from a given string of text.
pub fn update_from_str(
existing: &Stylesheet,
css: &str,
url_data: UrlExtraData,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
line_number_offset: u32,
) {
let namespaces = RwLock::new(Namespaces::default());
// FIXME: Consider adding use counters to Servo?
let (rules, source_map_url, source_url) = Self::parse_rules(
css,
&url_data,
existing.contents.origin,
&mut *namespaces.write(),
&existing.shared_lock,
stylesheet_loader,
error_reporter,
existing.contents.quirks_mode,
line_number_offset,
/* use_counters = */ None,
);
*existing.contents.url_data.write() = url_data;
mem::swap(
&mut *existing.contents.namespaces.write(),
&mut *namespaces.write(),
);
// Acquire the lock *after* parsing, to minimize the exclusive section.
let mut guard = existing.shared_lock.write();
*existing.contents.rules.write_with(&mut guard) = CssRules(rules);
*existing.contents.source_map_url.write() = source_map_url;
*existing.contents.source_url.write() = source_url;
}
fn parse_rules(
css: &str,
url_data: &UrlExtraData,
origin: Origin,
namespaces: &mut Namespaces,
shared_lock: &SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
use_counters: Option<&UseCounters>,
) -> (Vec<CssRule>, Option<String>, Option<String>) {
let mut rules = Vec::new();
let mut input = ParserInput::new_with_line_number_offset(css, line_number_offset);
let mut input = Parser::new(&mut input);
let context = ParserContext::new(
origin,
url_data,
None,
ParsingMode::DEFAULT,
quirks_mode,
error_reporter,
use_counters,
);
let rule_parser = TopLevelRuleParser {
shared_lock,
loader: stylesheet_loader,
context,
state: State::Start,
dom_error: None,
insert_rule_context: None,
namespaces,
};
{
let mut iter = RuleListParser::new_for_stylesheet(&mut input, rule_parser);
while let Some(result) = iter.next() {
match result {
Ok(rule) => {
// Use a fallible push here, and if it fails, just
// fall out of the loop. This will cause the page to
// be shown incorrectly, but it's better than OOMing.
if rules.try_push(rule).is_err() {
break;
}
},
Err((error, slice)) => {
let location = error.location;
let error = ContextualParseError::InvalidRule(slice, error);
iter.parser.context.log_css_error(location, error);
},
}
}
}
let source_map_url = input.current_source_map_url().map(String::from);
let source_url = input.current_source_url().map(String::from);
(rules, source_map_url, source_url)
}
/// Creates an empty stylesheet and parses it with a given base url, origin
/// and media.
///
/// Effectively creates a new stylesheet and forwards the hard work to
/// `Stylesheet::update_from_str`.
pub fn from_str(
css: &str,
url_data: UrlExtraData,
origin: Origin,
media: Arc<Locked<MediaList>>,
shared_lock: SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
) -> Self {
// FIXME: Consider adding use counters to Servo?
let contents = StylesheetContents::from_str(
css,
url_data,
origin,
&shared_lock,
stylesheet_loader,
error_reporter,
quirks_mode,
line_number_offset,
/* use_counters = */ None,
);
Stylesheet {
contents,
shared_lock,
media,
disabled: AtomicBool::new(false),
}
}
/// Returns whether the stylesheet has been explicitly disabled through the
/// CSSOM.
pub fn disabled(&self) -> bool {
self.disabled.load(Ordering::SeqCst)
}
/// Records that the stylesheet has been explicitly disabled through the
/// CSSOM.
///
/// Returns whether the the call resulted in a change in disabled state.
///
/// Disabled stylesheets remain in the document, but their rules are not
/// added to the Stylist.
pub fn set_disabled(&self, disabled: bool) -> bool {
self.disabled.swap(disabled, Ordering::SeqCst) != disabled
}
}
#[cfg(feature = "servo")]
impl Clone for Stylesheet {
fn clone(&self) -> Self {
// Create a new lock for our clone.
let lock = self.shared_lock.clone();
let guard = self.shared_lock.read();
// Make a deep clone of the media, using the new lock.
let media = self.media.read_with(&guard).clone();
let media = Arc::new(lock.wrap(media));
let contents = self
.contents
.deep_clone_with_lock(&lock, &guard, &DeepCloneParams);
Stylesheet {
contents,
media: media,
shared_lock: lock,
disabled: AtomicBool::new(self.disabled.load(Ordering::SeqCst)),
}
}
} | impl PartialEq for DocumentStyleSheet {
fn eq(&self, other: &Self) -> bool { | random_line_split |
stylesheet.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use {Namespace, Prefix};
use context::QuirksMode;
use cssparser::{Parser, ParserInput, RuleListParser};
use error_reporting::{ContextualParseError, ParseErrorReporter};
use fallible::FallibleVec;
use fxhash::FxHashMap;
use invalidation::media_queries::{MediaListKey, ToMediaListKey};
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
use media_queries::{Device, MediaList};
use parking_lot::RwLock;
use parser::ParserContext;
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard};
use std::mem;
use std::sync::atomic::{AtomicBool, Ordering};
use style_traits::ParsingMode;
use stylesheets::{CssRule, CssRules, Origin, UrlExtraData};
use stylesheets::loader::StylesheetLoader;
use stylesheets::rule_parser::{State, TopLevelRuleParser};
use stylesheets::rules_iterator::{EffectiveRules, EffectiveRulesIterator};
use stylesheets::rules_iterator::{NestedRuleIterationCondition, RulesIterator};
use use_counters::UseCounters;
/// This structure holds the user-agent and user stylesheets.
pub struct UserAgentStylesheets {
/// The lock used for user-agent stylesheets.
pub shared_lock: SharedRwLock,
/// The user or user agent stylesheets.
pub user_or_user_agent_stylesheets: Vec<DocumentStyleSheet>,
/// The quirks mode stylesheet.
pub quirks_mode_stylesheet: DocumentStyleSheet,
}
/// A set of namespaces applying to a given stylesheet.
///
/// The namespace id is used in gecko
#[derive(Clone, Debug, Default, MallocSizeOf)]
#[allow(missing_docs)]
pub struct Namespaces {
pub default: Option<Namespace>,
pub prefixes: FxHashMap<Prefix, Namespace>,
}
/// The contents of a given stylesheet. This effectively maps to a
/// StyleSheetInner in Gecko.
#[derive(Debug)]
pub struct StylesheetContents {
/// List of rules in the order they were found (important for
/// cascading order)
pub rules: Arc<Locked<CssRules>>,
/// The origin of this stylesheet.
pub origin: Origin,
/// The url data this stylesheet should use.
pub url_data: RwLock<UrlExtraData>,
/// The namespaces that apply to this stylesheet.
pub namespaces: RwLock<Namespaces>,
/// The quirks mode of this stylesheet.
pub quirks_mode: QuirksMode,
/// This stylesheet's source map URL.
pub source_map_url: RwLock<Option<String>>,
/// This stylesheet's source URL.
pub source_url: RwLock<Option<String>>,
}
impl StylesheetContents {
/// Parse a given CSS string, with a given url-data, origin, and
/// quirks mode.
pub fn from_str(
css: &str,
url_data: UrlExtraData,
origin: Origin,
shared_lock: &SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
use_counters: Option<&UseCounters>,
) -> Self {
let namespaces = RwLock::new(Namespaces::default());
let (rules, source_map_url, source_url) = Stylesheet::parse_rules(
css,
&url_data,
origin,
&mut *namespaces.write(),
&shared_lock,
stylesheet_loader,
error_reporter,
quirks_mode,
line_number_offset,
use_counters,
);
Self {
rules: CssRules::new(rules, &shared_lock),
origin: origin,
url_data: RwLock::new(url_data),
namespaces: namespaces,
quirks_mode: quirks_mode,
source_map_url: RwLock::new(source_map_url),
source_url: RwLock::new(source_url),
}
}
/// Returns a reference to the list of rules.
#[inline]
pub fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
&self.rules.read_with(guard).0
}
/// Measure heap usage.
#[cfg(feature = "gecko")]
pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
// Measurement of other fields may be added later.
self.rules.unconditional_shallow_size_of(ops) +
self.rules.read_with(guard).size_of(guard, ops)
}
}
impl DeepCloneWithLock for StylesheetContents {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
// Make a deep clone of the rules, using the new lock.
let rules = self
.rules
.read_with(guard)
.deep_clone_with_lock(lock, guard, params);
Self {
rules: Arc::new(lock.wrap(rules)),
quirks_mode: self.quirks_mode,
origin: self.origin,
url_data: RwLock::new((*self.url_data.read()).clone()),
namespaces: RwLock::new((*self.namespaces.read()).clone()),
source_map_url: RwLock::new((*self.source_map_url.read()).clone()),
source_url: RwLock::new((*self.source_url.read()).clone()),
}
}
}
/// The structure servo uses to represent a stylesheet.
#[derive(Debug)]
pub struct Stylesheet {
/// The contents of this stylesheet.
pub contents: StylesheetContents,
/// The lock used for objects inside this stylesheet
pub shared_lock: SharedRwLock,
/// List of media associated with the Stylesheet.
pub media: Arc<Locked<MediaList>>,
/// Whether this stylesheet should be disabled.
pub disabled: AtomicBool,
}
macro_rules! rule_filter {
($( $method: ident($variant:ident => $rule_type: ident), )+) => {
$(
#[allow(missing_docs)]
fn $method<F>(&self, device: &Device, guard: &SharedRwLockReadGuard, mut f: F)
where F: FnMut(&::stylesheets::$rule_type),
{
use stylesheets::CssRule;
for rule in self.effective_rules(device, guard) {
if let CssRule::$variant(ref lock) = *rule {
let rule = lock.read_with(guard);
f(&rule)
}
}
}
)+
}
}
/// A trait to represent a given stylesheet in a document.
pub trait StylesheetInDocument: ::std::fmt::Debug {
/// Get the stylesheet origin.
fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin;
/// Get the stylesheet quirks mode.
fn quirks_mode(&self, guard: &SharedRwLockReadGuard) -> QuirksMode;
/// Get whether this stylesheet is enabled.
fn enabled(&self) -> bool;
/// Get the media associated with this stylesheet.
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList>;
/// Returns a reference to the list of rules in this stylesheet.
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule];
/// Return an iterator using the condition `C`.
#[inline]
fn iter_rules<'a, 'b, C>(
&'a self,
device: &'a Device,
guard: &'a SharedRwLockReadGuard<'b>,
) -> RulesIterator<'a, 'b, C>
where
C: NestedRuleIterationCondition,
{
RulesIterator::new(device, self.quirks_mode(guard), guard, self.rules(guard))
}
/// Returns whether the style-sheet applies for the current device.
fn is_effective_for_device(&self, device: &Device, guard: &SharedRwLockReadGuard) -> bool {
match self.media(guard) {
Some(medialist) => medialist.evaluate(device, self.quirks_mode(guard)),
None => true,
}
}
/// Return an iterator over the effective rules within the style-sheet, as
/// according to the supplied `Device`.
#[inline]
fn effective_rules<'a, 'b>(
&'a self,
device: &'a Device,
guard: &'a SharedRwLockReadGuard<'b>,
) -> EffectiveRulesIterator<'a, 'b> {
self.iter_rules::<EffectiveRules>(device, guard)
}
rule_filter! {
effective_style_rules(Style => StyleRule),
effective_media_rules(Media => MediaRule),
effective_font_face_rules(FontFace => FontFaceRule),
effective_font_face_feature_values_rules(FontFeatureValues => FontFeatureValuesRule),
effective_counter_style_rules(CounterStyle => CounterStyleRule),
effective_viewport_rules(Viewport => ViewportRule),
effective_keyframes_rules(Keyframes => KeyframesRule),
effective_supports_rules(Supports => SupportsRule),
effective_page_rules(Page => PageRule),
effective_document_rules(Document => DocumentRule),
}
}
impl StylesheetInDocument for Stylesheet {
fn origin(&self, _guard: &SharedRwLockReadGuard) -> Origin {
self.contents.origin
}
fn quirks_mode(&self, _guard: &SharedRwLockReadGuard) -> QuirksMode {
self.contents.quirks_mode
}
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
Some(self.media.read_with(guard))
}
fn enabled(&self) -> bool {
!self.disabled()
}
#[inline]
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
self.contents.rules(guard)
}
}
/// A simple wrapper over an `Arc<Stylesheet>`, with pointer comparison, and
/// suitable for its use in a `StylesheetSet`.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct DocumentStyleSheet(
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] pub Arc<Stylesheet>,
);
impl PartialEq for DocumentStyleSheet {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl ToMediaListKey for DocumentStyleSheet {
fn to_media_list_key(&self) -> MediaListKey {
self.0.to_media_list_key()
}
}
impl StylesheetInDocument for DocumentStyleSheet {
fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin {
self.0.origin(guard)
}
fn quirks_mode(&self, guard: &SharedRwLockReadGuard) -> QuirksMode {
self.0.quirks_mode(guard)
}
fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
self.0.media(guard)
}
fn enabled(&self) -> bool {
self.0.enabled()
}
#[inline]
fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] {
self.0.rules(guard)
}
}
impl Stylesheet {
/// Updates an empty stylesheet from a given string of text.
pub fn update_from_str(
existing: &Stylesheet,
css: &str,
url_data: UrlExtraData,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
line_number_offset: u32,
) {
let namespaces = RwLock::new(Namespaces::default());
// FIXME: Consider adding use counters to Servo?
let (rules, source_map_url, source_url) = Self::parse_rules(
css,
&url_data,
existing.contents.origin,
&mut *namespaces.write(),
&existing.shared_lock,
stylesheet_loader,
error_reporter,
existing.contents.quirks_mode,
line_number_offset,
/* use_counters = */ None,
);
*existing.contents.url_data.write() = url_data;
mem::swap(
&mut *existing.contents.namespaces.write(),
&mut *namespaces.write(),
);
// Acquire the lock *after* parsing, to minimize the exclusive section.
let mut guard = existing.shared_lock.write();
*existing.contents.rules.write_with(&mut guard) = CssRules(rules);
*existing.contents.source_map_url.write() = source_map_url;
*existing.contents.source_url.write() = source_url;
}
fn parse_rules(
css: &str,
url_data: &UrlExtraData,
origin: Origin,
namespaces: &mut Namespaces,
shared_lock: &SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
use_counters: Option<&UseCounters>,
) -> (Vec<CssRule>, Option<String>, Option<String>) {
let mut rules = Vec::new();
let mut input = ParserInput::new_with_line_number_offset(css, line_number_offset);
let mut input = Parser::new(&mut input);
let context = ParserContext::new(
origin,
url_data,
None,
ParsingMode::DEFAULT,
quirks_mode,
error_reporter,
use_counters,
);
let rule_parser = TopLevelRuleParser {
shared_lock,
loader: stylesheet_loader,
context,
state: State::Start,
dom_error: None,
insert_rule_context: None,
namespaces,
};
{
let mut iter = RuleListParser::new_for_stylesheet(&mut input, rule_parser);
while let Some(result) = iter.next() {
match result {
Ok(rule) => {
// Use a fallible push here, and if it fails, just
// fall out of the loop. This will cause the page to
// be shown incorrectly, but it's better than OOMing.
if rules.try_push(rule).is_err() {
break;
}
},
Err((error, slice)) => {
let location = error.location;
let error = ContextualParseError::InvalidRule(slice, error);
iter.parser.context.log_css_error(location, error);
},
}
}
}
let source_map_url = input.current_source_map_url().map(String::from);
let source_url = input.current_source_url().map(String::from);
(rules, source_map_url, source_url)
}
/// Creates an empty stylesheet and parses it with a given base url, origin
/// and media.
///
/// Effectively creates a new stylesheet and forwards the hard work to
/// `Stylesheet::update_from_str`.
pub fn from_str(
css: &str,
url_data: UrlExtraData,
origin: Origin,
media: Arc<Locked<MediaList>>,
shared_lock: SharedRwLock,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: Option<&ParseErrorReporter>,
quirks_mode: QuirksMode,
line_number_offset: u32,
) -> Self {
// FIXME: Consider adding use counters to Servo?
let contents = StylesheetContents::from_str(
css,
url_data,
origin,
&shared_lock,
stylesheet_loader,
error_reporter,
quirks_mode,
line_number_offset,
/* use_counters = */ None,
);
Stylesheet {
contents,
shared_lock,
media,
disabled: AtomicBool::new(false),
}
}
/// Returns whether the stylesheet has been explicitly disabled through the
/// CSSOM.
pub fn disabled(&self) -> bool |
/// Records that the stylesheet has been explicitly disabled through the
/// CSSOM.
///
/// Returns whether the the call resulted in a change in disabled state.
///
/// Disabled stylesheets remain in the document, but their rules are not
/// added to the Stylist.
pub fn set_disabled(&self, disabled: bool) -> bool {
self.disabled.swap(disabled, Ordering::SeqCst) != disabled
}
}
#[cfg(feature = "servo")]
impl Clone for Stylesheet {
fn clone(&self) -> Self {
// Create a new lock for our clone.
let lock = self.shared_lock.clone();
let guard = self.shared_lock.read();
// Make a deep clone of the media, using the new lock.
let media = self.media.read_with(&guard).clone();
let media = Arc::new(lock.wrap(media));
let contents = self
.contents
.deep_clone_with_lock(&lock, &guard, &DeepCloneParams);
Stylesheet {
contents,
media: media,
shared_lock: lock,
disabled: AtomicBool::new(self.disabled.load(Ordering::SeqCst)),
}
}
}
| {
self.disabled.load(Ordering::SeqCst)
} | identifier_body |
base_ovh_konnector.js | // Generated by CoffeeScript 1.10.0
var Bill, baseKonnector, filterExisting, linkBankOperation, ovhFetcher, saveDataAndFile;
ovhFetcher = require('../lib/ovh_fetcher');
filterExisting = require('../lib/filter_existing');
saveDataAndFile = require('../lib/save_data_and_file');
linkBankOperation = require('../lib/link_bank_operation');
baseKonnector = require('../lib/base_konnector');
Bill = require('../models/bill');
module.exports = {
createNew: function(ovhApi, name, slug) {
var connector, fetchBills, fileOptions, logger, ovhFetcherInstance;
fileOptions = {
vendor: slug,
dateFormat: 'YYYYMMDD'
};
logger = require('printit')({
prefix: name,
date: true
});
ovhFetcherInstance = ovhFetcher["new"](ovhApi, slug, logger);
fetchBills = function(requiredFields, entries, body, next) {
return ovhFetcherInstance.fetchBills(requiredFields, entries, body, next);
};
return connector = baseKonnector.createNew({
name: name,
fields: {
loginUrl: "link",
token: "hidden",
folderPath: "folder"
},
models: [Bill],
fetchOperations: [
fetchBills, filterExisting(logger, Bill), saveDataAndFile(logger, Bill, fileOptions, ['bill']), linkBankOperation({
log: logger,
model: Bill,
identifier: slug,
dateDelta: 4, | }
}; | amountDelta: 0.1
})
]
}); | random_line_split |
test.rs | use quickcheck::{TestResult, quickcheck};
use rand::Rng;
use super::{integer_value, regex_value};
use expectest::prelude::*;
use pact_matching::s;
#[test]
fn validates_integer_value() {
fn prop(s: String) -> TestResult {
let mut rng = ::rand::thread_rng();
if rng.gen() && s.chars().any(|ch| !ch.is_numeric()) {
TestResult::discard()
} else {
let validation = integer_value(s.clone());
match validation {
Ok(_) => TestResult::from_bool(!s.is_empty() && s.chars().all(|ch| ch.is_numeric() )),
Err(_) => TestResult::from_bool(s.is_empty() || s.chars().find(|ch| !ch.is_numeric() ).is_some())
}
}
} | quickcheck(prop as fn(_) -> _);
expect!(integer_value(s!("1234"))).to(be_ok());
expect!(integer_value(s!("1234x"))).to(be_err());
}
#[test]
fn validates_regex_value() {
expect!(regex_value(s!("1234"))).to(be_ok());
expect!(regex_value(s!("["))).to(be_err());
} | random_line_split | |
test.rs | use quickcheck::{TestResult, quickcheck};
use rand::Rng;
use super::{integer_value, regex_value};
use expectest::prelude::*;
use pact_matching::s;
#[test]
fn validates_integer_value() {
fn prop(s: String) -> TestResult {
let mut rng = ::rand::thread_rng();
if rng.gen() && s.chars().any(|ch| !ch.is_numeric()) {
TestResult::discard()
} else {
let validation = integer_value(s.clone());
match validation {
Ok(_) => TestResult::from_bool(!s.is_empty() && s.chars().all(|ch| ch.is_numeric() )),
Err(_) => TestResult::from_bool(s.is_empty() || s.chars().find(|ch| !ch.is_numeric() ).is_some())
}
}
}
quickcheck(prop as fn(_) -> _);
expect!(integer_value(s!("1234"))).to(be_ok());
expect!(integer_value(s!("1234x"))).to(be_err());
}
#[test]
fn | () {
expect!(regex_value(s!("1234"))).to(be_ok());
expect!(regex_value(s!("["))).to(be_err());
}
| validates_regex_value | identifier_name |
test.rs | use quickcheck::{TestResult, quickcheck};
use rand::Rng;
use super::{integer_value, regex_value};
use expectest::prelude::*;
use pact_matching::s;
#[test]
fn validates_integer_value() {
fn prop(s: String) -> TestResult {
let mut rng = ::rand::thread_rng();
if rng.gen() && s.chars().any(|ch| !ch.is_numeric()) {
TestResult::discard()
} else {
let validation = integer_value(s.clone());
match validation {
Ok(_) => TestResult::from_bool(!s.is_empty() && s.chars().all(|ch| ch.is_numeric() )),
Err(_) => TestResult::from_bool(s.is_empty() || s.chars().find(|ch| !ch.is_numeric() ).is_some())
}
}
}
quickcheck(prop as fn(_) -> _);
expect!(integer_value(s!("1234"))).to(be_ok());
expect!(integer_value(s!("1234x"))).to(be_err());
}
#[test]
fn validates_regex_value() | {
expect!(regex_value(s!("1234"))).to(be_ok());
expect!(regex_value(s!("["))).to(be_err());
} | identifier_body | |
iterator.js | 'use strict';
var setPrototypeOf = require('es5-ext/object/set-prototype-of')
, d = require('d')
, Iterator = require('es6-iterator')
, toStringTagSymbol = require('es6-symbol').toStringTag
, kinds = require('./iterator-kinds')
, defineProperties = Object.defineProperties
, unBind = Iterator.prototype._unBind
, MapIterator;
MapIterator = module.exports = function (map, kind) {
if (!(this instanceof MapIterator)) return new MapIterator(map, kind);
Iterator.call(this, map.__mapKeysData__, map);
if (!kind || !kinds[kind]) kind = 'key+value';
defineProperties(this, {
__kind__: d('', kind),
| });
};
if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
MapIterator.prototype = Object.create(Iterator.prototype, {
constructor: d(MapIterator),
_resolve: d(function (i) {
if (this.__kind__ === 'value') return this.__values__[i];
if (this.__kind__ === 'key') return this.__list__[i];
return [this.__list__[i], this.__values__[i]];
}),
_unBind: d(function () {
this.__values__ = null;
unBind.call(this);
}),
toString: d(function () { return '[object Map Iterator]'; })
});
Object.defineProperty(MapIterator.prototype, toStringTagSymbol,
d('c', 'Map Iterator')); | __values__: d('w', map.__mapValuesData__)
| random_line_split |
binary_sensor.py | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
DEPENDENCIES = ['esphome']
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
|
class EsphomeBinarySensor(EsphomeEntity, BinarySensorDevice):
"""A binary sensor implementation for ESPHome."""
@property
def _static_info(self) -> 'BinarySensorInfo':
return super()._static_info
@property
def _state(self) -> Optional['BinarySensorState']:
return super()._state
@property
def is_on(self):
"""Return true if the binary sensor is on."""
if self._static_info.is_status_binary_sensor:
# Status binary sensors indicated connected state.
# So in their case what's usually _availability_ is now state
return self._entry_data.available
if self._state is None:
return None
return self._state.state
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._static_info.device_class
@property
def available(self):
"""Return True if entity is available."""
if self._static_info.is_status_binary_sensor:
return True
return super().available
| """Set up ESPHome binary sensors based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='binary_sensor',
info_type=BinarySensorInfo, entity_type=EsphomeBinarySensor,
state_type=BinarySensorState
) | identifier_body |
binary_sensor.py | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
DEPENDENCIES = ['esphome']
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up ESPHome binary sensors based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='binary_sensor',
info_type=BinarySensorInfo, entity_type=EsphomeBinarySensor,
state_type=BinarySensorState
)
class EsphomeBinarySensor(EsphomeEntity, BinarySensorDevice):
"""A binary sensor implementation for ESPHome."""
@property
def _static_info(self) -> 'BinarySensorInfo':
return super()._static_info
@property
def | (self) -> Optional['BinarySensorState']:
return super()._state
@property
def is_on(self):
"""Return true if the binary sensor is on."""
if self._static_info.is_status_binary_sensor:
# Status binary sensors indicated connected state.
# So in their case what's usually _availability_ is now state
return self._entry_data.available
if self._state is None:
return None
return self._state.state
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._static_info.device_class
@property
def available(self):
"""Return True if entity is available."""
if self._static_info.is_status_binary_sensor:
return True
return super().available
| _state | identifier_name |
binary_sensor.py | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
DEPENDENCIES = ['esphome']
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up ESPHome binary sensors based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='binary_sensor',
info_type=BinarySensorInfo, entity_type=EsphomeBinarySensor,
state_type=BinarySensorState
)
class EsphomeBinarySensor(EsphomeEntity, BinarySensorDevice):
"""A binary sensor implementation for ESPHome."""
@property
def _static_info(self) -> 'BinarySensorInfo':
return super()._static_info
@property
def _state(self) -> Optional['BinarySensorState']:
return super()._state
@property
def is_on(self):
"""Return true if the binary sensor is on."""
if self._static_info.is_status_binary_sensor:
# Status binary sensors indicated connected state.
# So in their case what's usually _availability_ is now state
|
if self._state is None:
return None
return self._state.state
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._static_info.device_class
@property
def available(self):
"""Return True if entity is available."""
if self._static_info.is_status_binary_sensor:
return True
return super().available
| return self._entry_data.available | conditional_block |
binary_sensor.py | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
DEPENDENCIES = ['esphome']
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up ESPHome binary sensors based on a config entry."""
# pylint: disable=redefined-outer-name
from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
await platform_async_setup_entry(
hass, entry, async_add_entities,
component_key='binary_sensor',
info_type=BinarySensorInfo, entity_type=EsphomeBinarySensor,
state_type=BinarySensorState
)
class EsphomeBinarySensor(EsphomeEntity, BinarySensorDevice):
"""A binary sensor implementation for ESPHome."""
@property
def _static_info(self) -> 'BinarySensorInfo':
return super()._static_info
@property
def _state(self) -> Optional['BinarySensorState']:
return super()._state
@property
def is_on(self):
"""Return true if the binary sensor is on."""
if self._static_info.is_status_binary_sensor:
# Status binary sensors indicated connected state.
# So in their case what's usually _availability_ is now state
return self._entry_data.available
if self._state is None:
return None
return self._state.state
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._static_info.device_class
@property
def available(self):
"""Return True if entity is available.""" | if self._static_info.is_status_binary_sensor:
return True
return super().available | random_line_split | |
purecss.js | /*******************************
Build Task
*******************************/
var
gulp = require('gulp'),
// node dependencies
console = require('better-console'),
fs = require('fs'),
// gulp dependencies
autoprefixer = require('gulp-autoprefixer'),
chmod = require('gulp-chmod'),
clone = require('gulp-clone'),
flatten = require('gulp-flatten'),
gulpif = require('gulp-if'),
less = require('gulp-less'),
plumber = require('gulp-plumber'),
print = require('gulp-print'),
rename = require('gulp-rename'),
replace = require('gulp-replace'),
runSequence = require('run-sequence'),
// config
config = require('../config/user'),
tasks = require('../config/tasks'),
install = require('../config/project/install'),
// shorthand
globs = config.globs,
assets = config.paths.assets,
output = config.paths.output,
source = config.paths.source,
banner = tasks.banner,
comments = tasks.regExp.comments,
log = tasks.log,
settings = tasks.settings
;
// add internal tasks (concat release)
require('../collections/internal')(gulp);
module.exports = function(callback) {
var
tasksCompleted = 0,
maybeCallback = function() {
tasksCompleted++;
if(tasksCompleted === 1) {
callback(); | ;
console.info('Building CSS');
if( !install.isSetup() ) {
console.error('Cannot build files. Run "gulp install" to set-up Semantic');
return;
}
// unified css stream
stream = gulp.src(source.definitions + '/**/' + globs.components + '.less')
.pipe(plumber(settings.plumber.less))
.pipe(less(settings.less))
.pipe(autoprefixer(settings.prefix))
.pipe(replace(comments.variables.in, comments.variables.out))
.pipe(replace(comments.license.in, comments.license.out))
.pipe(replace(comments.large.in, comments.large.out))
.pipe(replace(comments.small.in, comments.small.out))
.pipe(replace(comments.tiny.in, comments.tiny.out))
.pipe(flatten())
;
// two concurrent streams from same source to concat release
uncompressedStream = stream.pipe(clone());
// uncompressed component css
uncompressedStream
.pipe(plumber())
.pipe(replace(assets.source, assets.uncompressed))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(output.uncompressed))
.pipe(print(log.created))
.on('end', function() {
runSequence('package uncompressed css', maybeCallback);
})
;
}; | }
},
stream,
uncompressedStream | random_line_split |
purecss.js | /*******************************
Build Task
*******************************/
var
gulp = require('gulp'),
// node dependencies
console = require('better-console'),
fs = require('fs'),
// gulp dependencies
autoprefixer = require('gulp-autoprefixer'),
chmod = require('gulp-chmod'),
clone = require('gulp-clone'),
flatten = require('gulp-flatten'),
gulpif = require('gulp-if'),
less = require('gulp-less'),
plumber = require('gulp-plumber'),
print = require('gulp-print'),
rename = require('gulp-rename'),
replace = require('gulp-replace'),
runSequence = require('run-sequence'),
// config
config = require('../config/user'),
tasks = require('../config/tasks'),
install = require('../config/project/install'),
// shorthand
globs = config.globs,
assets = config.paths.assets,
output = config.paths.output,
source = config.paths.source,
banner = tasks.banner,
comments = tasks.regExp.comments,
log = tasks.log,
settings = tasks.settings
;
// add internal tasks (concat release)
require('../collections/internal')(gulp);
module.exports = function(callback) {
var
tasksCompleted = 0,
maybeCallback = function() {
tasksCompleted++;
if(tasksCompleted === 1) |
},
stream,
uncompressedStream
;
console.info('Building CSS');
if( !install.isSetup() ) {
console.error('Cannot build files. Run "gulp install" to set-up Semantic');
return;
}
// unified css stream
stream = gulp.src(source.definitions + '/**/' + globs.components + '.less')
.pipe(plumber(settings.plumber.less))
.pipe(less(settings.less))
.pipe(autoprefixer(settings.prefix))
.pipe(replace(comments.variables.in, comments.variables.out))
.pipe(replace(comments.license.in, comments.license.out))
.pipe(replace(comments.large.in, comments.large.out))
.pipe(replace(comments.small.in, comments.small.out))
.pipe(replace(comments.tiny.in, comments.tiny.out))
.pipe(flatten())
;
// two concurrent streams from same source to concat release
uncompressedStream = stream.pipe(clone());
// uncompressed component css
uncompressedStream
.pipe(plumber())
.pipe(replace(assets.source, assets.uncompressed))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(gulp.dest(output.uncompressed))
.pipe(print(log.created))
.on('end', function() {
runSequence('package uncompressed css', maybeCallback);
})
;
};
| {
callback();
} | conditional_block |
LinkToChefConfEditorPage.py | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
__author__ = "Antonio Hernández <ahernandez@emergya.com>"
__copyright__ = "Copyright (C) 2011, Junta de Andalucía <devmaster@guadalinex.org>"
__license__ = "GPL-2"
import LinkToChefHostnamePage
import LinkToChefResultsPage
import firstboot.pages.linkToChef
from firstboot_lib import PageWindow
from firstboot import serverconf
import firstboot.validation as validation
import gettext
from gettext import gettext as _
gettext.textdomain('firstboot')
__REQUIRED__ = False
__DEFAULT_ROLE__ = 'default_group'
def get_page(main_window):
page = LinkToChefConfEditorPage(main_window)
return page
class LinkToChefConfEditorPage(PageWindow.PageWindow):
__gtype_name__ = "LinkToChefConfEditorPage"
def finish_initializing(self):
self.update_server_conf = False
self.chef_is_configured = False
self.unlink_from_chef = False
def load_page(self, params=None):
if 'server_conf' in params:
self.server_conf = params['server_conf']
if not self.server_conf is None:
self.ui.lblVersionValue.set_label(self.server_conf.get_version())
self.ui.lblOrganizationValue.set_label(self.server_conf.get_organization())
self.ui.lblNotesValue.set_label(self.server_conf.get_notes())
self.ui.txtUrlChef.set_text(self.server_conf.get_chef_conf().get_url())
self.ui.txtUrlChefCert.set_text(self.server_conf.get_chef_conf().get_pem_url())
self.ui.txtHostname.set_text(self.server_conf.get_chef_conf().get_hostname())
self.ui.txtDefaultRole.set_text(self.server_conf.get_chef_conf().get_default_role())
if self.server_conf is None:
self.server_conf = serverconf.ServerConf()
if len(self.ui.txtDefaultRole.get_text()) == 0:
self.ui.txtDefaultRole.set_text(__DEFAULT_ROLE__)
self.update_server_conf = True
self.chef_is_configured = params['chef_is_configured']
self.unlink_from_chef = params['unlink_from_chef']
# if self.chef_is_configured and self.unlink_from_chef:
# self.ui.chkChef.get_child().set_markup(self._bold(_('This \
#workstation is going to be unlinked from the Chef server.')))
def _bold(self, str):
return '<b>%s</b>' % str
def translate(self):
desc = _('These parameters are required in order to join a Chef server:')
self.ui.lblDescription.set_text(desc)
self.ui.lblUrlChefDesc.set_label(_('"Chef URL": an existant URL in your server where Chef is installed.'))
self.ui.lblUrlChefCertDesc.set_label(_('"Chef Certificate": Validation certificate URL\
in order to autoregister this workstation in the Chef server.'))
self.ui.lblHostnameDesc.set_label(_('"Node Name": must be an unique name.'))
self.ui.lblDefaultRoleDesc.set_label(_('"Default Group": a global group for all the workstations in your organization.\nIf you are not an advanced Chef administrator, do not change this.'))
self.ui.lblVersion.set_label(_('Version'))
self.ui.lblOrganization.set_label(_('Organization'))
self.ui.lblNotes.set_label(_('Comments'))
self.ui.lblUrlChef.set_label('Chef URL')
self.ui.lblUrlChefCert.set_label(_('Certificate URL'))
self.ui.lblHostname.set_label(_('Node Name'))
self.ui.lblDefaultRole.set_label(_('Default Group'))
def previous_page(self, load_page_callback):
load_page_callback(firstboot.pages.linkToChef)
def next_page(self, load_page_callback):
if | def on_serverConf_changed(self, entry):
if not self.update_server_conf:
return
self.server_conf.get_chef_conf().set_url(self.ui.txtUrlChef.get_text())
self.server_conf.get_chef_conf().set_pem_url(self.ui.txtUrlChefCert.get_text())
self.server_conf.get_chef_conf().set_default_role(self.ui.txtDefaultRole.get_text())
self.server_conf.get_chef_conf().set_hostname(self.ui.txtHostname.get_text())
def validate_conf(self):
valid = True
messages = []
if not self.server_conf.get_chef_conf().validate():
valid = False
messages.append({'type': 'error', 'message': _('Chef and Chef Cert URLs must be valid URLs.')})
hostname = self.server_conf.get_chef_conf().get_hostname()
if not validation.is_qname(hostname):
valid = False
messages.append({'type': 'error', 'message': _('Node name is empty or contains invalid characters.')})
try:
used_hostnames = serverconf.get_chef_hostnames(self.server_conf.get_chef_conf())
except Exception as e:
used_hostnames = []
# IMPORTANT: Append the error but don't touch the variable "valid" here,
# just because if we can't get the hostnames here,
# Chef will inform us about that later, while we are registering
# the client.
messages.append({'type': 'error', 'message': str(e)})
if hostname in used_hostnames:
valid = False
messages.append({'type': 'error', 'message': _('Node name already exists in the Chef server. Choose a different one.')})
return valid, messages
| not self.unlink_from_chef:
result, messages = self.validate_conf()
if result == True:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_ldap=False,
unlink_ldap=False,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
load_page_callback(LinkToChefResultsPage, {
'server_conf': self.server_conf,
'result': result,
'messages': messages
})
else:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
load_page_callback(LinkToChefResultsPage, {
'result': result,
'server_conf': self.server_conf,
'messages': messages
})
| identifier_body |
LinkToChefConfEditorPage.py | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
__author__ = "Antonio Hernández <ahernandez@emergya.com>"
__copyright__ = "Copyright (C) 2011, Junta de Andalucía <devmaster@guadalinex.org>"
__license__ = "GPL-2"
import LinkToChefHostnamePage
import LinkToChefResultsPage
import firstboot.pages.linkToChef
from firstboot_lib import PageWindow
from firstboot import serverconf
import firstboot.validation as validation
import gettext
from gettext import gettext as _
gettext.textdomain('firstboot')
__REQUIRED__ = False
__DEFAULT_ROLE__ = 'default_group'
def get_page(main_window):
page = LinkToChefConfEditorPage(main_window)
return page
class LinkToChefConfEditorPage(PageWindow.PageWindow):
__gtype_name__ = "LinkToChefConfEditorPage"
def finish_initializing(self):
self.update_server_conf = False
self.chef_is_configured = False
self.unlink_from_chef = False
def load_page(self, params=None):
if 'server_conf' in params:
self.server_conf = params['server_conf']
if not self.server_conf is None:
self.ui.lblVersionValue.set_label(self.server_conf.get_version())
self.ui.lblOrganizationValue.set_label(self.server_conf.get_organization())
self.ui.lblNotesValue.set_label(self.server_conf.get_notes())
self.ui.txtUrlChef.set_text(self.server_conf.get_chef_conf().get_url())
self.ui.txtUrlChefCert.set_text(self.server_conf.get_chef_conf().get_pem_url())
self.ui.txtHostname.set_text(self.server_conf.get_chef_conf().get_hostname())
self.ui.txtDefaultRole.set_text(self.server_conf.get_chef_conf().get_default_role())
if self.server_conf is None:
self.server_conf = serverconf.ServerConf()
if len(self.ui.txtDefaultRole.get_text()) == 0:
self.ui.txtDefaultRole.set_text(__DEFAULT_ROLE__)
self.update_server_conf = True
self.chef_is_configured = params['chef_is_configured']
self.unlink_from_chef = params['unlink_from_chef']
# if self.chef_is_configured and self.unlink_from_chef:
# self.ui.chkChef.get_child().set_markup(self._bold(_('This \
#workstation is going to be unlinked from the Chef server.')))
def _bold(self, str):
return '<b>%s</b>' % str
def translate(self):
desc = _('These parameters are required in order to join a Chef server:')
self.ui.lblDescription.set_text(desc)
self.ui.lblUrlChefDesc.set_label(_('"Chef URL": an existant URL in your server where Chef is installed.'))
self.ui.lblUrlChefCertDesc.set_label(_('"Chef Certificate": Validation certificate URL\
in order to autoregister this workstation in the Chef server.'))
self.ui.lblHostnameDesc.set_label(_('"Node Name": must be an unique name.'))
self.ui.lblDefaultRoleDesc.set_label(_('"Default Group": a global group for all the workstations in your organization.\nIf you are not an advanced Chef administrator, do not change this.'))
self.ui.lblVersion.set_label(_('Version'))
self.ui.lblOrganization.set_label(_('Organization'))
self.ui.lblNotes.set_label(_('Comments'))
self.ui.lblUrlChef.set_label('Chef URL')
self.ui.lblUrlChefCert.set_label(_('Certificate URL')) | load_page_callback(firstboot.pages.linkToChef)
def next_page(self, load_page_callback):
if not self.unlink_from_chef:
result, messages = self.validate_conf()
if result == True:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_ldap=False,
unlink_ldap=False,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
load_page_callback(LinkToChefResultsPage, {
'server_conf': self.server_conf,
'result': result,
'messages': messages
})
else:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
load_page_callback(LinkToChefResultsPage, {
'result': result,
'server_conf': self.server_conf,
'messages': messages
})
def on_serverConf_changed(self, entry):
if not self.update_server_conf:
return
self.server_conf.get_chef_conf().set_url(self.ui.txtUrlChef.get_text())
self.server_conf.get_chef_conf().set_pem_url(self.ui.txtUrlChefCert.get_text())
self.server_conf.get_chef_conf().set_default_role(self.ui.txtDefaultRole.get_text())
self.server_conf.get_chef_conf().set_hostname(self.ui.txtHostname.get_text())
def validate_conf(self):
valid = True
messages = []
if not self.server_conf.get_chef_conf().validate():
valid = False
messages.append({'type': 'error', 'message': _('Chef and Chef Cert URLs must be valid URLs.')})
hostname = self.server_conf.get_chef_conf().get_hostname()
if not validation.is_qname(hostname):
valid = False
messages.append({'type': 'error', 'message': _('Node name is empty or contains invalid characters.')})
try:
used_hostnames = serverconf.get_chef_hostnames(self.server_conf.get_chef_conf())
except Exception as e:
used_hostnames = []
# IMPORTANT: Append the error but don't touch the variable "valid" here,
# just because if we can't get the hostnames here,
# Chef will inform us about that later, while we are registering
# the client.
messages.append({'type': 'error', 'message': str(e)})
if hostname in used_hostnames:
valid = False
messages.append({'type': 'error', 'message': _('Node name already exists in the Chef server. Choose a different one.')})
return valid, messages | self.ui.lblHostname.set_label(_('Node Name'))
self.ui.lblDefaultRole.set_label(_('Default Group'))
def previous_page(self, load_page_callback): | random_line_split |
LinkToChefConfEditorPage.py | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
__author__ = "Antonio Hernández <ahernandez@emergya.com>"
__copyright__ = "Copyright (C) 2011, Junta de Andalucía <devmaster@guadalinex.org>"
__license__ = "GPL-2"
import LinkToChefHostnamePage
import LinkToChefResultsPage
import firstboot.pages.linkToChef
from firstboot_lib import PageWindow
from firstboot import serverconf
import firstboot.validation as validation
import gettext
from gettext import gettext as _
gettext.textdomain('firstboot')
__REQUIRED__ = False
__DEFAULT_ROLE__ = 'default_group'
def get_page(main_window):
page = LinkToChefConfEditorPage(main_window)
return page
class LinkToChefConfEditorPage(PageWindow.PageWindow):
__gtype_name__ = "LinkToChefConfEditorPage"
def finish_initializing(self):
self.update_server_conf = False
self.chef_is_configured = False
self.unlink_from_chef = False
def load_page(self, params=None):
if 'server_conf' in params:
self.server_conf = params['server_conf']
if not self.server_conf is None:
self.ui.lblVersionValue.set_label(self.server_conf.get_version())
self.ui.lblOrganizationValue.set_label(self.server_conf.get_organization())
self.ui.lblNotesValue.set_label(self.server_conf.get_notes())
self.ui.txtUrlChef.set_text(self.server_conf.get_chef_conf().get_url())
self.ui.txtUrlChefCert.set_text(self.server_conf.get_chef_conf().get_pem_url())
self.ui.txtHostname.set_text(self.server_conf.get_chef_conf().get_hostname())
self.ui.txtDefaultRole.set_text(self.server_conf.get_chef_conf().get_default_role())
if self.server_conf is None:
self.server_conf = serverconf.ServerConf()
if len(self.ui.txtDefaultRole.get_text()) == 0:
self.ui.txtDefaultRole.set_text(__DEFAULT_ROLE__)
self.update_server_conf = True
self.chef_is_configured = params['chef_is_configured']
self.unlink_from_chef = params['unlink_from_chef']
# if self.chef_is_configured and self.unlink_from_chef:
# self.ui.chkChef.get_child().set_markup(self._bold(_('This \
#workstation is going to be unlinked from the Chef server.')))
def _bold(self, str):
return '<b>%s</b>' % str
def translate(self):
desc = _('These parameters are required in order to join a Chef server:')
self.ui.lblDescription.set_text(desc)
self.ui.lblUrlChefDesc.set_label(_('"Chef URL": an existant URL in your server where Chef is installed.'))
self.ui.lblUrlChefCertDesc.set_label(_('"Chef Certificate": Validation certificate URL\
in order to autoregister this workstation in the Chef server.'))
self.ui.lblHostnameDesc.set_label(_('"Node Name": must be an unique name.'))
self.ui.lblDefaultRoleDesc.set_label(_('"Default Group": a global group for all the workstations in your organization.\nIf you are not an advanced Chef administrator, do not change this.'))
self.ui.lblVersion.set_label(_('Version'))
self.ui.lblOrganization.set_label(_('Organization'))
self.ui.lblNotes.set_label(_('Comments'))
self.ui.lblUrlChef.set_label('Chef URL')
self.ui.lblUrlChefCert.set_label(_('Certificate URL'))
self.ui.lblHostname.set_label(_('Node Name'))
self.ui.lblDefaultRole.set_label(_('Default Group'))
def previous_page(self, load_page_callback):
load_page_callback(firstboot.pages.linkToChef)
def next_page(self, load_page_callback):
if not self.unlink_from_chef:
result, messages = self.validate_conf()
if result == True:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_ldap=False,
unlink_ldap=False,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
load_page_callback(LinkToChefResultsPage, {
'server_conf': self.server_conf,
'result': result,
'messages': messages
})
else:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
load_page_callback(LinkToChefResultsPage, {
'result': result,
'server_conf': self.server_conf,
'messages': messages
})
def on | elf, entry):
if not self.update_server_conf:
return
self.server_conf.get_chef_conf().set_url(self.ui.txtUrlChef.get_text())
self.server_conf.get_chef_conf().set_pem_url(self.ui.txtUrlChefCert.get_text())
self.server_conf.get_chef_conf().set_default_role(self.ui.txtDefaultRole.get_text())
self.server_conf.get_chef_conf().set_hostname(self.ui.txtHostname.get_text())
def validate_conf(self):
valid = True
messages = []
if not self.server_conf.get_chef_conf().validate():
valid = False
messages.append({'type': 'error', 'message': _('Chef and Chef Cert URLs must be valid URLs.')})
hostname = self.server_conf.get_chef_conf().get_hostname()
if not validation.is_qname(hostname):
valid = False
messages.append({'type': 'error', 'message': _('Node name is empty or contains invalid characters.')})
try:
used_hostnames = serverconf.get_chef_hostnames(self.server_conf.get_chef_conf())
except Exception as e:
used_hostnames = []
# IMPORTANT: Append the error but don't touch the variable "valid" here,
# just because if we can't get the hostnames here,
# Chef will inform us about that later, while we are registering
# the client.
messages.append({'type': 'error', 'message': str(e)})
if hostname in used_hostnames:
valid = False
messages.append({'type': 'error', 'message': _('Node name already exists in the Chef server. Choose a different one.')})
return valid, messages
| _serverConf_changed(s | identifier_name |
LinkToChefConfEditorPage.py | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# This file is part of Guadalinex
#
# This software is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
__author__ = "Antonio Hernández <ahernandez@emergya.com>"
__copyright__ = "Copyright (C) 2011, Junta de Andalucía <devmaster@guadalinex.org>"
__license__ = "GPL-2"
import LinkToChefHostnamePage
import LinkToChefResultsPage
import firstboot.pages.linkToChef
from firstboot_lib import PageWindow
from firstboot import serverconf
import firstboot.validation as validation
import gettext
from gettext import gettext as _
gettext.textdomain('firstboot')
__REQUIRED__ = False
__DEFAULT_ROLE__ = 'default_group'
def get_page(main_window):
page = LinkToChefConfEditorPage(main_window)
return page
class LinkToChefConfEditorPage(PageWindow.PageWindow):
__gtype_name__ = "LinkToChefConfEditorPage"
def finish_initializing(self):
self.update_server_conf = False
self.chef_is_configured = False
self.unlink_from_chef = False
def load_page(self, params=None):
if 'server_conf' in params:
self.server_conf = params['server_conf']
if not self.server_conf is None:
self.ui.lblVersionValue.set_label(self.server_conf.get_version())
self.ui.lblOrganizationValue.set_label(self.server_conf.get_organization())
self.ui.lblNotesValue.set_label(self.server_conf.get_notes())
self.ui.txtUrlChef.set_text(self.server_conf.get_chef_conf().get_url())
self.ui.txtUrlChefCert.set_text(self.server_conf.get_chef_conf().get_pem_url())
self.ui.txtHostname.set_text(self.server_conf.get_chef_conf().get_hostname())
self.ui.txtDefaultRole.set_text(self.server_conf.get_chef_conf().get_default_role())
if self.server_conf is None:
self.server_conf = serverconf.ServerConf()
if len(self.ui.txtDefaultRole.get_text()) == 0:
self.ui.txtDefaultRole.set_text(__DEFAULT_ROLE__)
self.update_server_conf = True
self.chef_is_configured = params['chef_is_configured']
self.unlink_from_chef = params['unlink_from_chef']
# if self.chef_is_configured and self.unlink_from_chef:
# self.ui.chkChef.get_child().set_markup(self._bold(_('This \
#workstation is going to be unlinked from the Chef server.')))
def _bold(self, str):
return '<b>%s</b>' % str
def translate(self):
desc = _('These parameters are required in order to join a Chef server:')
self.ui.lblDescription.set_text(desc)
self.ui.lblUrlChefDesc.set_label(_('"Chef URL": an existant URL in your server where Chef is installed.'))
self.ui.lblUrlChefCertDesc.set_label(_('"Chef Certificate": Validation certificate URL\
in order to autoregister this workstation in the Chef server.'))
self.ui.lblHostnameDesc.set_label(_('"Node Name": must be an unique name.'))
self.ui.lblDefaultRoleDesc.set_label(_('"Default Group": a global group for all the workstations in your organization.\nIf you are not an advanced Chef administrator, do not change this.'))
self.ui.lblVersion.set_label(_('Version'))
self.ui.lblOrganization.set_label(_('Organization'))
self.ui.lblNotes.set_label(_('Comments'))
self.ui.lblUrlChef.set_label('Chef URL')
self.ui.lblUrlChefCert.set_label(_('Certificate URL'))
self.ui.lblHostname.set_label(_('Node Name'))
self.ui.lblDefaultRole.set_label(_('Default Group'))
def previous_page(self, load_page_callback):
load_page_callback(firstboot.pages.linkToChef)
def next_page(self, load_page_callback):
if not self.unlink_from_chef:
result, messages = self.validate_conf()
if result == True:
re | load_page_callback(LinkToChefResultsPage, {
'server_conf': self.server_conf,
'result': result,
'messages': messages
})
else:
result, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
load_page_callback(LinkToChefResultsPage, {
'result': result,
'server_conf': self.server_conf,
'messages': messages
})
def on_serverConf_changed(self, entry):
if not self.update_server_conf:
return
self.server_conf.get_chef_conf().set_url(self.ui.txtUrlChef.get_text())
self.server_conf.get_chef_conf().set_pem_url(self.ui.txtUrlChefCert.get_text())
self.server_conf.get_chef_conf().set_default_role(self.ui.txtDefaultRole.get_text())
self.server_conf.get_chef_conf().set_hostname(self.ui.txtHostname.get_text())
def validate_conf(self):
valid = True
messages = []
if not self.server_conf.get_chef_conf().validate():
valid = False
messages.append({'type': 'error', 'message': _('Chef and Chef Cert URLs must be valid URLs.')})
hostname = self.server_conf.get_chef_conf().get_hostname()
if not validation.is_qname(hostname):
valid = False
messages.append({'type': 'error', 'message': _('Node name is empty or contains invalid characters.')})
try:
used_hostnames = serverconf.get_chef_hostnames(self.server_conf.get_chef_conf())
except Exception as e:
used_hostnames = []
# IMPORTANT: Append the error but don't touch the variable "valid" here,
# just because if we can't get the hostnames here,
# Chef will inform us about that later, while we are registering
# the client.
messages.append({'type': 'error', 'message': str(e)})
if hostname in used_hostnames:
valid = False
messages.append({'type': 'error', 'message': _('Node name already exists in the Chef server. Choose a different one.')})
return valid, messages
| sult, messages = serverconf.setup_server(
server_conf=self.server_conf,
link_ldap=False,
unlink_ldap=False,
link_chef=not self.unlink_from_chef,
unlink_chef=self.unlink_from_chef
)
| conditional_block |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Joel Grand-Guillaume. Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Account Constraints', | 'version': '1.1',
'depends': ['account'],
'author': 'Camptocamp',
'license': 'AGPL-3',
'category': 'Generic Modules/Accounting',
'description': """
Account Constraints
===================
Add constraints in the accounting module of OpenERP to avoid bad usage
by users that lead to corrupted datas. This is based on our experiences
and legal state of the art in other software.
Summary of constraints are:
* Add a constraint on account move: you cannot pickup a date that is not
in the fiscal year of the concerned period (configurable per journal)
* For manual entries when multicurrency:
a. Validation on the use of the 'Currency' and 'Currency Amount'
fields as it is possible to enter one without the other
b. Validation to prevent a Credit amount with a positive
'Currency Amount', or a Debit with a negative 'Currency Amount'
* Add a check on entries that user cannot provide a secondary currency
if the same than the company one.
* Remove the possibility to modify or delete a move line related to an
invoice or a bank statement, no matter what the status of the move
(draft, validated or posted). This is useful in a standard context but
even more if you're using `account_default_draft_move`. This way you ensure
that the user cannot make mistakes even in draft state, he must pass through
the parent object to make his modification.
Contributors
* Stéphane Bidoul <stephane.bidoul@acsone.eu>
""",
'website': 'http://www.camptocamp.com',
'data': [
'view/account_journal.xml',
'view/account_bank_statement.xml',
],
'installable': True,
} | random_line_split | |
tables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Analyze tracing data for edenscm
//!
//! This is edenscm application specific. It's not a general purposed library.
use serde_json::Value;
// use std::borrow::Cow;
use std::collections::BTreeMap as Map;
use tracing_collector::model::{IndexMap, TreeSpan, TreeSpans};
type Row = Map<String, Value>;
type Rows = Vec<Row>;
type Tables = Map<String, Rows>;
type TidSpans<'a> = IndexMap<(u64, u64), TreeSpans<&'a str>>;
// TODO: Make things more configurable.
/// Extract rows from tracing data. Output format is similar to NoSQL tables:
///
/// ```plain,ignore
/// {table_name: [{column_name: column_data}]}
/// ```
pub fn extract_tables(tid_spans: &TidSpans) -> Tables {
let mut tables = Map::new();
extract_dev_command_timers(&mut tables, tid_spans);
extract_other_tables(&mut tables, tid_spans);
tables
}
fn extract_dev_command_timers<'a>(tables: &mut Tables, tid_spans: &TidSpans) {
let mut row = Row::new();
let toint = |value: &str| -> Value { value.parse::<i64>().unwrap_or_default().into() };
for spans in tid_spans.values() {
for span in spans.walk() {
match span.meta.get("name").cloned().unwrap_or("") {
// By hgcommands, run.rs
"Run Command" => {
let duration = span.duration_millis().unwrap_or(0);
row.insert("command_duration".into(), duration.into());
row.insert("elapsed".into(), duration.into());
for (&name, &value) in span.meta.iter() {
match name {
"nice" => {
row.insert("nice".into(), toint(value));
}
"version" => {
// Truncate the "version" string. This matches the old telemetry behavior.
row.insert("version".into(), value[..34.min(value.len())].into());
}
"max_rss" => {
row.insert("maxrss".into(), toint(value));
}
"exit_code" => {
row.insert("errorcode".into(), toint(value));
}
"parent_names" => |
"args" => {
if let Ok(args) = serde_json::from_str::<Vec<String>>(value) {
// Normalize the first argument to "hg".
let mut full = "hg".to_string();
for arg in args.into_iter().skip(1) {
// Keep the length bounded.
if full.len() + arg.len() >= 256 {
full += " (truncated)";
break;
}
full += &" ";
// TODO: Use shell_escape once in tp2.
// full += &shell_escape::unix::escape(Cow::Owned(arg));
full += &arg;
}
row.insert("fullcommand".into(), full.into());
}
}
_ => {}
}
}
}
// The "log:command-row" event is used by code that wants to
// log to columns of the main command row easily.
"log:command-row" if span.is_event => {
extract_span(&span, &mut row);
}
_ => {}
}
}
}
tables.insert("dev_command_timers".into(), vec![row]);
}
fn extract_other_tables<'a>(tables: &mut Tables, tid_spans: &TidSpans) {
for spans in tid_spans.values() {
for span in spans.walk() {
match span.meta.get("name").cloned().unwrap_or("") {
// The "log:create-row" event is used by code that wants to log
// to a entire new column in a specified table.
//
// The event is expected to have "table", and the rest of the
// metadata will be logged as-is.
"log:create-row" => {
let table_name = match span.meta.get("table") {
Some(&name) => name,
None => continue,
};
let mut row = Row::new();
extract_span(span, &mut row);
tables.entry(table_name.into()).or_default().push(row);
}
_ => {}
}
}
}
}
/// Parse a span, extract its metadata to a row.
fn extract_span(span: &TreeSpan<&str>, row: &mut Row) {
for (&name, &value) in span.meta.iter() {
match name {
// Those keys are likely generated. Skip them.
"module_path" | "cat" | "line" | "name" => {}
// Attempt to convert it to an integer (since tracing data is
// string only).
_ => match value.parse::<i64>() {
Ok(i) => {
row.insert(name.into(), i.into());
}
_ => {
row.insert(name.into(), value.into());
}
},
}
}
}
| {
if let Ok(names) = serde_json::from_str::<Vec<String>>(value) {
let name = names.get(0).cloned().unwrap_or_default();
row.insert("parent".into(), name.into());
}
} | conditional_block |
tables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Analyze tracing data for edenscm
//!
//! This is edenscm application specific. It's not a general purposed library.
use serde_json::Value;
// use std::borrow::Cow;
use std::collections::BTreeMap as Map;
use tracing_collector::model::{IndexMap, TreeSpan, TreeSpans};
type Row = Map<String, Value>;
type Rows = Vec<Row>;
type Tables = Map<String, Rows>;
type TidSpans<'a> = IndexMap<(u64, u64), TreeSpans<&'a str>>;
// TODO: Make things more configurable.
/// Extract rows from tracing data. Output format is similar to NoSQL tables:
///
/// ```plain,ignore
/// {table_name: [{column_name: column_data}]}
/// ```
pub fn extract_tables(tid_spans: &TidSpans) -> Tables {
let mut tables = Map::new();
extract_dev_command_timers(&mut tables, tid_spans);
extract_other_tables(&mut tables, tid_spans);
tables
}
fn extract_dev_command_timers<'a>(tables: &mut Tables, tid_spans: &TidSpans) {
let mut row = Row::new();
let toint = |value: &str| -> Value { value.parse::<i64>().unwrap_or_default().into() };
for spans in tid_spans.values() {
for span in spans.walk() {
match span.meta.get("name").cloned().unwrap_or("") {
// By hgcommands, run.rs
"Run Command" => {
let duration = span.duration_millis().unwrap_or(0);
row.insert("command_duration".into(), duration.into());
row.insert("elapsed".into(), duration.into());
for (&name, &value) in span.meta.iter() {
match name {
"nice" => {
row.insert("nice".into(), toint(value));
}
"version" => {
// Truncate the "version" string. This matches the old telemetry behavior.
row.insert("version".into(), value[..34.min(value.len())].into());
}
"max_rss" => {
row.insert("maxrss".into(), toint(value));
}
"exit_code" => {
row.insert("errorcode".into(), toint(value));
}
"parent_names" => {
if let Ok(names) = serde_json::from_str::<Vec<String>>(value) {
let name = names.get(0).cloned().unwrap_or_default();
row.insert("parent".into(), name.into());
}
}
"args" => {
if let Ok(args) = serde_json::from_str::<Vec<String>>(value) {
// Normalize the first argument to "hg".
let mut full = "hg".to_string();
for arg in args.into_iter().skip(1) {
// Keep the length bounded.
if full.len() + arg.len() >= 256 {
full += " (truncated)";
break;
}
full += &" ";
// TODO: Use shell_escape once in tp2.
// full += &shell_escape::unix::escape(Cow::Owned(arg));
full += &arg;
}
row.insert("fullcommand".into(), full.into());
}
}
_ => {}
}
}
}
// The "log:command-row" event is used by code that wants to
// log to columns of the main command row easily.
"log:command-row" if span.is_event => {
extract_span(&span, &mut row);
}
_ => {}
}
}
}
tables.insert("dev_command_timers".into(), vec![row]);
}
fn extract_other_tables<'a>(tables: &mut Tables, tid_spans: &TidSpans) {
for spans in tid_spans.values() {
for span in spans.walk() {
match span.meta.get("name").cloned().unwrap_or("") {
// The "log:create-row" event is used by code that wants to log
// to a entire new column in a specified table.
//
// The event is expected to have "table", and the rest of the
// metadata will be logged as-is.
"log:create-row" => {
let table_name = match span.meta.get("table") {
Some(&name) => name,
None => continue,
};
let mut row = Row::new();
extract_span(span, &mut row);
tables.entry(table_name.into()).or_default().push(row);
}
_ => {}
}
}
}
}
/// Parse a span, extract its metadata to a row.
fn | (span: &TreeSpan<&str>, row: &mut Row) {
for (&name, &value) in span.meta.iter() {
match name {
// Those keys are likely generated. Skip them.
"module_path" | "cat" | "line" | "name" => {}
// Attempt to convert it to an integer (since tracing data is
// string only).
_ => match value.parse::<i64>() {
Ok(i) => {
row.insert(name.into(), i.into());
}
_ => {
row.insert(name.into(), value.into());
}
},
}
}
}
| extract_span | identifier_name |
tables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Analyze tracing data for edenscm
//!
//! This is edenscm application specific. It's not a general purposed library.
use serde_json::Value;
// use std::borrow::Cow;
use std::collections::BTreeMap as Map;
use tracing_collector::model::{IndexMap, TreeSpan, TreeSpans};
type Row = Map<String, Value>;
type Rows = Vec<Row>;
type Tables = Map<String, Rows>;
type TidSpans<'a> = IndexMap<(u64, u64), TreeSpans<&'a str>>;
// TODO: Make things more configurable.
/// Extract rows from tracing data. Output format is similar to NoSQL tables:
///
/// ```plain,ignore
/// {table_name: [{column_name: column_data}]}
/// ```
pub fn extract_tables(tid_spans: &TidSpans) -> Tables {
let mut tables = Map::new();
extract_dev_command_timers(&mut tables, tid_spans);
extract_other_tables(&mut tables, tid_spans);
tables
}
fn extract_dev_command_timers<'a>(tables: &mut Tables, tid_spans: &TidSpans) {
let mut row = Row::new();
let toint = |value: &str| -> Value { value.parse::<i64>().unwrap_or_default().into() };
for spans in tid_spans.values() {
for span in spans.walk() {
match span.meta.get("name").cloned().unwrap_or("") {
// By hgcommands, run.rs
"Run Command" => {
let duration = span.duration_millis().unwrap_or(0);
row.insert("command_duration".into(), duration.into());
row.insert("elapsed".into(), duration.into());
for (&name, &value) in span.meta.iter() {
match name {
"nice" => {
row.insert("nice".into(), toint(value));
}
"version" => {
// Truncate the "version" string. This matches the old telemetry behavior.
row.insert("version".into(), value[..34.min(value.len())].into());
}
"max_rss" => {
row.insert("maxrss".into(), toint(value));
}
"exit_code" => {
row.insert("errorcode".into(), toint(value));
}
"parent_names" => {
if let Ok(names) = serde_json::from_str::<Vec<String>>(value) {
let name = names.get(0).cloned().unwrap_or_default();
row.insert("parent".into(), name.into());
}
}
"args" => {
if let Ok(args) = serde_json::from_str::<Vec<String>>(value) {
// Normalize the first argument to "hg".
let mut full = "hg".to_string();
for arg in args.into_iter().skip(1) {
// Keep the length bounded.
if full.len() + arg.len() >= 256 {
full += " (truncated)";
break;
}
full += &" ";
// TODO: Use shell_escape once in tp2.
// full += &shell_escape::unix::escape(Cow::Owned(arg));
full += &arg;
}
row.insert("fullcommand".into(), full.into());
}
}
_ => {}
}
}
}
// The "log:command-row" event is used by code that wants to
// log to columns of the main command row easily.
"log:command-row" if span.is_event => {
extract_span(&span, &mut row);
}
_ => {}
}
}
}
tables.insert("dev_command_timers".into(), vec![row]);
}
fn extract_other_tables<'a>(tables: &mut Tables, tid_spans: &TidSpans) {
for spans in tid_spans.values() {
for span in spans.walk() {
match span.meta.get("name").cloned().unwrap_or("") {
// The "log:create-row" event is used by code that wants to log
// to a entire new column in a specified table.
//
// The event is expected to have "table", and the rest of the
// metadata will be logged as-is.
"log:create-row" => {
let table_name = match span.meta.get("table") {
Some(&name) => name,
None => continue,
};
let mut row = Row::new();
extract_span(span, &mut row);
tables.entry(table_name.into()).or_default().push(row);
}
_ => {}
}
}
}
}
/// Parse a span, extract its metadata to a row.
fn extract_span(span: &TreeSpan<&str>, row: &mut Row) | {
for (&name, &value) in span.meta.iter() {
match name {
// Those keys are likely generated. Skip them.
"module_path" | "cat" | "line" | "name" => {}
// Attempt to convert it to an integer (since tracing data is
// string only).
_ => match value.parse::<i64>() {
Ok(i) => {
row.insert(name.into(), i.into());
}
_ => {
row.insert(name.into(), value.into());
}
},
}
}
} | identifier_body | |
tables.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Analyze tracing data for edenscm
//!
//! This is edenscm application specific. It's not a general purposed library.
use serde_json::Value;
// use std::borrow::Cow;
use std::collections::BTreeMap as Map;
use tracing_collector::model::{IndexMap, TreeSpan, TreeSpans};
type Row = Map<String, Value>;
type Rows = Vec<Row>;
type Tables = Map<String, Rows>;
type TidSpans<'a> = IndexMap<(u64, u64), TreeSpans<&'a str>>;
// TODO: Make things more configurable.
/// Extract rows from tracing data. Output format is similar to NoSQL tables:
///
/// ```plain,ignore
/// {table_name: [{column_name: column_data}]}
/// ```
pub fn extract_tables(tid_spans: &TidSpans) -> Tables {
let mut tables = Map::new();
extract_dev_command_timers(&mut tables, tid_spans);
extract_other_tables(&mut tables, tid_spans);
tables
}
fn extract_dev_command_timers<'a>(tables: &mut Tables, tid_spans: &TidSpans) {
let mut row = Row::new();
let toint = |value: &str| -> Value { value.parse::<i64>().unwrap_or_default().into() };
for spans in tid_spans.values() {
for span in spans.walk() {
match span.meta.get("name").cloned().unwrap_or("") {
// By hgcommands, run.rs
"Run Command" => {
let duration = span.duration_millis().unwrap_or(0);
row.insert("command_duration".into(), duration.into());
row.insert("elapsed".into(), duration.into());
for (&name, &value) in span.meta.iter() {
match name {
"nice" => {
row.insert("nice".into(), toint(value));
}
"version" => {
// Truncate the "version" string. This matches the old telemetry behavior.
row.insert("version".into(), value[..34.min(value.len())].into());
}
"max_rss" => {
row.insert("maxrss".into(), toint(value));
}
"exit_code" => {
row.insert("errorcode".into(), toint(value));
}
"parent_names" => {
if let Ok(names) = serde_json::from_str::<Vec<String>>(value) {
let name = names.get(0).cloned().unwrap_or_default();
row.insert("parent".into(), name.into());
}
}
"args" => {
if let Ok(args) = serde_json::from_str::<Vec<String>>(value) {
// Normalize the first argument to "hg".
let mut full = "hg".to_string();
for arg in args.into_iter().skip(1) {
// Keep the length bounded.
if full.len() + arg.len() >= 256 {
full += " (truncated)";
break;
}
full += &" ";
// TODO: Use shell_escape once in tp2.
// full += &shell_escape::unix::escape(Cow::Owned(arg));
full += &arg;
}
row.insert("fullcommand".into(), full.into()); | }
_ => {}
}
}
}
// The "log:command-row" event is used by code that wants to
// log to columns of the main command row easily.
"log:command-row" if span.is_event => {
extract_span(&span, &mut row);
}
_ => {}
}
}
}
tables.insert("dev_command_timers".into(), vec![row]);
}
fn extract_other_tables<'a>(tables: &mut Tables, tid_spans: &TidSpans) {
for spans in tid_spans.values() {
for span in spans.walk() {
match span.meta.get("name").cloned().unwrap_or("") {
// The "log:create-row" event is used by code that wants to log
// to a entire new column in a specified table.
//
// The event is expected to have "table", and the rest of the
// metadata will be logged as-is.
"log:create-row" => {
let table_name = match span.meta.get("table") {
Some(&name) => name,
None => continue,
};
let mut row = Row::new();
extract_span(span, &mut row);
tables.entry(table_name.into()).or_default().push(row);
}
_ => {}
}
}
}
}
/// Parse a span, extract its metadata to a row.
fn extract_span(span: &TreeSpan<&str>, row: &mut Row) {
for (&name, &value) in span.meta.iter() {
match name {
// Those keys are likely generated. Skip them.
"module_path" | "cat" | "line" | "name" => {}
// Attempt to convert it to an integer (since tracing data is
// string only).
_ => match value.parse::<i64>() {
Ok(i) => {
row.insert(name.into(), i.into());
}
_ => {
row.insert(name.into(), value.into());
}
},
}
}
} | } | random_line_split |
lib.rs | #![crate_name = "graphics"]
#![deny(missing_docs)]
#![deny(missing_copy_implementations)]
//! A library for 2D graphics that works with multiple back-ends.
//!
//! Piston-Graphics was started in 2014 by Sven Nilsen to test
//! back-end agnostic design for 2D in Rust.
//! This means generic code can be reused across projects and platforms.
//!
//! ### Design
//!
//! A graphics back-end implements the `Graphics` trait.
//!
//! This library uses immediate design for flexibility.
//! By default, triangles are generated from 2D shapes and passed in chunks
//! to the back-end. This behavior can be overridden by a back-end library.
//!
//! The structures used for drawing 2D shapes contains settings for rendering.
//! The separation of shapes and settings allows more reuse and flexibility.
//! For example, to render an image, you use an `Image` object.
//!
//! The `math` module contains useful methods for 2D geometry.
//!
//! `Context` stores settings that are commonly shared when rendering.
//! It can be copied and changed without affecting any global state.
//!
//! At top level, there are some shortcut methods for common operations.
//! For example, `ellipse` is a simplified version of `Ellipse`.
extern crate vecmath;
extern crate texture;
extern crate read_color;
extern crate interpolation;
extern crate viewport;
pub use texture::ImageSize;
pub use viewport::Viewport;
pub use graphics::Graphics;
pub use source_rectangled::SourceRectangled;
pub use rectangled::Rectangled;
pub use transformed::Transformed;
pub use colored::Colored;
pub use rectangle::Rectangle;
pub use line::Line;
pub use ellipse::Ellipse;
pub use circle_arc::CircleArc;
pub use image::Image;
pub use polygon::Polygon;
pub use text::Text;
pub use context::Context;
pub use draw_state::DrawState;
/// Any triangulation method called on the back-end
/// never exceeds this number of vertices.
/// This can be used to initialize buffers that fit the chunk size.
pub static BACK_END_MAX_VERTEX_COUNT: usize = 1024;
mod graphics;
mod source_rectangled;
mod rectangled;
mod transformed;
mod colored;
pub mod draw_state;
pub mod character;
pub mod context;
pub mod color;
pub mod polygon;
pub mod line;
pub mod circle_arc;
pub mod ellipse;
pub mod rectangle;
pub mod image;
pub mod types;
pub mod modular_index;
pub mod text;
pub mod triangulation;
pub mod math;
pub mod deform;
pub mod grid;
pub mod radians {
//! Reexport radians helper trait from vecmath
pub use vecmath::traits::Radians;
}
/// Clears the screen.
pub fn clear<G>(
color: types::Color, g: &mut G
)
where G: Graphics
{
g.clear_color(color);
g.clear_stencil(0);
}
/// Draws image.
pub fn | <G>(
image: &<G as Graphics>::Texture,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Image::new().draw(image, &Default::default(), transform, g);
}
/// Draws ellipse.
pub fn ellipse<R: Into<types::Rectangle>, G>(
color: types::Color,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Ellipse::new(color).draw(rect, &Default::default(), transform, g);
}
/// Draws arc
pub fn circle_arc<R: Into<types::Rectangle>, G>(
color: types::Color,
radius: types::Radius,
start: types::Scalar,
end: types::Scalar,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
CircleArc::new(color, radius, start, end)
.draw(rect, &Default::default(), transform, g);
}
/// Draws rectangle.
pub fn rectangle<R: Into<types::Rectangle>, G>(
color: types::Color,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Rectangle::new(color).draw(rect, &Default::default(), transform, g);
}
/// Draws polygon.
pub fn polygon<G>(
color: types::Color,
polygon: types::Polygon,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Polygon::new(color).draw(polygon, &Default::default(), transform, g);
}
/// Draws line.
pub fn line<L: Into<types::Line>, G>(
color: types::Color,
radius: types::Radius,
line: L,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Line::new(color, radius).draw(line, &Default::default(), transform, g)
}
/// Draws text.
pub fn text<C, G>(
color: types::Color,
font_size: types::FontSize,
text: &str,
cache: &mut C,
transform: math::Matrix2d,
g: &mut G
)
where
C: character::CharacterCache,
G: Graphics<Texture = <C as character::CharacterCache>::Texture>
{
Text::new_color(color, font_size)
.draw(text, cache, &Default::default(), transform, g)
}
| image | identifier_name |
lib.rs | #![crate_name = "graphics"]
#![deny(missing_docs)]
#![deny(missing_copy_implementations)]
//! A library for 2D graphics that works with multiple back-ends.
//!
//! Piston-Graphics was started in 2014 by Sven Nilsen to test
//! back-end agnostic design for 2D in Rust.
//! This means generic code can be reused across projects and platforms.
//!
//! ### Design
//!
//! A graphics back-end implements the `Graphics` trait.
//!
//! This library uses immediate design for flexibility.
//! By default, triangles are generated from 2D shapes and passed in chunks
//! to the back-end. This behavior can be overridden by a back-end library.
//!
//! The structures used for drawing 2D shapes contains settings for rendering.
//! The separation of shapes and settings allows more reuse and flexibility.
//! For example, to render an image, you use an `Image` object.
//!
//! The `math` module contains useful methods for 2D geometry.
//!
//! `Context` stores settings that are commonly shared when rendering.
//! It can be copied and changed without affecting any global state.
//!
//! At top level, there are some shortcut methods for common operations.
//! For example, `ellipse` is a simplified version of `Ellipse`.
extern crate vecmath;
extern crate texture;
extern crate read_color;
extern crate interpolation;
extern crate viewport;
pub use texture::ImageSize;
pub use viewport::Viewport;
pub use graphics::Graphics;
pub use source_rectangled::SourceRectangled;
pub use rectangled::Rectangled;
pub use transformed::Transformed;
pub use colored::Colored;
pub use rectangle::Rectangle;
pub use line::Line;
pub use ellipse::Ellipse;
pub use circle_arc::CircleArc;
pub use image::Image;
pub use polygon::Polygon;
pub use text::Text;
pub use context::Context;
pub use draw_state::DrawState;
/// Any triangulation method called on the back-end
/// never exceeds this number of vertices.
/// This can be used to initialize buffers that fit the chunk size.
pub static BACK_END_MAX_VERTEX_COUNT: usize = 1024;
mod graphics;
mod source_rectangled;
mod rectangled;
mod transformed;
mod colored;
pub mod draw_state;
pub mod character;
pub mod context;
pub mod color;
pub mod polygon;
pub mod line;
pub mod circle_arc;
pub mod ellipse;
pub mod rectangle;
pub mod image;
pub mod types;
pub mod modular_index;
pub mod text;
pub mod triangulation;
pub mod math;
pub mod deform;
pub mod grid;
pub mod radians {
//! Reexport radians helper trait from vecmath
pub use vecmath::traits::Radians;
}
/// Clears the screen.
pub fn clear<G>(
color: types::Color, g: &mut G
)
where G: Graphics
{
g.clear_color(color);
g.clear_stencil(0);
}
/// Draws image.
pub fn image<G>(
image: &<G as Graphics>::Texture,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Image::new().draw(image, &Default::default(), transform, g);
}
/// Draws ellipse.
pub fn ellipse<R: Into<types::Rectangle>, G>(
color: types::Color,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Ellipse::new(color).draw(rect, &Default::default(), transform, g);
}
/// Draws arc
pub fn circle_arc<R: Into<types::Rectangle>, G>(
color: types::Color,
radius: types::Radius,
start: types::Scalar,
end: types::Scalar,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
CircleArc::new(color, radius, start, end)
.draw(rect, &Default::default(), transform, g);
}
/// Draws rectangle.
pub fn rectangle<R: Into<types::Rectangle>, G>(
color: types::Color,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Rectangle::new(color).draw(rect, &Default::default(), transform, g);
}
/// Draws polygon.
pub fn polygon<G>(
color: types::Color,
polygon: types::Polygon,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Polygon::new(color).draw(polygon, &Default::default(), transform, g);
}
/// Draws line.
pub fn line<L: Into<types::Line>, G>(
color: types::Color,
radius: types::Radius,
line: L,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Line::new(color, radius).draw(line, &Default::default(), transform, g)
}
/// Draws text.
pub fn text<C, G>(
color: types::Color,
font_size: types::FontSize,
text: &str,
cache: &mut C,
transform: math::Matrix2d,
g: &mut G
)
where
C: character::CharacterCache,
G: Graphics<Texture = <C as character::CharacterCache>::Texture>
| {
Text::new_color(color, font_size)
.draw(text, cache, &Default::default(), transform, g)
} | identifier_body | |
lib.rs | #![crate_name = "graphics"]
#![deny(missing_docs)]
#![deny(missing_copy_implementations)]
//! A library for 2D graphics that works with multiple back-ends.
//!
//! Piston-Graphics was started in 2014 by Sven Nilsen to test
//! back-end agnostic design for 2D in Rust.
//! This means generic code can be reused across projects and platforms.
//!
//! ### Design
//!
//! A graphics back-end implements the `Graphics` trait.
//!
//! This library uses immediate design for flexibility.
//! By default, triangles are generated from 2D shapes and passed in chunks
//! to the back-end. This behavior can be overridden by a back-end library.
//!
//! The structures used for drawing 2D shapes contains settings for rendering.
//! The separation of shapes and settings allows more reuse and flexibility.
//! For example, to render an image, you use an `Image` object.
//!
//! The `math` module contains useful methods for 2D geometry.
//!
//! `Context` stores settings that are commonly shared when rendering.
//! It can be copied and changed without affecting any global state.
//!
//! At top level, there are some shortcut methods for common operations.
//! For example, `ellipse` is a simplified version of `Ellipse`.
extern crate vecmath;
extern crate texture;
extern crate read_color;
extern crate interpolation;
extern crate viewport;
pub use texture::ImageSize;
pub use viewport::Viewport;
pub use graphics::Graphics;
pub use source_rectangled::SourceRectangled;
pub use rectangled::Rectangled;
pub use transformed::Transformed;
pub use colored::Colored;
pub use rectangle::Rectangle;
pub use line::Line;
pub use ellipse::Ellipse;
pub use circle_arc::CircleArc;
pub use image::Image;
pub use polygon::Polygon;
pub use text::Text;
pub use context::Context;
pub use draw_state::DrawState;
/// Any triangulation method called on the back-end
/// never exceeds this number of vertices.
/// This can be used to initialize buffers that fit the chunk size.
pub static BACK_END_MAX_VERTEX_COUNT: usize = 1024;
mod graphics;
mod source_rectangled;
mod rectangled;
mod transformed;
mod colored;
pub mod draw_state;
pub mod character;
pub mod context;
pub mod color;
pub mod polygon;
pub mod line;
pub mod circle_arc;
pub mod ellipse;
pub mod rectangle; | pub mod text;
pub mod triangulation;
pub mod math;
pub mod deform;
pub mod grid;
pub mod radians {
//! Reexport radians helper trait from vecmath
pub use vecmath::traits::Radians;
}
/// Clears the screen.
pub fn clear<G>(
color: types::Color, g: &mut G
)
where G: Graphics
{
g.clear_color(color);
g.clear_stencil(0);
}
/// Draws image.
pub fn image<G>(
image: &<G as Graphics>::Texture,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Image::new().draw(image, &Default::default(), transform, g);
}
/// Draws ellipse.
pub fn ellipse<R: Into<types::Rectangle>, G>(
color: types::Color,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Ellipse::new(color).draw(rect, &Default::default(), transform, g);
}
/// Draws arc
pub fn circle_arc<R: Into<types::Rectangle>, G>(
color: types::Color,
radius: types::Radius,
start: types::Scalar,
end: types::Scalar,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
CircleArc::new(color, radius, start, end)
.draw(rect, &Default::default(), transform, g);
}
/// Draws rectangle.
pub fn rectangle<R: Into<types::Rectangle>, G>(
color: types::Color,
rect: R,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Rectangle::new(color).draw(rect, &Default::default(), transform, g);
}
/// Draws polygon.
pub fn polygon<G>(
color: types::Color,
polygon: types::Polygon,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Polygon::new(color).draw(polygon, &Default::default(), transform, g);
}
/// Draws line.
pub fn line<L: Into<types::Line>, G>(
color: types::Color,
radius: types::Radius,
line: L,
transform: math::Matrix2d,
g: &mut G
)
where G: Graphics
{
Line::new(color, radius).draw(line, &Default::default(), transform, g)
}
/// Draws text.
pub fn text<C, G>(
color: types::Color,
font_size: types::FontSize,
text: &str,
cache: &mut C,
transform: math::Matrix2d,
g: &mut G
)
where
C: character::CharacterCache,
G: Graphics<Texture = <C as character::CharacterCache>::Texture>
{
Text::new_color(color, font_size)
.draw(text, cache, &Default::default(), transform, g)
} | pub mod image;
pub mod types;
pub mod modular_index; | random_line_split |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CError, Result as CResult};
use authenticators::Authenticator;
use compression::Compression;
use r2d2;
use transport::CDRSTransport;
use rand;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Load balancing strategy
#[derive(PartialEq)]
pub enum LoadBalancingStrategy {
/// Round Robin balancing strategy
RoundRobin,
/// Random balancing strategy
Random,
}
impl LoadBalancingStrategy {
/// Returns next value for selected load balancing strategy
pub fn next<'a, N>(&'a self, nodes: &'a Vec<N>, i: usize) -> Option<&N> {
match *self {
LoadBalancingStrategy::Random => nodes.get(self.rnd_idx((0, Some(nodes.len())))),
LoadBalancingStrategy::RoundRobin => {
let mut cycle = nodes.iter().cycle().skip(i);
cycle.next()
}
}
}
/// Returns random number from a range
fn rnd_idx(&self, bounds: (usize, Option<usize>)) -> usize {
let min = bounds.0;
let max = bounds.1.unwrap_or(u8::max_value() as usize);
let rnd = rand::random::<usize>();
rnd % (max - min) + min
}
}
/// Load balancer
///
/// #Example
///
/// ```no_run
/// use cdrs::cluster::{LoadBalancingStrategy, LoadBalancer};
/// use cdrs::transport::TransportTcp;
/// let transports = vec![TransportTcp::new("127.0.0.1:9042"), TransportTcp::new("127.0.0.1:9042")];
/// let load_balancer = LoadBalancer::new(transports, LoadBalancingStrategy::RoundRobin);
/// let node = load_balancer.next().unwrap();
/// ```
pub struct LoadBalancer<T> {
strategy: LoadBalancingStrategy,
nodes: Vec<T>,
i: AtomicUsize,
}
impl<T> LoadBalancer<T> {
/// Factory function which creates new `LoadBalancer` with provided strategy.
pub fn new(nodes: Vec<T>, strategy: LoadBalancingStrategy) -> LoadBalancer<T> {
LoadBalancer {
nodes: nodes,
strategy: strategy,
i: AtomicUsize::new(0),
}
}
/// Returns next node basing on provided strategy.
pub fn next(&self) -> Option<&T> {
let next = self.strategy
.next(&self.nodes, self.i.load(Ordering::Relaxed) as usize);
if self.strategy == LoadBalancingStrategy::RoundRobin {
self.i.fetch_add(1, Ordering::Relaxed);
// prevent overflow
let i = self.i.load(Ordering::Relaxed);
match i.checked_rem(self.nodes.len() as usize) {
Some(rem) => self.i.store(rem, Ordering::Relaxed),
None => return None,
}
}
next
}
}
/// [r2d2](https://github.com/sfackler/r2d2) `ManageConnection`.
pub struct ClusterConnectionManager<T, X> {
load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression,
}
impl<T, X> ClusterConnectionManager<T, X>
where T: Authenticator + Send + Sync + 'static
{
/// Creates a new instance of `ConnectionManager`.
/// It requires transport, authenticator and compression as inputs.
pub fn new(load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression)
-> ClusterConnectionManager<T, X> {
ClusterConnectionManager {
load_balancer: load_balancer,
authenticator: authenticator,
compression: compression,
}
}
}
impl<T: Authenticator + Send + Sync + 'static,
X: CDRSTransport + Send + Sync + 'static> r2d2::ManageConnection
for ClusterConnectionManager<T, X> {
type Connection = Session<T, X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CResult<X> = self.load_balancer
.next()
.ok_or_else(|| "Cannot get next node".into())
.and_then(|x| x.try_clone().map_err(|e| e.into()));
let transport = try!(transport_res);
let compression = self.compression;
let cdrs = CDRS::new(transport, self.authenticator.clone());
cdrs.start(compression)
}
fn | (&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();
connection.query(query, false, false).map(|_| ())
}
fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_robin() {
let nodes = vec!["a", "b", "c"];
let nodes_c = nodes.clone();
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::RoundRobin);
for i in 0..10 {
assert_eq!(&nodes_c[i % 3], load_balancer.next().unwrap());
}
}
#[test]
fn lb_random() {
let nodes = vec!["a", "b", "c", "d", "e", "f", "g"];
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::Random);
for _ in 0..100 {
let s = load_balancer.next();
assert!(s.is_some());
}
}
}
| is_valid | identifier_name |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CError, Result as CResult};
use authenticators::Authenticator;
use compression::Compression;
use r2d2;
use transport::CDRSTransport;
use rand;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Load balancing strategy
#[derive(PartialEq)]
pub enum LoadBalancingStrategy {
/// Round Robin balancing strategy
RoundRobin,
/// Random balancing strategy
Random,
}
impl LoadBalancingStrategy {
/// Returns next value for selected load balancing strategy
pub fn next<'a, N>(&'a self, nodes: &'a Vec<N>, i: usize) -> Option<&N> {
match *self {
LoadBalancingStrategy::Random => nodes.get(self.rnd_idx((0, Some(nodes.len())))),
LoadBalancingStrategy::RoundRobin => {
let mut cycle = nodes.iter().cycle().skip(i);
cycle.next()
}
}
}
/// Returns random number from a range
fn rnd_idx(&self, bounds: (usize, Option<usize>)) -> usize {
let min = bounds.0;
let max = bounds.1.unwrap_or(u8::max_value() as usize);
let rnd = rand::random::<usize>();
rnd % (max - min) + min
}
}
/// Load balancer
///
/// #Example
///
/// ```no_run
/// use cdrs::cluster::{LoadBalancingStrategy, LoadBalancer};
/// use cdrs::transport::TransportTcp;
/// let transports = vec![TransportTcp::new("127.0.0.1:9042"), TransportTcp::new("127.0.0.1:9042")];
/// let load_balancer = LoadBalancer::new(transports, LoadBalancingStrategy::RoundRobin);
/// let node = load_balancer.next().unwrap();
/// ```
pub struct LoadBalancer<T> {
strategy: LoadBalancingStrategy,
nodes: Vec<T>,
i: AtomicUsize,
}
impl<T> LoadBalancer<T> {
/// Factory function which creates new `LoadBalancer` with provided strategy.
pub fn new(nodes: Vec<T>, strategy: LoadBalancingStrategy) -> LoadBalancer<T> {
LoadBalancer {
nodes: nodes,
strategy: strategy,
i: AtomicUsize::new(0),
}
}
/// Returns next node basing on provided strategy.
pub fn next(&self) -> Option<&T> {
let next = self.strategy
.next(&self.nodes, self.i.load(Ordering::Relaxed) as usize);
if self.strategy == LoadBalancingStrategy::RoundRobin {
self.i.fetch_add(1, Ordering::Relaxed);
// prevent overflow
let i = self.i.load(Ordering::Relaxed);
match i.checked_rem(self.nodes.len() as usize) {
Some(rem) => self.i.store(rem, Ordering::Relaxed),
None => return None,
}
}
next
}
}
/// [r2d2](https://github.com/sfackler/r2d2) `ManageConnection`.
pub struct ClusterConnectionManager<T, X> {
load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression,
}
impl<T, X> ClusterConnectionManager<T, X>
where T: Authenticator + Send + Sync + 'static
{
/// Creates a new instance of `ConnectionManager`.
/// It requires transport, authenticator and compression as inputs.
pub fn new(load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression)
-> ClusterConnectionManager<T, X> |
}
impl<T: Authenticator + Send + Sync + 'static,
X: CDRSTransport + Send + Sync + 'static> r2d2::ManageConnection
for ClusterConnectionManager<T, X> {
type Connection = Session<T, X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CResult<X> = self.load_balancer
.next()
.ok_or_else(|| "Cannot get next node".into())
.and_then(|x| x.try_clone().map_err(|e| e.into()));
let transport = try!(transport_res);
let compression = self.compression;
let cdrs = CDRS::new(transport, self.authenticator.clone());
cdrs.start(compression)
}
fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();
connection.query(query, false, false).map(|_| ())
}
fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_robin() {
let nodes = vec!["a", "b", "c"];
let nodes_c = nodes.clone();
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::RoundRobin);
for i in 0..10 {
assert_eq!(&nodes_c[i % 3], load_balancer.next().unwrap());
}
}
#[test]
fn lb_random() {
let nodes = vec!["a", "b", "c", "d", "e", "f", "g"];
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::Random);
for _ in 0..100 {
let s = load_balancer.next();
assert!(s.is_some());
}
}
}
| {
ClusterConnectionManager {
load_balancer: load_balancer,
authenticator: authenticator,
compression: compression,
}
} | identifier_body |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CError, Result as CResult};
use authenticators::Authenticator;
use compression::Compression;
use r2d2;
use transport::CDRSTransport;
use rand;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Load balancing strategy
#[derive(PartialEq)]
pub enum LoadBalancingStrategy {
/// Round Robin balancing strategy
RoundRobin,
/// Random balancing strategy
Random,
}
impl LoadBalancingStrategy {
/// Returns next value for selected load balancing strategy
pub fn next<'a, N>(&'a self, nodes: &'a Vec<N>, i: usize) -> Option<&N> {
match *self {
LoadBalancingStrategy::Random => nodes.get(self.rnd_idx((0, Some(nodes.len())))),
LoadBalancingStrategy::RoundRobin => {
let mut cycle = nodes.iter().cycle().skip(i);
cycle.next()
}
}
}
/// Returns random number from a range
fn rnd_idx(&self, bounds: (usize, Option<usize>)) -> usize {
let min = bounds.0;
let max = bounds.1.unwrap_or(u8::max_value() as usize);
let rnd = rand::random::<usize>();
rnd % (max - min) + min
}
}
/// Load balancer
///
/// #Example
///
/// ```no_run
/// use cdrs::cluster::{LoadBalancingStrategy, LoadBalancer};
/// use cdrs::transport::TransportTcp;
/// let transports = vec![TransportTcp::new("127.0.0.1:9042"), TransportTcp::new("127.0.0.1:9042")];
/// let load_balancer = LoadBalancer::new(transports, LoadBalancingStrategy::RoundRobin);
/// let node = load_balancer.next().unwrap();
/// ```
pub struct LoadBalancer<T> {
strategy: LoadBalancingStrategy,
nodes: Vec<T>,
i: AtomicUsize,
}
impl<T> LoadBalancer<T> {
/// Factory function which creates new `LoadBalancer` with provided strategy.
pub fn new(nodes: Vec<T>, strategy: LoadBalancingStrategy) -> LoadBalancer<T> {
LoadBalancer {
nodes: nodes,
strategy: strategy,
i: AtomicUsize::new(0),
}
}
/// Returns next node basing on provided strategy.
pub fn next(&self) -> Option<&T> {
let next = self.strategy
.next(&self.nodes, self.i.load(Ordering::Relaxed) as usize);
if self.strategy == LoadBalancingStrategy::RoundRobin {
self.i.fetch_add(1, Ordering::Relaxed);
// prevent overflow
let i = self.i.load(Ordering::Relaxed);
match i.checked_rem(self.nodes.len() as usize) {
Some(rem) => self.i.store(rem, Ordering::Relaxed),
None => return None,
}
}
next
}
}
/// [r2d2](https://github.com/sfackler/r2d2) `ManageConnection`.
pub struct ClusterConnectionManager<T, X> {
load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression,
}
impl<T, X> ClusterConnectionManager<T, X>
where T: Authenticator + Send + Sync + 'static
{
/// Creates a new instance of `ConnectionManager`.
/// It requires transport, authenticator and compression as inputs.
pub fn new(load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression)
-> ClusterConnectionManager<T, X> {
ClusterConnectionManager {
load_balancer: load_balancer,
authenticator: authenticator,
compression: compression,
}
} | X: CDRSTransport + Send + Sync + 'static> r2d2::ManageConnection
for ClusterConnectionManager<T, X> {
type Connection = Session<T, X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CResult<X> = self.load_balancer
.next()
.ok_or_else(|| "Cannot get next node".into())
.and_then(|x| x.try_clone().map_err(|e| e.into()));
let transport = try!(transport_res);
let compression = self.compression;
let cdrs = CDRS::new(transport, self.authenticator.clone());
cdrs.start(compression)
}
fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();
connection.query(query, false, false).map(|_| ())
}
fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_robin() {
let nodes = vec!["a", "b", "c"];
let nodes_c = nodes.clone();
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::RoundRobin);
for i in 0..10 {
assert_eq!(&nodes_c[i % 3], load_balancer.next().unwrap());
}
}
#[test]
fn lb_random() {
let nodes = vec!["a", "b", "c", "d", "e", "f", "g"];
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::Random);
for _ in 0..100 {
let s = load_balancer.next();
assert!(s.is_some());
}
}
} | }
impl<T: Authenticator + Send + Sync + 'static, | random_line_split |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The `ByteString` struct.
use chrono::prelude::{Utc, Weekday};
use chrono::{Datelike, TimeZone};
use cssparser::CowRcStr;
use html5ever::{LocalName, Namespace};
use regex::Regex;
use servo_atoms::Atom;
use std::borrow::{Borrow, Cow, ToOwned};
use std::default::Default;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops;
use std::ops::{Deref, DerefMut};
use std::str;
use std::str::FromStr;
/// Encapsulates the IDL `ByteString` type.
#[derive(Clone, Debug, Default, Eq, JSTraceable, MallocSizeOf, PartialEq)]
pub struct ByteString(Vec<u8>);
impl ByteString {
/// Creates a new `ByteString`.
pub fn new(value: Vec<u8>) -> ByteString {
ByteString(value)
}
/// Returns `self` as a string, if it encodes valid UTF-8, and `None`
/// otherwise.
pub fn as_str(&self) -> Option<&str> {
str::from_utf8(&self.0).ok()
}
/// Returns the length.
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns `self` with A–Z replaced by a–z.
pub fn to_lower(&self) -> ByteString {
ByteString::new(self.0.to_ascii_lowercase())
}
}
impl Into<Vec<u8>> for ByteString {
fn into(self) -> Vec<u8> {
self.0
}
}
impl Hash for ByteString {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl FromStr for ByteString {
type Err = ();
fn from_str(s: &str) -> Result<ByteString, ()> {
Ok(ByteString::new(s.to_owned().into_bytes()))
}
}
impl ops::Deref for ByteString {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
/// A string that is constructed from a UCS-2 buffer by replacing invalid code
/// points with the replacement character.
#[derive(Clone, Default, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)]
pub struct USVString(pub String);
impl Borrow<str> for USVString {
#[inline]
fn borrow(&self) -> &str {
&self.0
}
}
impl Deref for USVString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&self.0
}
}
impl DerefMut for USVString {
#[inline]
fn deref_mut(&mut self) -> &mut str {
&mut self.0
}
}
impl AsRef<str> for USVString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for USVString {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl PartialEq<str> for USVString {
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
impl<'a> PartialEq<&'a str> for USVString {
fn eq(&self, other: &&'a str) -> bool {
&**self == *other
}
}
impl From<String> for USVString {
fn from(contents: String) -> USVString {
USVString(contents)
}
}
/// Returns whether `s` is a `token`, as defined by
/// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-17).
pub fn is_token(s: &[u8]) -> bool {
if s.is_empty() {
return false; // A token must be at least a single character
}
s.iter().all(|&x| {
// http://tools.ietf.org/html/rfc2616#section-2.2
match x {
0..=31 | 127 => false, // CTLs
40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 |
125 | 32 => false, // separators
x if x > 127 => false, // non-CHARs
_ => true,
}
})
}
/// A DOMString.
///
/// This type corresponds to the [`DOMString`](idl) type in WebIDL.
///
/// [idl]: https://heycam.github.io/webidl/#idl-DOMString
///
/// Conceptually, a DOMString has the same value space as a JavaScript String,
/// i.e., an array of 16-bit *code units* representing UTF-16, potentially with
/// unpaired surrogates present (also sometimes called WTF-16).
///
/// Currently, this type stores a Rust `String`, in order to avoid issues when
/// integrating with the rest of the Rust ecosystem and even the rest of the
/// browser itself.
///
/// However, Rust `String`s are guaranteed to be valid UTF-8, and as such have
/// a *smaller value space* than WTF-16 (i.e., some JavaScript String values
/// can not be represented as a Rust `String`). This introduces the question of
/// what to do with values being passed from JavaScript to Rust that contain
/// unpaired surrogates.
///
/// The hypothesis is that it does not matter much how exactly those values are
/// transformed, because passing unpaired surrogates into the DOM is very rare.
/// In order to test this hypothesis, Servo will panic when encountering any
/// unpaired surrogates on conversion to `DOMString` by default. (The command
/// line option `-Z replace-surrogates` instead causes Servo to replace the
/// unpaired surrogate by a U+FFFD replacement character.)
///
/// Currently, the lack of crash reports about this issue provides some
/// evidence to support the hypothesis. This evidence will hopefully be used to
/// convince other browser vendors that it would be safe to replace unpaired
/// surrogates at the boundary between JavaScript and native code. (This would
/// unify the `DOMString` and `USVString` types, both in the WebIDL standard
/// and in Servo.)
///
/// This type is currently `!Send`, in order to help with an independent
/// experiment to store `JSString`s rather than Rust `String`s.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)]
pub struct DOMS | ing, PhantomData<*const ()>);
impl DOMString {
/// Creates a new `DOMString`.
pub fn new() -> DOMString {
DOMString(String::new(), PhantomData)
}
/// Creates a new `DOMString` from a `String`.
pub fn from_string(s: String) -> DOMString {
DOMString(s, PhantomData)
}
/// Appends a given string slice onto the end of this String.
pub fn push_str(&mut self, string: &str) {
self.0.push_str(string)
}
/// Clears this `DOMString`, removing all contents.
pub fn clear(&mut self) {
self.0.clear()
}
/// Shortens this String to the specified length.
pub fn truncate(&mut self, new_len: usize) {
self.0.truncate(new_len);
}
/// Removes newline characters according to <https://infra.spec.whatwg.org/#strip-newlines>.
pub fn strip_newlines(&mut self) {
self.0.retain(|c| c != '\r' && c != '\n');
}
/// Removes leading and trailing ASCII whitespaces according to
/// <https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace>.
pub fn strip_leading_and_trailing_ascii_whitespace(&mut self) {
if self.0.len() == 0 {
return;
}
let trailing_whitespace_len = self
.0
.trim_end_matches(|ref c| char::is_ascii_whitespace(c))
.len();
self.0.truncate(trailing_whitespace_len);
if self.0.is_empty() {
return;
}
let first_non_whitespace = self.0.find(|ref c| !char::is_ascii_whitespace(c)).unwrap();
let _ = self.0.replace_range(0..first_non_whitespace, "");
}
/// Validates this `DOMString` is a time string according to
/// <https://html.spec.whatwg.org/multipage/#valid-time-string>.
pub fn is_valid_time_string(&self) -> bool {
enum State {
HourHigh,
HourLow09,
HourLow03,
MinuteColon,
MinuteHigh,
MinuteLow,
SecondColon,
SecondHigh,
SecondLow,
MilliStop,
MilliHigh,
MilliMiddle,
MilliLow,
Done,
Error,
}
let next_state = |valid: bool, next: State| -> State {
if valid {
next
} else {
State::Error
}
};
let state = self.chars().fold(State::HourHigh, |state, c| {
match state {
// Step 1 "HH"
State::HourHigh => match c {
'0' | '1' => State::HourLow09,
'2' => State::HourLow03,
_ => State::Error,
},
State::HourLow09 => next_state(c.is_digit(10), State::MinuteColon),
State::HourLow03 => next_state(c.is_digit(4), State::MinuteColon),
// Step 2 ":"
State::MinuteColon => next_state(c == ':', State::MinuteHigh),
// Step 3 "mm"
State::MinuteHigh => next_state(c.is_digit(6), State::MinuteLow),
State::MinuteLow => next_state(c.is_digit(10), State::SecondColon),
// Step 4.1 ":"
State::SecondColon => next_state(c == ':', State::SecondHigh),
// Step 4.2 "ss"
State::SecondHigh => next_state(c.is_digit(6), State::SecondLow),
State::SecondLow => next_state(c.is_digit(10), State::MilliStop),
// Step 4.3.1 "."
State::MilliStop => next_state(c == '.', State::MilliHigh),
// Step 4.3.2 "SSS"
State::MilliHigh => next_state(c.is_digit(10), State::MilliMiddle),
State::MilliMiddle => next_state(c.is_digit(10), State::MilliLow),
State::MilliLow => next_state(c.is_digit(10), State::Done),
_ => State::Error,
}
});
match state {
State::Done |
// Step 4 (optional)
State::SecondColon |
// Step 4.3 (optional)
State::MilliStop |
// Step 4.3.2 (only 1 digit required)
State::MilliMiddle | State::MilliLow => true,
_ => false
}
}
/// A valid date string should be "YYYY-MM-DD"
/// YYYY must be four or more digits, MM and DD both must be two digits
/// https://html.spec.whatwg.org/multipage/#valid-date-string
pub fn is_valid_date_string(&self) -> bool {
self.parse_date_string().is_ok()
}
/// https://html.spec.whatwg.org/multipage/#parse-a-date-string
pub fn parse_date_string(&self) -> Result<(i32, u32, u32), ()> {
let value = &self.0;
// Step 1, 2, 3
let (year_int, month_int, day_int) = parse_date_component(value)?;
// Step 4
if value.split('-').nth(3).is_some() {
return Err(());
}
// Step 5, 6
Ok((year_int, month_int, day_int))
}
/// https://html.spec.whatwg.org/multipage/#parse-a-time-string
pub fn parse_time_string(&self) -> Result<(u32, u32, f64), ()> {
let value = &self.0;
// Step 1, 2, 3
let (hour_int, minute_int, second_float) = parse_time_component(value)?;
// Step 4
if value.split(':').nth(3).is_some() {
return Err(());
}
// Step 5, 6
Ok((hour_int, minute_int, second_float))
}
/// A valid month string should be "YYYY-MM"
/// YYYY must be four or more digits, MM both must be two digits
/// https://html.spec.whatwg.org/multipage/#valid-month-string
pub fn is_valid_month_string(&self) -> bool {
self.parse_month_string().is_ok()
}
/// https://html.spec.whatwg.org/multipage/#parse-a-month-string
pub fn parse_month_string(&self) -> Result<(i32, u32), ()> {
let value = &self;
// Step 1, 2, 3
let (year_int, month_int) = parse_month_component(value)?;
// Step 4
if value.split("-").nth(2).is_some() {
return Err(());
}
// Step 5
Ok((year_int, month_int))
}
/// A valid week string should be like {YYYY}-W{WW}, such as "2017-W52"
/// YYYY must be four or more digits, WW both must be two digits
/// https://html.spec.whatwg.org/multipage/#valid-week-string
pub fn is_valid_week_string(&self) -> bool {
self.parse_week_string().is_ok()
}
/// https://html.spec.whatwg.org/multipage/#parse-a-week-string
pub fn parse_week_string(&self) -> Result<(i32, u32), ()> {
let value = &self.0;
// Step 1, 2, 3
let mut iterator = value.split('-');
let year = iterator.next().ok_or(())?;
// Step 4
let year_int = year.parse::<i32>().map_err(|_| ())?;
if year.len() < 4 || year_int == 0 {
return Err(());
}
// Step 5, 6
let week = iterator.next().ok_or(())?;
let (week_first, week_last) = week.split_at(1);
if week_first != "W" {
return Err(());
}
// Step 7
let week_int = week_last.parse::<u32>().map_err(|_| ())?;
if week_last.len() != 2 {
return Err(());
}
// Step 8
let max_week = max_week_in_year(year_int);
// Step 9
if week_int < 1 || week_int > max_week {
return Err(());
}
// Step 10
if iterator.next().is_some() {
return Err(());
}
// Step 11
Ok((year_int, week_int))
}
/// https://html.spec.whatwg.org/multipage/#valid-floating-point-number
pub fn is_valid_floating_point_number_string(&self) -> bool {
lazy_static! {
static ref RE: Regex =
Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap();
}
RE.is_match(&self.0) && self.parse_floating_point_number().is_ok()
}
/// https://html.spec.whatwg.org/multipage/#rules-for-parsing-floating-point-number-values
pub fn parse_floating_point_number(&self) -> Result<f64, ()> {
// Steps 15-16 are telling us things about IEEE rounding modes
// for floating-point significands; this code assumes the Rust
// compiler already matches them in any cases where
// that actually matters. They are not
// related to f64::round(), which is for rounding to integers.
let input = &self.0;
match input.trim().parse::<f64>() {
Ok(val)
if !(
// A valid number is the same as what rust considers to be valid,
// except for +1., NaN, and Infinity.
val.is_infinite() ||
val.is_nan() ||
input.ends_with(".") ||
input.starts_with("+")
) =>
{
Ok(val)
},
_ => Err(()),
}
}
/// https://html.spec.whatwg.org/multipage/#best-representation-of-the-number-as-a-floating-point-number
pub fn set_best_representation_of_the_floating_point_number(&mut self) {
if let Ok(val) = self.parse_floating_point_number() {
self.0 = val.to_string();
}
}
/// A valid normalized local date and time string should be "{date}T{time}"
/// where date and time are both valid, and the time string must be as short as possible
/// https://html.spec.whatwg.org/multipage/#valid-normalised-local-date-and-time-string
pub fn convert_valid_normalized_local_date_and_time_string(&mut self) -> Result<(), ()> {
let ((year, month, day), (hour, minute, second)) =
self.parse_local_date_and_time_string()?;
if second == 0.0 {
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}",
year, month, day, hour, minute
);
} else if second < 10.0 {
// we need exactly one leading zero on the seconds,
// whatever their total string length might be
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:0{}",
year, month, day, hour, minute, second
);
} else {
// we need no leading zeroes on the seconds
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{}",
year, month, day, hour, minute, second
);
}
Ok(())
}
/// https://html.spec.whatwg.org/multipage/#parse-a-local-date-and-time-string
pub fn parse_local_date_and_time_string(
&self,
) -> Result<((i32, u32, u32), (u32, u32, f64)), ()> {
let value = &self;
// Step 1, 2, 4
let mut iterator = if value.contains('T') {
value.split('T')
} else {
value.split(' ')
};
// Step 3
let date = iterator.next().ok_or(())?;
let date_tuple = parse_date_component(date)?;
// Step 5
let time = iterator.next().ok_or(())?;
let time_tuple = parse_time_component(time)?;
// Step 6
if iterator.next().is_some() {
return Err(());
}
// Step 7, 8, 9
Ok((date_tuple, time_tuple))
}
}
impl Borrow<str> for DOMString {
#[inline]
fn borrow(&self) -> &str {
&self.0
}
}
impl Default for DOMString {
fn default() -> Self {
DOMString(String::new(), PhantomData)
}
}
impl Deref for DOMString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&self.0
}
}
impl DerefMut for DOMString {
#[inline]
fn deref_mut(&mut self) -> &mut str {
&mut self.0
}
}
impl AsRef<str> for DOMString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for DOMString {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl PartialEq<str> for DOMString {
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
impl<'a> PartialEq<&'a str> for DOMString {
fn eq(&self, other: &&'a str) -> bool {
&**self == *other
}
}
impl From<String> for DOMString {
fn from(contents: String) -> DOMString {
DOMString(contents, PhantomData)
}
}
impl<'a> From<&'a str> for DOMString {
fn from(contents: &str) -> DOMString {
DOMString::from(String::from(contents))
}
}
impl<'a> From<Cow<'a, str>> for DOMString {
fn from(contents: Cow<'a, str>) -> DOMString {
match contents {
Cow::Owned(s) => DOMString::from(s),
Cow::Borrowed(s) => DOMString::from(s),
}
}
}
impl From<DOMString> for LocalName {
fn from(contents: DOMString) -> LocalName {
LocalName::from(contents.0)
}
}
impl From<DOMString> for Namespace {
fn from(contents: DOMString) -> Namespace {
Namespace::from(contents.0)
}
}
impl From<DOMString> for Atom {
fn from(contents: DOMString) -> Atom {
Atom::from(contents.0)
}
}
impl From<DOMString> for String {
fn from(contents: DOMString) -> String {
contents.0
}
}
impl Into<Vec<u8>> for DOMString {
fn into(self) -> Vec<u8> {
self.0.into()
}
}
impl<'a> Into<Cow<'a, str>> for DOMString {
fn into(self) -> Cow<'a, str> {
self.0.into()
}
}
impl<'a> Into<CowRcStr<'a>> for DOMString {
fn into(self) -> CowRcStr<'a> {
self.0.into()
}
}
impl Extend<char> for DOMString {
fn extend<I>(&mut self, iterable: I)
where
I: IntoIterator<Item = char>,
{
self.0.extend(iterable)
}
}
/// https://html.spec.whatwg.org/multipage/#parse-a-month-component
fn parse_month_component(value: &str) -> Result<(i32, u32), ()> {
// Step 3
let mut iterator = value.split('-');
let year = iterator.next().ok_or(())?;
let month = iterator.next().ok_or(())?;
// Step 1, 2
let year_int = year.parse::<i32>().map_err(|_| ())?;
if year.len() < 4 || year_int == 0 {
return Err(());
}
// Step 4, 5
let month_int = month.parse::<u32>().map_err(|_| ())?;
if month.len() != 2 || month_int > 12 || month_int < 1 {
return Err(());
}
// Step 6
Ok((year_int, month_int))
}
/// https://html.spec.whatwg.org/multipage/#parse-a-date-component
fn parse_date_component(value: &str) -> Result<(i32, u32, u32), ()> {
// Step 1
let (year_int, month_int) = parse_month_component(value)?;
// Step 3, 4
let day = value.split('-').nth(2).ok_or(())?;
let day_int = day.parse::<u32>().map_err(|_| ())?;
if day.len() != 2 {
return Err(());
}
// Step 2, 5
let max_day = max_day_in_month(year_int, month_int)?;
if day_int == 0 || day_int > max_day {
return Err(());
}
// Step 6
Ok((year_int, month_int, day_int))
}
/// https://html.spec.whatwg.org/multipage/#parse-a-time-component
fn parse_time_component(value: &str) -> Result<(u32, u32, f64), ()> {
// Step 1
let mut iterator = value.split(':');
let hour = iterator.next().ok_or(())?;
if hour.len() != 2 {
return Err(());
}
let hour_int = hour.parse::<u32>().map_err(|_| ())?;
// Step 2
if hour_int > 23 {
return Err(());
}
// Step 3, 4
let minute = iterator.next().ok_or(())?;
if minute.len() != 2 {
return Err(());
}
let minute_int = minute.parse::<u32>().map_err(|_| ())?;
// Step 5
if minute_int > 59 {
return Err(());
}
// Step 6, 7
let second_float = match iterator.next() {
Some(second) => {
let mut second_iterator = second.split('.');
if second_iterator.next().ok_or(())?.len() != 2 {
return Err(());
}
match second_iterator.next() {
Some(second_last) => {
if second_last.len() > 3 {
return Err(());
}
},
None => {},
}
second.parse::<f64>().map_err(|_| ())?
},
None => 0.0,
};
// Step 8
Ok((hour_int, minute_int, second_float))
}
fn max_day_in_month(year_num: i32, month_num: u32) -> Result<u32, ()> {
match month_num {
1 | 3 | 5 | 7 | 8 | 10 | 12 => Ok(31),
4 | 6 | 9 | 11 => Ok(30),
2 => {
if is_leap_year(year_num) {
Ok(29)
} else {
Ok(28)
}
},
_ => Err(()),
}
}
/// https://html.spec.whatwg.org/multipage/#week-number-of-the-last-day
fn max_week_in_year(year: i32) -> u32 {
match Utc.ymd(year as i32, 1, 1).weekday() {
Weekday::Thu => 53,
Weekday::Wed if is_leap_year(year) => 53,
_ => 52,
}
}
#[inline]
fn is_leap_year(year: i32) -> bool {
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
}
| tring(Str | identifier_name |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The `ByteString` struct.
use chrono::prelude::{Utc, Weekday};
use chrono::{Datelike, TimeZone};
use cssparser::CowRcStr;
use html5ever::{LocalName, Namespace};
use regex::Regex;
use servo_atoms::Atom;
use std::borrow::{Borrow, Cow, ToOwned};
use std::default::Default;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops;
use std::ops::{Deref, DerefMut};
use std::str;
use std::str::FromStr;
/// Encapsulates the IDL `ByteString` type.
#[derive(Clone, Debug, Default, Eq, JSTraceable, MallocSizeOf, PartialEq)]
pub struct ByteString(Vec<u8>);
impl ByteString {
/// Creates a new `ByteString`.
pub fn new(value: Vec<u8>) -> ByteString {
ByteString(value)
}
/// Returns `self` as a string, if it encodes valid UTF-8, and `None`
/// otherwise.
pub fn as_str(&self) -> Option<&str> {
str::from_utf8(&self.0).ok()
}
/// Returns the length.
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns `self` with A–Z replaced by a–z.
pub fn to_lower(&self) -> ByteString {
ByteString::new(self.0.to_ascii_lowercase())
}
}
impl Into<Vec<u8>> for ByteString {
fn into(self) -> Vec<u8> {
self.0
}
}
impl Hash for ByteString {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl FromStr for ByteString {
type Err = ();
fn from_str(s: &str) -> Result<ByteString, ()> {
Ok(ByteString::new(s.to_owned().into_bytes()))
}
}
impl ops::Deref for ByteString {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
/// A string that is constructed from a UCS-2 buffer by replacing invalid code
/// points with the replacement character.
#[derive(Clone, Default, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)]
pub struct USVString(pub String);
impl Borrow<str> for USVString {
#[inline]
fn borrow(&self) -> &str {
&self.0
}
}
impl Deref for USVString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&self.0
}
}
impl DerefMut for USVString {
#[inline]
fn deref_mut(&mut self) -> &mut str {
&mut self.0
}
}
impl AsRef<str> for USVString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for USVString {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl PartialEq<str> for USVString {
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
impl<'a> PartialEq<&'a str> for USVString {
fn eq(&self, other: &&'a str) -> bool {
&**self == *other
}
}
impl From<String> for USVString {
fn from(contents: String) -> USVString {
USVString(contents)
}
}
/// Returns whether `s` is a `token`, as defined by
/// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-17).
pub fn is_token(s: &[u8]) -> bool {
if s.is_empty() {
return false; // A token must be at least a single character
}
s.iter().all(|&x| {
// http://tools.ietf.org/html/rfc2616#section-2.2
match x {
0..=31 | 127 => false, // CTLs
40 | 41 | 60 | 62 | 64 | 44 | 59 | 58 | 92 | 34 | 47 | 91 | 93 | 63 | 61 | 123 |
125 | 32 => false, // separators
x if x > 127 => false, // non-CHARs
_ => true,
}
})
}
/// A DOMString.
///
/// This type corresponds to the [`DOMString`](idl) type in WebIDL.
///
/// [idl]: https://heycam.github.io/webidl/#idl-DOMString
///
/// Conceptually, a DOMString has the same value space as a JavaScript String,
/// i.e., an array of 16-bit *code units* representing UTF-16, potentially with
/// unpaired surrogates present (also sometimes called WTF-16).
///
/// Currently, this type stores a Rust `String`, in order to avoid issues when
/// integrating with the rest of the Rust ecosystem and even the rest of the
/// browser itself.
///
/// However, Rust `String`s are guaranteed to be valid UTF-8, and as such have
/// a *smaller value space* than WTF-16 (i.e., some JavaScript String values
/// can not be represented as a Rust `String`). This introduces the question of
/// what to do with values being passed from JavaScript to Rust that contain
/// unpaired surrogates.
///
/// The hypothesis is that it does not matter much how exactly those values are
/// transformed, because passing unpaired surrogates into the DOM is very rare.
/// In order to test this hypothesis, Servo will panic when encountering any
/// unpaired surrogates on conversion to `DOMString` by default. (The command
/// line option `-Z replace-surrogates` instead causes Servo to replace the
/// unpaired surrogate by a U+FFFD replacement character.)
///
/// Currently, the lack of crash reports about this issue provides some
/// evidence to support the hypothesis. This evidence will hopefully be used to
/// convince other browser vendors that it would be safe to replace unpaired
/// surrogates at the boundary between JavaScript and native code. (This would
/// unify the `DOMString` and `USVString` types, both in the WebIDL standard
/// and in Servo.)
///
/// This type is currently `!Send`, in order to help with an independent
/// experiment to store `JSString`s rather than Rust `String`s.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)]
pub struct DOMString(String, PhantomData<*const ()>);
impl DOMString {
/// Creates a new `DOMString`.
pub fn new() -> DOMString {
DOMString(String::new(), PhantomData)
}
/// Creates a new `DOMString` from a `String`. |
/// Appends a given string slice onto the end of this String.
pub fn push_str(&mut self, string: &str) {
self.0.push_str(string)
}
/// Clears this `DOMString`, removing all contents.
pub fn clear(&mut self) {
self.0.clear()
}
/// Shortens this String to the specified length.
pub fn truncate(&mut self, new_len: usize) {
self.0.truncate(new_len);
}
/// Removes newline characters according to <https://infra.spec.whatwg.org/#strip-newlines>.
pub fn strip_newlines(&mut self) {
self.0.retain(|c| c != '\r' && c != '\n');
}
/// Removes leading and trailing ASCII whitespaces according to
/// <https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace>.
pub fn strip_leading_and_trailing_ascii_whitespace(&mut self) {
if self.0.len() == 0 {
return;
}
let trailing_whitespace_len = self
.0
.trim_end_matches(|ref c| char::is_ascii_whitespace(c))
.len();
self.0.truncate(trailing_whitespace_len);
if self.0.is_empty() {
return;
}
let first_non_whitespace = self.0.find(|ref c| !char::is_ascii_whitespace(c)).unwrap();
let _ = self.0.replace_range(0..first_non_whitespace, "");
}
/// Validates this `DOMString` is a time string according to
/// <https://html.spec.whatwg.org/multipage/#valid-time-string>.
pub fn is_valid_time_string(&self) -> bool {
enum State {
HourHigh,
HourLow09,
HourLow03,
MinuteColon,
MinuteHigh,
MinuteLow,
SecondColon,
SecondHigh,
SecondLow,
MilliStop,
MilliHigh,
MilliMiddle,
MilliLow,
Done,
Error,
}
let next_state = |valid: bool, next: State| -> State {
if valid {
next
} else {
State::Error
}
};
let state = self.chars().fold(State::HourHigh, |state, c| {
match state {
// Step 1 "HH"
State::HourHigh => match c {
'0' | '1' => State::HourLow09,
'2' => State::HourLow03,
_ => State::Error,
},
State::HourLow09 => next_state(c.is_digit(10), State::MinuteColon),
State::HourLow03 => next_state(c.is_digit(4), State::MinuteColon),
// Step 2 ":"
State::MinuteColon => next_state(c == ':', State::MinuteHigh),
// Step 3 "mm"
State::MinuteHigh => next_state(c.is_digit(6), State::MinuteLow),
State::MinuteLow => next_state(c.is_digit(10), State::SecondColon),
// Step 4.1 ":"
State::SecondColon => next_state(c == ':', State::SecondHigh),
// Step 4.2 "ss"
State::SecondHigh => next_state(c.is_digit(6), State::SecondLow),
State::SecondLow => next_state(c.is_digit(10), State::MilliStop),
// Step 4.3.1 "."
State::MilliStop => next_state(c == '.', State::MilliHigh),
// Step 4.3.2 "SSS"
State::MilliHigh => next_state(c.is_digit(10), State::MilliMiddle),
State::MilliMiddle => next_state(c.is_digit(10), State::MilliLow),
State::MilliLow => next_state(c.is_digit(10), State::Done),
_ => State::Error,
}
});
match state {
State::Done |
// Step 4 (optional)
State::SecondColon |
// Step 4.3 (optional)
State::MilliStop |
// Step 4.3.2 (only 1 digit required)
State::MilliMiddle | State::MilliLow => true,
_ => false
}
}
/// A valid date string should be "YYYY-MM-DD"
/// YYYY must be four or more digits, MM and DD both must be two digits
/// https://html.spec.whatwg.org/multipage/#valid-date-string
pub fn is_valid_date_string(&self) -> bool {
self.parse_date_string().is_ok()
}
/// https://html.spec.whatwg.org/multipage/#parse-a-date-string
pub fn parse_date_string(&self) -> Result<(i32, u32, u32), ()> {
let value = &self.0;
// Step 1, 2, 3
let (year_int, month_int, day_int) = parse_date_component(value)?;
// Step 4
if value.split('-').nth(3).is_some() {
return Err(());
}
// Step 5, 6
Ok((year_int, month_int, day_int))
}
/// https://html.spec.whatwg.org/multipage/#parse-a-time-string
pub fn parse_time_string(&self) -> Result<(u32, u32, f64), ()> {
let value = &self.0;
// Step 1, 2, 3
let (hour_int, minute_int, second_float) = parse_time_component(value)?;
// Step 4
if value.split(':').nth(3).is_some() {
return Err(());
}
// Step 5, 6
Ok((hour_int, minute_int, second_float))
}
/// A valid month string should be "YYYY-MM"
/// YYYY must be four or more digits, MM both must be two digits
/// https://html.spec.whatwg.org/multipage/#valid-month-string
pub fn is_valid_month_string(&self) -> bool {
self.parse_month_string().is_ok()
}
/// https://html.spec.whatwg.org/multipage/#parse-a-month-string
pub fn parse_month_string(&self) -> Result<(i32, u32), ()> {
let value = &self;
// Step 1, 2, 3
let (year_int, month_int) = parse_month_component(value)?;
// Step 4
if value.split("-").nth(2).is_some() {
return Err(());
}
// Step 5
Ok((year_int, month_int))
}
/// A valid week string should be like {YYYY}-W{WW}, such as "2017-W52"
/// YYYY must be four or more digits, WW both must be two digits
/// https://html.spec.whatwg.org/multipage/#valid-week-string
pub fn is_valid_week_string(&self) -> bool {
self.parse_week_string().is_ok()
}
/// https://html.spec.whatwg.org/multipage/#parse-a-week-string
pub fn parse_week_string(&self) -> Result<(i32, u32), ()> {
let value = &self.0;
// Step 1, 2, 3
let mut iterator = value.split('-');
let year = iterator.next().ok_or(())?;
// Step 4
let year_int = year.parse::<i32>().map_err(|_| ())?;
if year.len() < 4 || year_int == 0 {
return Err(());
}
// Step 5, 6
let week = iterator.next().ok_or(())?;
let (week_first, week_last) = week.split_at(1);
if week_first != "W" {
return Err(());
}
// Step 7
let week_int = week_last.parse::<u32>().map_err(|_| ())?;
if week_last.len() != 2 {
return Err(());
}
// Step 8
let max_week = max_week_in_year(year_int);
// Step 9
if week_int < 1 || week_int > max_week {
return Err(());
}
// Step 10
if iterator.next().is_some() {
return Err(());
}
// Step 11
Ok((year_int, week_int))
}
/// https://html.spec.whatwg.org/multipage/#valid-floating-point-number
pub fn is_valid_floating_point_number_string(&self) -> bool {
lazy_static! {
static ref RE: Regex =
Regex::new(r"^-?(?:\d+\.\d+|\d+|\.\d+)(?:(e|E)(\+|\-)?\d+)?$").unwrap();
}
RE.is_match(&self.0) && self.parse_floating_point_number().is_ok()
}
/// https://html.spec.whatwg.org/multipage/#rules-for-parsing-floating-point-number-values
pub fn parse_floating_point_number(&self) -> Result<f64, ()> {
// Steps 15-16 are telling us things about IEEE rounding modes
// for floating-point significands; this code assumes the Rust
// compiler already matches them in any cases where
// that actually matters. They are not
// related to f64::round(), which is for rounding to integers.
let input = &self.0;
match input.trim().parse::<f64>() {
Ok(val)
if !(
// A valid number is the same as what rust considers to be valid,
// except for +1., NaN, and Infinity.
val.is_infinite() ||
val.is_nan() ||
input.ends_with(".") ||
input.starts_with("+")
) =>
{
Ok(val)
},
_ => Err(()),
}
}
/// https://html.spec.whatwg.org/multipage/#best-representation-of-the-number-as-a-floating-point-number
pub fn set_best_representation_of_the_floating_point_number(&mut self) {
if let Ok(val) = self.parse_floating_point_number() {
self.0 = val.to_string();
}
}
/// A valid normalized local date and time string should be "{date}T{time}"
/// where date and time are both valid, and the time string must be as short as possible
/// https://html.spec.whatwg.org/multipage/#valid-normalised-local-date-and-time-string
pub fn convert_valid_normalized_local_date_and_time_string(&mut self) -> Result<(), ()> {
let ((year, month, day), (hour, minute, second)) =
self.parse_local_date_and_time_string()?;
if second == 0.0 {
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}",
year, month, day, hour, minute
);
} else if second < 10.0 {
// we need exactly one leading zero on the seconds,
// whatever their total string length might be
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:0{}",
year, month, day, hour, minute, second
);
} else {
// we need no leading zeroes on the seconds
self.0 = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{}",
year, month, day, hour, minute, second
);
}
Ok(())
}
/// https://html.spec.whatwg.org/multipage/#parse-a-local-date-and-time-string
pub fn parse_local_date_and_time_string(
&self,
) -> Result<((i32, u32, u32), (u32, u32, f64)), ()> {
let value = &self;
// Step 1, 2, 4
let mut iterator = if value.contains('T') {
value.split('T')
} else {
value.split(' ')
};
// Step 3
let date = iterator.next().ok_or(())?;
let date_tuple = parse_date_component(date)?;
// Step 5
let time = iterator.next().ok_or(())?;
let time_tuple = parse_time_component(time)?;
// Step 6
if iterator.next().is_some() {
return Err(());
}
// Step 7, 8, 9
Ok((date_tuple, time_tuple))
}
}
impl Borrow<str> for DOMString {
#[inline]
fn borrow(&self) -> &str {
&self.0
}
}
impl Default for DOMString {
fn default() -> Self {
DOMString(String::new(), PhantomData)
}
}
impl Deref for DOMString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&self.0
}
}
impl DerefMut for DOMString {
#[inline]
fn deref_mut(&mut self) -> &mut str {
&mut self.0
}
}
impl AsRef<str> for DOMString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for DOMString {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl PartialEq<str> for DOMString {
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
impl<'a> PartialEq<&'a str> for DOMString {
fn eq(&self, other: &&'a str) -> bool {
&**self == *other
}
}
impl From<String> for DOMString {
fn from(contents: String) -> DOMString {
DOMString(contents, PhantomData)
}
}
impl<'a> From<&'a str> for DOMString {
fn from(contents: &str) -> DOMString {
DOMString::from(String::from(contents))
}
}
impl<'a> From<Cow<'a, str>> for DOMString {
fn from(contents: Cow<'a, str>) -> DOMString {
match contents {
Cow::Owned(s) => DOMString::from(s),
Cow::Borrowed(s) => DOMString::from(s),
}
}
}
impl From<DOMString> for LocalName {
fn from(contents: DOMString) -> LocalName {
LocalName::from(contents.0)
}
}
impl From<DOMString> for Namespace {
fn from(contents: DOMString) -> Namespace {
Namespace::from(contents.0)
}
}
impl From<DOMString> for Atom {
fn from(contents: DOMString) -> Atom {
Atom::from(contents.0)
}
}
impl From<DOMString> for String {
fn from(contents: DOMString) -> String {
contents.0
}
}
impl Into<Vec<u8>> for DOMString {
fn into(self) -> Vec<u8> {
self.0.into()
}
}
impl<'a> Into<Cow<'a, str>> for DOMString {
fn into(self) -> Cow<'a, str> {
self.0.into()
}
}
impl<'a> Into<CowRcStr<'a>> for DOMString {
fn into(self) -> CowRcStr<'a> {
self.0.into()
}
}
impl Extend<char> for DOMString {
fn extend<I>(&mut self, iterable: I)
where
I: IntoIterator<Item = char>,
{
self.0.extend(iterable)
}
}
/// https://html.spec.whatwg.org/multipage/#parse-a-month-component
fn parse_month_component(value: &str) -> Result<(i32, u32), ()> {
// Step 3
let mut iterator = value.split('-');
let year = iterator.next().ok_or(())?;
let month = iterator.next().ok_or(())?;
// Step 1, 2
let year_int = year.parse::<i32>().map_err(|_| ())?;
if year.len() < 4 || year_int == 0 {
return Err(());
}
// Step 4, 5
let month_int = month.parse::<u32>().map_err(|_| ())?;
if month.len() != 2 || month_int > 12 || month_int < 1 {
return Err(());
}
// Step 6
Ok((year_int, month_int))
}
/// https://html.spec.whatwg.org/multipage/#parse-a-date-component
fn parse_date_component(value: &str) -> Result<(i32, u32, u32), ()> {
// Step 1
let (year_int, month_int) = parse_month_component(value)?;
// Step 3, 4
let day = value.split('-').nth(2).ok_or(())?;
let day_int = day.parse::<u32>().map_err(|_| ())?;
if day.len() != 2 {
return Err(());
}
// Step 2, 5
let max_day = max_day_in_month(year_int, month_int)?;
if day_int == 0 || day_int > max_day {
return Err(());
}
// Step 6
Ok((year_int, month_int, day_int))
}
/// https://html.spec.whatwg.org/multipage/#parse-a-time-component
fn parse_time_component(value: &str) -> Result<(u32, u32, f64), ()> {
// Step 1
let mut iterator = value.split(':');
let hour = iterator.next().ok_or(())?;
if hour.len() != 2 {
return Err(());
}
let hour_int = hour.parse::<u32>().map_err(|_| ())?;
// Step 2
if hour_int > 23 {
return Err(());
}
// Step 3, 4
let minute = iterator.next().ok_or(())?;
if minute.len() != 2 {
return Err(());
}
let minute_int = minute.parse::<u32>().map_err(|_| ())?;
// Step 5
if minute_int > 59 {
return Err(());
}
// Step 6, 7
let second_float = match iterator.next() {
Some(second) => {
let mut second_iterator = second.split('.');
if second_iterator.next().ok_or(())?.len() != 2 {
return Err(());
}
match second_iterator.next() {
Some(second_last) => {
if second_last.len() > 3 {
return Err(());
}
},
None => {},
}
second.parse::<f64>().map_err(|_| ())?
},
None => 0.0,
};
// Step 8
Ok((hour_int, minute_int, second_float))
}
fn max_day_in_month(year_num: i32, month_num: u32) -> Result<u32, ()> {
match month_num {
1 | 3 | 5 | 7 | 8 | 10 | 12 => Ok(31),
4 | 6 | 9 | 11 => Ok(30),
2 => {
if is_leap_year(year_num) {
Ok(29)
} else {
Ok(28)
}
},
_ => Err(()),
}
}
/// https://html.spec.whatwg.org/multipage/#week-number-of-the-last-day
fn max_week_in_year(year: i32) -> u32 {
match Utc.ymd(year as i32, 1, 1).weekday() {
Weekday::Thu => 53,
Weekday::Wed if is_leap_year(year) => 53,
_ => 52,
}
}
#[inline]
fn is_leap_year(year: i32) -> bool {
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
} | pub fn from_string(s: String) -> DOMString {
DOMString(s, PhantomData)
} | random_line_split |
app.js | angular.module('app', ['app.controllers', 'app.services', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
templateUrl: "/html/home.html",
data: {
requireLogin: false
}
})
.state('entrar', {
url: "/entrar",
templateUrl: "/html/entrar.html",
controller: 'LoginController',
data: {
requireLogin: false
}
})
.state('cadastrar', {
url: "/cadastrar",
templateUrl: "/html/cadastrar.html",
controller: 'LoginController',
data: {
requireLogin: false
}
})
.state('painel', {
url: "/painel",
templateUrl: "/html/painel.html",
controller: 'PainelController',
data: {
requireLogin: true
}
})
.state('painel.novoCaderno', {
url: "/novoCaderno",
templateUrl: "/html/novo_caderno.html",
controller: 'CadernoController'
})
.state('painel.caderno', {
url: "/caderno",
templateUrl: "/html/caderno.html",
controller: 'CadernoController'
})
.state('painel.caderno.nota', {
url: "/nota",
templateUrl: "/html/nota.html",
controller: 'CadernoController'
});
$httpProvider.interceptors.push('AuthInterceptor');
})
.run(function($rootScope, $state, AuthToken) {
| event.preventDefault();
$state.go('entrar');
}
});
}); | $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
if(requireLogin && !AuthToken.isAuthenticated()) {
| random_line_split |
app.js | angular.module('app', ['app.controllers', 'app.services', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
templateUrl: "/html/home.html",
data: {
requireLogin: false
}
})
.state('entrar', {
url: "/entrar",
templateUrl: "/html/entrar.html",
controller: 'LoginController',
data: {
requireLogin: false
}
})
.state('cadastrar', {
url: "/cadastrar",
templateUrl: "/html/cadastrar.html",
controller: 'LoginController',
data: {
requireLogin: false
}
})
.state('painel', {
url: "/painel",
templateUrl: "/html/painel.html",
controller: 'PainelController',
data: {
requireLogin: true
}
})
.state('painel.novoCaderno', {
url: "/novoCaderno",
templateUrl: "/html/novo_caderno.html",
controller: 'CadernoController'
})
.state('painel.caderno', {
url: "/caderno",
templateUrl: "/html/caderno.html",
controller: 'CadernoController'
})
.state('painel.caderno.nota', {
url: "/nota",
templateUrl: "/html/nota.html",
controller: 'CadernoController'
});
$httpProvider.interceptors.push('AuthInterceptor');
})
.run(function($rootScope, $state, AuthToken) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
if(requireLogin && !AuthToken.isAuthenticated()) |
});
});
| {
event.preventDefault();
$state.go('entrar');
} | conditional_block |
grunt.js | /*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: '<json:jquery-disqus.jquery.json>',
meta: {
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
},
concat: {
dist: {
src: ['<banner:meta.banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'],
dest: 'dist/<%= pkg.name %>.js'
}
},
min: {
dist: {
src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
dest: 'dist/<%= pkg.name %>.min.js'
}
},
qunit: {
files: ['test/**/*.html']
},
lint: {
files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']
},
watch: {
files: '<config:lint.files>',
tasks: 'lint qunit'
},
jshint: {
options: {
curly: true,
eqeqeq: true, | sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true
},
globals: {
jQuery: true
}
},
uglify: {}
});
// Default task.
grunt.registerTask('default', 'lint qunit concat min');
}; | immed: true,
latedef: true,
newcap: true,
noarg: true, | random_line_split |
convertSub.py | from PyQt5 import QtWidgets
from projManagement.Validation import Validation
from configuration.Appconfig import Appconfig
import os
# This class is called when user creates new Project
class convertSub(QtWidgets.QWidget):
"""
Contains functions that checks project present for conversion and
also function to convert Kicad Netlist to Ngspice Netlist.
"""
def __init__(self, dockarea):
super(convertSub, self).__init__()
self.obj_validation = Validation()
self.obj_appconfig = Appconfig()
self.obj_dockarea = dockarea
def createSub(self):
"""
This function create command to call KiCad to Ngspice converter.
If the netlist is not generated for selected project it will show
error **The subcircuit does not contain any Kicad netlist file for
conversion.**
And if no project is selected for conversion, it again show error
message to select a file or create a file.
"""
print("Openinig Kicad-to-Ngspice converter from Subcircuit Module")
self.projDir = self.obj_appconfig.current_subcircuit["SubcircuitName"]
# Validating if current project is available or not
if self.obj_validation.validateKicad(self.projDir):
# Checking if project has .cir file or not
if self.obj_validation.validateCir(self.projDir):
|
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'The subcircuit does not contain any Kicad netlist file' +
' for conversion.'
)
self.msg.exec_()
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'Please select the subcircuit first. You can either create ' +
'new subcircuit or open existing subcircuit'
)
self.msg.exec_()
| self.projName = os.path.basename(self.projDir)
self.project = os.path.join(self.projDir, self.projName)
var1 = self.project + ".cir"
var2 = "sub"
self.obj_dockarea.kicadToNgspiceEditor(var1, var2) | conditional_block |
convertSub.py | from PyQt5 import QtWidgets
from projManagement.Validation import Validation
from configuration.Appconfig import Appconfig
import os
# This class is called when user creates new Project
class convertSub(QtWidgets.QWidget):
"""
Contains functions that checks project present for conversion and
also function to convert Kicad Netlist to Ngspice Netlist.
"""
def __init__(self, dockarea):
super(convertSub, self).__init__()
self.obj_validation = Validation()
self.obj_appconfig = Appconfig()
self.obj_dockarea = dockarea | This function create command to call KiCad to Ngspice converter.
If the netlist is not generated for selected project it will show
error **The subcircuit does not contain any Kicad netlist file for
conversion.**
And if no project is selected for conversion, it again show error
message to select a file or create a file.
"""
print("Openinig Kicad-to-Ngspice converter from Subcircuit Module")
self.projDir = self.obj_appconfig.current_subcircuit["SubcircuitName"]
# Validating if current project is available or not
if self.obj_validation.validateKicad(self.projDir):
# Checking if project has .cir file or not
if self.obj_validation.validateCir(self.projDir):
self.projName = os.path.basename(self.projDir)
self.project = os.path.join(self.projDir, self.projName)
var1 = self.project + ".cir"
var2 = "sub"
self.obj_dockarea.kicadToNgspiceEditor(var1, var2)
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'The subcircuit does not contain any Kicad netlist file' +
' for conversion.'
)
self.msg.exec_()
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'Please select the subcircuit first. You can either create ' +
'new subcircuit or open existing subcircuit'
)
self.msg.exec_() |
def createSub(self):
""" | random_line_split |
convertSub.py | from PyQt5 import QtWidgets
from projManagement.Validation import Validation
from configuration.Appconfig import Appconfig
import os
# This class is called when user creates new Project
class convertSub(QtWidgets.QWidget):
| """
Contains functions that checks project present for conversion and
also function to convert Kicad Netlist to Ngspice Netlist.
"""
def __init__(self, dockarea):
super(convertSub, self).__init__()
self.obj_validation = Validation()
self.obj_appconfig = Appconfig()
self.obj_dockarea = dockarea
def createSub(self):
"""
This function create command to call KiCad to Ngspice converter.
If the netlist is not generated for selected project it will show
error **The subcircuit does not contain any Kicad netlist file for
conversion.**
And if no project is selected for conversion, it again show error
message to select a file or create a file.
"""
print("Openinig Kicad-to-Ngspice converter from Subcircuit Module")
self.projDir = self.obj_appconfig.current_subcircuit["SubcircuitName"]
# Validating if current project is available or not
if self.obj_validation.validateKicad(self.projDir):
# Checking if project has .cir file or not
if self.obj_validation.validateCir(self.projDir):
self.projName = os.path.basename(self.projDir)
self.project = os.path.join(self.projDir, self.projName)
var1 = self.project + ".cir"
var2 = "sub"
self.obj_dockarea.kicadToNgspiceEditor(var1, var2)
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'The subcircuit does not contain any Kicad netlist file' +
' for conversion.'
)
self.msg.exec_()
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'Please select the subcircuit first. You can either create ' +
'new subcircuit or open existing subcircuit'
)
self.msg.exec_() | identifier_body | |
convertSub.py | from PyQt5 import QtWidgets
from projManagement.Validation import Validation
from configuration.Appconfig import Appconfig
import os
# This class is called when user creates new Project
class convertSub(QtWidgets.QWidget):
"""
Contains functions that checks project present for conversion and
also function to convert Kicad Netlist to Ngspice Netlist.
"""
def | (self, dockarea):
super(convertSub, self).__init__()
self.obj_validation = Validation()
self.obj_appconfig = Appconfig()
self.obj_dockarea = dockarea
def createSub(self):
"""
This function create command to call KiCad to Ngspice converter.
If the netlist is not generated for selected project it will show
error **The subcircuit does not contain any Kicad netlist file for
conversion.**
And if no project is selected for conversion, it again show error
message to select a file or create a file.
"""
print("Openinig Kicad-to-Ngspice converter from Subcircuit Module")
self.projDir = self.obj_appconfig.current_subcircuit["SubcircuitName"]
# Validating if current project is available or not
if self.obj_validation.validateKicad(self.projDir):
# Checking if project has .cir file or not
if self.obj_validation.validateCir(self.projDir):
self.projName = os.path.basename(self.projDir)
self.project = os.path.join(self.projDir, self.projName)
var1 = self.project + ".cir"
var2 = "sub"
self.obj_dockarea.kicadToNgspiceEditor(var1, var2)
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'The subcircuit does not contain any Kicad netlist file' +
' for conversion.'
)
self.msg.exec_()
else:
self.msg = QtWidgets.QErrorMessage()
self.msg.setModal(True)
self.msg.setWindowTitle("Error Message")
self.msg.showMessage(
'Please select the subcircuit first. You can either create ' +
'new subcircuit or open existing subcircuit'
)
self.msg.exec_()
| __init__ | identifier_name |
Config.js | /**
* @author mrdoob / http://mrdoob.com/
*/
var Config = function () {
var namespace = 'threejs-inspector';
var storage = {
'selectionBoxEnabled': false,
'rafEnabled' : false,
'rafFps' : 30,
}
if ( window.localStorage[ namespace ] === undefined ) | else {
var data = JSON.parse( window.localStorage[ namespace ] );
for ( var key in data ) {
storage[ key ] = data[ key ];
}
}
return {
getKey: function ( key ) {
return storage[ key ];
},
setKey: function () { // key, value, key, value ...
for ( var i = 0, l = arguments.length; i < l; i += 2 ) {
storage[ arguments[ i ] ] = arguments[ i + 1 ];
}
window.localStorage[ namespace ] = JSON.stringify( storage );
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' );
},
clear: function () {
delete window.localStorage[ namespace ];
}
}
};
| {
window.localStorage[ namespace ] = JSON.stringify( storage );
} | conditional_block |
Config.js | /**
* @author mrdoob / http://mrdoob.com/
*/
var Config = function () {
var namespace = 'threejs-inspector';
var storage = {
'selectionBoxEnabled': false,
'rafEnabled' : false,
'rafFps' : 30,
}
if ( window.localStorage[ namespace ] === undefined ) {
window.localStorage[ namespace ] = JSON.stringify( storage );
} else {
var data = JSON.parse( window.localStorage[ namespace ] );
for ( var key in data ) {
storage[ key ] = data[ key ];
}
}
return {
getKey: function ( key ) {
return storage[ key ];
},
setKey: function () { // key, value, key, value ...
for ( var i = 0, l = arguments.length; i < l; i += 2 ) {
storage[ arguments[ i ] ] = arguments[ i + 1 ];
} | },
clear: function () {
delete window.localStorage[ namespace ];
}
}
}; |
window.localStorage[ namespace ] = JSON.stringify( storage );
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' );
| random_line_split |
modifDoublon2.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
def sc | ,b, matrix):
if b == '*' :
return -500000000000000000000000000
elif a == '-' :
return 0
elif (a,b) not in matrix:
return matrix[(tuple(reversed((a,b))))]
else:
return matrix[(a,b)]
def modifDoublon2(x,y,z,ldna,offset,doublon,i,q,patternX,patternY):
ATCG = ["A","T","C","G"]
# on commence par déterminer quels acides aminés de x et y sont "ciblés"
aaX = Seq("", IUPAC.protein)
aaY = Seq("", IUPAC.protein)
q_bis = 0.
q_bis += q
if(z<=0):
aaX += x[i]
q_bis /= patternX[i]
else:
aaX += x[i+1+z//3]
q_bis /=patternX[i+1+z//3]
if(z>0):
aaY += y[-i]
q_bis*=patternY[-i]
else:
aaY +=y[-i + z//3]
q_bis*=patternY[-i + z//3]
scores = []
for a in ATCG:
for b in ATCG:
currentDNAx = Seq("", IUPAC.unambiguous_dna)
currentDNAy = Seq("", IUPAC.unambiguous_dna)
currentDNAx += a + b + ldna[doublon+2]
currentaaX = currentDNAx.translate()
currentDNAy += ldna[doublon-1] +a + b
currentaaY = currentDNAy.reverse_complement().translate()
score = score_match(aaX[0].upper(),currentaaX[0].upper(),blosum62)
score += q_bis*score_match(aaY[0].upper(),currentaaY[0].upper(),blosum62)
scores.append(score)
result = scores.index(max(scores))
ldna[doublon] = ATCG[result//4]
ldna[doublon+1]= ATCG[result%4]
| ore_match(a | identifier_name |
modifDoublon2.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
def score_match(a,b, matrix):
if | def modifDoublon2(x,y,z,ldna,offset,doublon,i,q,patternX,patternY):
ATCG = ["A","T","C","G"]
# on commence par déterminer quels acides aminés de x et y sont "ciblés"
aaX = Seq("", IUPAC.protein)
aaY = Seq("", IUPAC.protein)
q_bis = 0.
q_bis += q
if(z<=0):
aaX += x[i]
q_bis /= patternX[i]
else:
aaX += x[i+1+z//3]
q_bis /=patternX[i+1+z//3]
if(z>0):
aaY += y[-i]
q_bis*=patternY[-i]
else:
aaY +=y[-i + z//3]
q_bis*=patternY[-i + z//3]
scores = []
for a in ATCG:
for b in ATCG:
currentDNAx = Seq("", IUPAC.unambiguous_dna)
currentDNAy = Seq("", IUPAC.unambiguous_dna)
currentDNAx += a + b + ldna[doublon+2]
currentaaX = currentDNAx.translate()
currentDNAy += ldna[doublon-1] +a + b
currentaaY = currentDNAy.reverse_complement().translate()
score = score_match(aaX[0].upper(),currentaaX[0].upper(),blosum62)
score += q_bis*score_match(aaY[0].upper(),currentaaY[0].upper(),blosum62)
scores.append(score)
result = scores.index(max(scores))
ldna[doublon] = ATCG[result//4]
ldna[doublon+1]= ATCG[result%4]
| b == '*' :
return -500000000000000000000000000
elif a == '-' :
return 0
elif (a,b) not in matrix:
return matrix[(tuple(reversed((a,b))))]
else:
return matrix[(a,b)]
| identifier_body |
modifDoublon2.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
def score_match(a,b, matrix):
if b == '*' :
return -500000000000000000000000000
elif a == '-' :
return 0
elif (a,b) not in matrix:
return matrix[(tuple(reversed((a,b))))]
else:
return matrix[(a,b)]
def modifDoublon2(x,y,z,ldna,offset,doublon,i,q,patternX,patternY):
ATCG = ["A","T","C","G"]
# on commence par déterminer quels acides aminés de x et y sont "ciblés"
aaX = Seq("", IUPAC.protein)
aaY = Seq("", IUPAC.protein)
q_bis = 0.
q_bis += q
if(z<=0):
aaX += x[i]
q_bis /= patternX[i]
else:
aaX += x[i+1+z//3]
q_bis /=patternX[i+1+z//3]
if(z>0):
aaY += y[-i]
q_bis*=patternY[-i]
else:
aaY +=y[-i + z//3]
q_bis*=patternY[-i + z//3]
scores = [] | currentDNAx += a + b + ldna[doublon+2]
currentaaX = currentDNAx.translate()
currentDNAy += ldna[doublon-1] +a + b
currentaaY = currentDNAy.reverse_complement().translate()
score = score_match(aaX[0].upper(),currentaaX[0].upper(),blosum62)
score += q_bis*score_match(aaY[0].upper(),currentaaY[0].upper(),blosum62)
scores.append(score)
result = scores.index(max(scores))
ldna[doublon] = ATCG[result//4]
ldna[doublon+1]= ATCG[result%4] | for a in ATCG:
for b in ATCG:
currentDNAx = Seq("", IUPAC.unambiguous_dna)
currentDNAy = Seq("", IUPAC.unambiguous_dna) | random_line_split |
modifDoublon2.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
#remarque : Ceci n'est pas une maélioration de modifDoublon,
#c'est une version alternative qui ne s'applique pas aux même doublons.
def score_match(a,b, matrix):
if b == '*' :
return -500000000000000000000000000
elif a == '-' :
return 0
elif (a,b) not in matrix:
return matrix[(tuple(reversed((a,b))))]
else:
return matrix[(a,b)]
def modifDoublon2(x,y,z,ldna,offset,doublon,i,q,patternX,patternY):
ATCG = ["A","T","C","G"]
# on commence par déterminer quels acides aminés de x et y sont "ciblés"
aaX = Seq("", IUPAC.protein)
aaY = Seq("", IUPAC.protein)
q_bis = 0.
q_bis += q
if(z<=0):
aaX += x[i]
q_bis /= patternX[i]
else:
aaX += x[i+1+z//3]
q_bis /=patternX[i+1+z//3]
if(z>0):
aaY += y[-i]
q_bis*=patternY[-i]
else:
aaY + |
scores = []
for a in ATCG:
for b in ATCG:
currentDNAx = Seq("", IUPAC.unambiguous_dna)
currentDNAy = Seq("", IUPAC.unambiguous_dna)
currentDNAx += a + b + ldna[doublon+2]
currentaaX = currentDNAx.translate()
currentDNAy += ldna[doublon-1] +a + b
currentaaY = currentDNAy.reverse_complement().translate()
score = score_match(aaX[0].upper(),currentaaX[0].upper(),blosum62)
score += q_bis*score_match(aaY[0].upper(),currentaaY[0].upper(),blosum62)
scores.append(score)
result = scores.index(max(scores))
ldna[doublon] = ATCG[result//4]
ldna[doublon+1]= ATCG[result%4]
| =y[-i + z//3]
q_bis*=patternY[-i + z//3]
| conditional_block |
index.d.ts | // Type definitions for react-particles-js v3.0.0
// Project: https://github.com/wufe/react-particles-js
// Definitions by: Simone Bembi <https://github.com/wufe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="react" />
import { ComponentClass } from "react";
import { Container } from "tsparticles/Core/Container";
import { ISourceOptions } from "tsparticles";
export type IParticlesParams = ISourceOptions;
export * from 'tsparticles/Enums';
export * from "tsparticles/Plugins/Absorbers/Enums";
export * from "tsparticles/Plugins/Emitters/Enums"; | width?: string;
height?: string;
params?: IParticlesParams;
style?: any;
className?: string;
canvasClassName?: string;
particlesRef?: React.RefObject<Container>;
}
type Particles = ComponentClass<ParticlesProps>;
declare const Particles: Particles;
export default Particles; | export * from "tsparticles/Plugins/PolygonMask/Enums";
export interface ParticlesProps { | random_line_split |
virus_clean.py | # clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""docstring for virus_clean"""
def __init__(self,n_iqd = 5, **kwargs):
'''
parameters
n_std -- number of interquartile distances accepted in molecular clock filter
'''
self.n_iqd = n_iqd
def remove_insertions(self):
'''
remove all columns from the alignment in which the outgroup is gapped
'''
outgroup_ok = np.array(self.sequence_lookup[self.outgroup['strain']])!='-'
for seq in self.viruses:
seq.seq = Seq("".join(np.array(seq.seq)[outgroup_ok]).upper())
def clean_gaps(self):
'''
remove viruses with gaps -- not part of the standard pipeline
'''
self.viruses = filter(lambda x: '-' in x.seq, self.viruses)
def clean_ambiguous(self):
'''
substitute all ambiguous characters with '-',
ancestral inference will interpret this as missing data
'''
for v in self.viruses:
v.seq = Seq(re.sub(r'[BDEFHIJKLMNOPQRSUVWXYZ]', '-',str(v.seq)))
def unique_date(self):
'''
add a unique numerical date to each leaf. uniqueness is achieved adding a small number
'''
from date_util import numerical_date
og = self.sequence_lookup[self.outgroup['strain']]
if hasattr(og, 'date'):
try:
og.num_date = numerical_date(og.date)
except:
print "cannot parse date"
og.num_date="undefined";
for ii, v in enumerate(self.viruses):
if hasattr(v, 'date'):
try:
v.num_date = numerical_date(v.date, self.date_format['fields']) + 1e-7*(ii+1)
except:
print "cannot parse date"
v.num_date="undefined";
def times_from_outgroup(self):
outgroup_date = self.sequence_lookup[self.outgroup['strain']].num_date
return np.array([x.num_date-outgroup_date for x in self.viruses if x.strain])
def distance_from_outgroup(self):
from seq_util import hamming_distance
outgroup_seq = self.sequence_lookup[self.outgroup['strain']].seq
return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain])
def clean_distances(self):
"""Remove viruses that don't follow a loose clock """
times = self.times_from_outgroup()
distances = self.distance_from_outgroup()
slope, intercept, r_value, p_value, std_err = stats.linregress(times, distances)
residuals = slope*times + intercept - distances
r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25)
if self.verbose:
print "\tslope: " + str(slope)
print "\tr: " + str(r_value)
print "\tresiduals iqd: " + str(r_iqd)
new_viruses = []
for (v,r) in izip(self.viruses,residuals):
# filter viruses more than n_std standard devitations up or down
if np.abs(r)<self.n_iqd * r_iqd or v.id == self.outgroup["strain"]:
new_viruses.append(v)
else:
if self.verbose>1:
print "\t\tresidual:", r, "\nremoved ",v.strain
self.viruses = MultipleSeqAlignment(new_viruses)
def clean_generic(self):
| print "Number of viruses before cleaning:",len(self.viruses)
self.unique_date()
self.remove_insertions()
self.clean_ambiguous()
self.clean_distances()
self.viruses.sort(key=lambda x:x.num_date)
print "Number of viruses after outlier filtering:",len(self.viruses) | identifier_body | |
virus_clean.py | # clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""docstring for virus_clean"""
def __init__(self,n_iqd = 5, **kwargs):
'''
parameters
n_std -- number of interquartile distances accepted in molecular clock filter
'''
self.n_iqd = n_iqd
def remove_insertions(self):
'''
remove all columns from the alignment in which the outgroup is gapped
'''
outgroup_ok = np.array(self.sequence_lookup[self.outgroup['strain']])!='-'
for seq in self.viruses:
seq.seq = Seq("".join(np.array(seq.seq)[outgroup_ok]).upper())
def clean_gaps(self):
'''
remove viruses with gaps -- not part of the standard pipeline
'''
self.viruses = filter(lambda x: '-' in x.seq, self.viruses)
def clean_ambiguous(self):
'''
substitute all ambiguous characters with '-',
ancestral inference will interpret this as missing data
'''
for v in self.viruses:
v.seq = Seq(re.sub(r'[BDEFHIJKLMNOPQRSUVWXYZ]', '-',str(v.seq)))
def unique_date(self):
'''
add a unique numerical date to each leaf. uniqueness is achieved adding a small number
'''
from date_util import numerical_date
og = self.sequence_lookup[self.outgroup['strain']]
if hasattr(og, 'date'):
try:
og.num_date = numerical_date(og.date)
except:
print "cannot parse date"
og.num_date="undefined";
for ii, v in enumerate(self.viruses):
if hasattr(v, 'date'):
try:
v.num_date = numerical_date(v.date, self.date_format['fields']) + 1e-7*(ii+1)
except:
print "cannot parse date"
v.num_date="undefined";
def times_from_outgroup(self):
outgroup_date = self.sequence_lookup[self.outgroup['strain']].num_date
return np.array([x.num_date-outgroup_date for x in self.viruses if x.strain])
def | (self):
from seq_util import hamming_distance
outgroup_seq = self.sequence_lookup[self.outgroup['strain']].seq
return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain])
def clean_distances(self):
"""Remove viruses that don't follow a loose clock """
times = self.times_from_outgroup()
distances = self.distance_from_outgroup()
slope, intercept, r_value, p_value, std_err = stats.linregress(times, distances)
residuals = slope*times + intercept - distances
r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25)
if self.verbose:
print "\tslope: " + str(slope)
print "\tr: " + str(r_value)
print "\tresiduals iqd: " + str(r_iqd)
new_viruses = []
for (v,r) in izip(self.viruses,residuals):
# filter viruses more than n_std standard devitations up or down
if np.abs(r)<self.n_iqd * r_iqd or v.id == self.outgroup["strain"]:
new_viruses.append(v)
else:
if self.verbose>1:
print "\t\tresidual:", r, "\nremoved ",v.strain
self.viruses = MultipleSeqAlignment(new_viruses)
def clean_generic(self):
print "Number of viruses before cleaning:",len(self.viruses)
self.unique_date()
self.remove_insertions()
self.clean_ambiguous()
self.clean_distances()
self.viruses.sort(key=lambda x:x.num_date)
print "Number of viruses after outlier filtering:",len(self.viruses)
| distance_from_outgroup | identifier_name |
virus_clean.py | # clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""docstring for virus_clean"""
def __init__(self,n_iqd = 5, **kwargs):
'''
parameters
n_std -- number of interquartile distances accepted in molecular clock filter
'''
self.n_iqd = n_iqd
def remove_insertions(self):
'''
remove all columns from the alignment in which the outgroup is gapped
'''
outgroup_ok = np.array(self.sequence_lookup[self.outgroup['strain']])!='-'
for seq in self.viruses:
seq.seq = Seq("".join(np.array(seq.seq)[outgroup_ok]).upper())
def clean_gaps(self):
'''
remove viruses with gaps -- not part of the standard pipeline
'''
self.viruses = filter(lambda x: '-' in x.seq, self.viruses)
def clean_ambiguous(self):
'''
substitute all ambiguous characters with '-',
ancestral inference will interpret this as missing data
'''
for v in self.viruses:
v.seq = Seq(re.sub(r'[BDEFHIJKLMNOPQRSUVWXYZ]', '-',str(v.seq)))
def unique_date(self):
'''
add a unique numerical date to each leaf. uniqueness is achieved adding a small number
'''
from date_util import numerical_date
og = self.sequence_lookup[self.outgroup['strain']]
if hasattr(og, 'date'):
try:
og.num_date = numerical_date(og.date)
except:
print "cannot parse date"
og.num_date="undefined";
for ii, v in enumerate(self.viruses):
if hasattr(v, 'date'):
try:
v.num_date = numerical_date(v.date, self.date_format['fields']) + 1e-7*(ii+1)
except:
print "cannot parse date"
v.num_date="undefined";
def times_from_outgroup(self):
outgroup_date = self.sequence_lookup[self.outgroup['strain']].num_date
return np.array([x.num_date-outgroup_date for x in self.viruses if x.strain])
def distance_from_outgroup(self):
from seq_util import hamming_distance
outgroup_seq = self.sequence_lookup[self.outgroup['strain']].seq
return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain])
def clean_distances(self):
"""Remove viruses that don't follow a loose clock """
times = self.times_from_outgroup()
distances = self.distance_from_outgroup()
slope, intercept, r_value, p_value, std_err = stats.linregress(times, distances)
residuals = slope*times + intercept - distances
r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25)
if self.verbose:
print "\tslope: " + str(slope)
print "\tr: " + str(r_value)
print "\tresiduals iqd: " + str(r_iqd)
new_viruses = []
for (v,r) in izip(self.viruses,residuals):
# filter viruses more than n_std standard devitations up or down
if np.abs(r)<self.n_iqd * r_iqd or v.id == self.outgroup["strain"]:
new_viruses.append(v)
else:
if self.verbose>1:
|
self.viruses = MultipleSeqAlignment(new_viruses)
def clean_generic(self):
print "Number of viruses before cleaning:",len(self.viruses)
self.unique_date()
self.remove_insertions()
self.clean_ambiguous()
self.clean_distances()
self.viruses.sort(key=lambda x:x.num_date)
print "Number of viruses after outlier filtering:",len(self.viruses)
| print "\t\tresidual:", r, "\nremoved ",v.strain | conditional_block |
virus_clean.py | # clean sequences after alignment, criteria based on sequences
# make inline with canonical ordering (no extra gaps)
import os, datetime, time, re
from itertools import izip
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from scipy import stats
import numpy as np
class virus_clean(object):
"""docstring for virus_clean"""
def __init__(self,n_iqd = 5, **kwargs):
'''
parameters
n_std -- number of interquartile distances accepted in molecular clock filter
'''
self.n_iqd = n_iqd
def remove_insertions(self):
'''
remove all columns from the alignment in which the outgroup is gapped
'''
outgroup_ok = np.array(self.sequence_lookup[self.outgroup['strain']])!='-'
for seq in self.viruses:
seq.seq = Seq("".join(np.array(seq.seq)[outgroup_ok]).upper())
def clean_gaps(self):
'''
remove viruses with gaps -- not part of the standard pipeline
'''
self.viruses = filter(lambda x: '-' in x.seq, self.viruses)
def clean_ambiguous(self):
'''
substitute all ambiguous characters with '-', | for v in self.viruses:
v.seq = Seq(re.sub(r'[BDEFHIJKLMNOPQRSUVWXYZ]', '-',str(v.seq)))
def unique_date(self):
'''
add a unique numerical date to each leaf. uniqueness is achieved adding a small number
'''
from date_util import numerical_date
og = self.sequence_lookup[self.outgroup['strain']]
if hasattr(og, 'date'):
try:
og.num_date = numerical_date(og.date)
except:
print "cannot parse date"
og.num_date="undefined";
for ii, v in enumerate(self.viruses):
if hasattr(v, 'date'):
try:
v.num_date = numerical_date(v.date, self.date_format['fields']) + 1e-7*(ii+1)
except:
print "cannot parse date"
v.num_date="undefined";
def times_from_outgroup(self):
outgroup_date = self.sequence_lookup[self.outgroup['strain']].num_date
return np.array([x.num_date-outgroup_date for x in self.viruses if x.strain])
def distance_from_outgroup(self):
from seq_util import hamming_distance
outgroup_seq = self.sequence_lookup[self.outgroup['strain']].seq
return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain])
def clean_distances(self):
"""Remove viruses that don't follow a loose clock """
times = self.times_from_outgroup()
distances = self.distance_from_outgroup()
slope, intercept, r_value, p_value, std_err = stats.linregress(times, distances)
residuals = slope*times + intercept - distances
r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25)
if self.verbose:
print "\tslope: " + str(slope)
print "\tr: " + str(r_value)
print "\tresiduals iqd: " + str(r_iqd)
new_viruses = []
for (v,r) in izip(self.viruses,residuals):
# filter viruses more than n_std standard devitations up or down
if np.abs(r)<self.n_iqd * r_iqd or v.id == self.outgroup["strain"]:
new_viruses.append(v)
else:
if self.verbose>1:
print "\t\tresidual:", r, "\nremoved ",v.strain
self.viruses = MultipleSeqAlignment(new_viruses)
def clean_generic(self):
print "Number of viruses before cleaning:",len(self.viruses)
self.unique_date()
self.remove_insertions()
self.clean_ambiguous()
self.clean_distances()
self.viruses.sort(key=lambda x:x.num_date)
print "Number of viruses after outlier filtering:",len(self.viruses) | ancestral inference will interpret this as missing data
''' | random_line_split |
macro_parser.rs | // Copyright 2012-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.
//! This is an Earley-like parser, without support for in-grammar nonterminals,
//! only by calling out to the main rust parser for named nonterminals (which it
//! commits to fully when it hits one in a grammar). This means that there are no
//! completer or predictor rules, and therefore no need to store one column per
//! token: instead, there's a set of current Earley items and a set of next
//! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
//! pathological cases, is worse than traditional Earley parsing, but it's an
//! easier fit for Macro-by-Example-style rules, and I think the overhead is
//! lower. (In order to prevent the pathological case, we'd need to lazily
//! construct the resulting `NamedMatch`es at the very end. It'd be a pain,
//! and require more memory to keep around old items, but it would also save
//! overhead)
//!
//! Quick intro to how the parser works:
//!
//! A 'position' is a dot in the middle of a matcher, usually represented as a
//! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
//!
//! The parser walks through the input a character at a time, maintaining a list
//! of items consistent with the current position in the input string: `cur_eis`.
//!
//! As it processes them, it fills up `eof_eis` with items that would be valid if
//! the macro invocation is now over, `bb_eis` with items that are waiting on
//! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting
//! on the a particular token. Most of the logic concerns moving the · through the
//! repetitions indicated by Kleene stars. It only advances or calls out to the
//! real Rust parser when no `cur_eis` items remain
//!
//! Example: Start parsing `a a a a b` against [· a $( a )* a b].
//!
//! Remaining input: `a a a a b`
//! next_eis: [· a $( a )* a b]
//!
//! - - - Advance over an `a`. - - -
//!
//! Remaining input: `a a a b`
//! cur: [a · $( a )* a b]
//! Descend/Skip (first item).
//! next: [a $( · a )* a b] [a $( a )* · a b].
//!
//! - - - Advance over an `a`. - - -
//!
//! Remaining input: `a a b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
//!
//! - - - Advance over an `a`. - - - (this looks exactly like the last step)
//!
//! Remaining input: `a b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
//!
//! - - - Advance over an `a`. - - - (this looks exactly like the last step)
//!
//! Remaining input: `b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a `b`. - - -
//!
//! Remaining input: ``
//! eof: [a $( a )* a b ·]
pub use self::NamedMatch::*;
pub use self::ParseResult::*;
use self::TokenTreeOrTokenTreeVec::*;
use ast;
use ast::{TokenTree, Ident};
use ast::{TtDelimited, TtSequence, TtToken};
use codemap::{BytePos, mk_sp, Span};
use codemap;
use parse::lexer::*; //resolve bug?
use parse::ParseSess;
use parse::attr::ParserAttr;
use parse::parser::{LifetimeAndTypesWithoutColons, Parser};
use parse::token::{Eof, DocComment, MatchNt, SubstNt};
use parse::token::{Token, Nonterminal};
use parse::token;
use print::pprust;
use ptr::P;
use std::mem;
use std::rc::Rc;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
// To avoid costly uniqueness checks, we require that `MatchSeq` always has
// a nonempty body.
#[derive(Clone)]
enum TokenTreeOrTokenTreeVec {
Tt(ast::TokenTree),
TtSeq(Rc<Vec<ast::TokenTree>>),
}
impl TokenTreeOrTokenTreeVec {
fn len(&self) -> usize {
match self {
&TtSeq(ref v) => v.len(),
&Tt(ref tt) => tt.len(),
}
}
fn get_tt(&self, index: usize) -> TokenTree {
match self {
&TtSeq(ref v) => v[index].clone(),
&Tt(ref tt) => tt.get_tt(index),
}
}
}
/// an unzipping of `TokenTree`s
#[derive(Clone)]
struct MatcherTtFrame {
elts: TokenTreeOrTokenTreeVec,
idx: usize,
}
#[derive(Clone)]
pub struct MatcherPos {
stack: | erTtFrame>,
top_elts: TokenTreeOrTokenTreeVec,
sep: Option<Token>,
idx: usize,
up: Option<Box<MatcherPos>>,
matches: Vec<Vec<Rc<NamedMatch>>>,
match_lo: usize,
match_cur: usize,
match_hi: usize,
sp_lo: BytePos,
}
pub fn count_names(ms: &[TokenTree]) -> usize {
ms.iter().fold(0, |count, elt| {
count + match elt {
&TtSequence(_, ref seq) => {
seq.num_captures
}
&TtDelimited(_, ref delim) => {
count_names(&delim.tts)
}
&TtToken(_, MatchNt(..)) => {
1
}
&TtToken(_, _) => 0,
}
})
}
pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos)
-> Box<MatcherPos> {
let match_idx_hi = count_names(&ms[..]);
let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect();
Box::new(MatcherPos {
stack: vec![],
top_elts: TtSeq(ms),
sep: sep,
idx: 0,
up: None,
matches: matches,
match_lo: 0,
match_cur: 0,
match_hi: match_idx_hi,
sp_lo: lo
})
}
/// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL:
/// so it is associated with a single ident in a parse, and all
/// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type
/// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a
/// single token::MATCH_NONTERMINAL in the TokenTree that produced it.
///
/// The in-memory structure of a particular NamedMatch represents the match
/// that occurred when a particular subset of a matcher was applied to a
/// particular token tree.
///
/// The width of each MatchedSeq in the NamedMatch, and the identity of the
/// `MatchedNonterminal`s, will depend on the token tree it was applied to:
/// each MatchedSeq corresponds to a single TTSeq in the originating
/// token tree. The depth of the NamedMatch structure will therefore depend
/// only on the nesting depth of `ast::TTSeq`s in the originating
/// token tree it was derived from.
pub enum NamedMatch {
MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span),
MatchedNonterminal(Nonterminal)
}
pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>])
-> HashMap<Ident, Rc<NamedMatch>> {
fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>],
ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) {
match m {
&TtSequence(_, ref seq) => {
for next_m in &seq.tts {
n_rec(p_s, next_m, res, ret_val, idx)
}
}
&TtDelimited(_, ref delim) => {
for next_m in &delim.tts {
n_rec(p_s, next_m, res, ret_val, idx)
}
}
&TtToken(sp, MatchNt(bind_name, _, _, _)) => {
match ret_val.entry(bind_name) {
Vacant(spot) => {
spot.insert(res[*idx].clone());
*idx += 1;
}
Occupied(..) => {
let string = token::get_ident(bind_name);
panic!(p_s.span_diagnostic
.span_fatal(sp,
&format!("duplicated bind name: {}",
&string)))
}
}
}
&TtToken(_, SubstNt(..)) => panic!("Cannot fill in a NT"),
&TtToken(_, _) => (),
}
}
let mut ret_val = HashMap::new();
let mut idx = 0;
for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) }
ret_val
}
pub enum ParseResult<T> {
Success(T),
Failure(codemap::Span, String),
Error(codemap::Span, String)
}
pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>;
pub fn parse_or_else(sess: &ParseSess,
cfg: ast::CrateConfig,
rdr: TtReader,
ms: Vec<TokenTree> )
-> HashMap<Ident, Rc<NamedMatch>> {
match parse(sess, cfg, rdr, &ms[..]) {
Success(m) => m,
Failure(sp, str) => {
panic!(sess.span_diagnostic.span_fatal(sp, &str[..]))
}
Error(sp, str) => {
panic!(sess.span_diagnostic.span_fatal(sp, &str[..]))
}
}
}
/// Perform a token equality check, ignoring syntax context (that is, an
/// unhygienic comparison)
pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
match (t1,t2) {
(&token::Ident(id1,_),&token::Ident(id2,_))
| (&token::Lifetime(id1),&token::Lifetime(id2)) =>
id1.name == id2.name,
_ => *t1 == *t2
}
}
pub fn parse(sess: &ParseSess,
cfg: ast::CrateConfig,
mut rdr: TtReader,
ms: &[TokenTree])
-> NamedParseResult {
let mut cur_eis = Vec::new();
cur_eis.push(initial_matcher_pos(Rc::new(ms.iter()
.cloned()
.collect()),
None,
rdr.peek().sp.lo));
loop {
let mut bb_eis = Vec::new(); // black-box parsed by parser.rs
let mut next_eis = Vec::new(); // or proceed normally
let mut eof_eis = Vec::new();
let TokenAndSpan { tok, sp } = rdr.peek();
/* we append new items to this while we go */
loop {
let mut ei = match cur_eis.pop() {
None => break, /* for each Earley Item */
Some(ei) => ei,
};
// When unzipped trees end, remove them
while ei.idx >= ei.top_elts.len() {
match ei.stack.pop() {
Some(MatcherTtFrame { elts, idx }) => {
ei.top_elts = elts;
ei.idx = idx + 1;
}
None => break
}
}
let idx = ei.idx;
let len = ei.top_elts.len();
/* at end of sequence */
if idx >= len {
// can't move out of `match`es, so:
if ei.up.is_some() {
// hack: a matcher sequence is repeating iff it has a
// parent (the top level is just a container)
// disregard separator, try to go up
// (remove this condition to make trailing seps ok)
if idx == len {
// pop from the matcher position
let mut new_pos = ei.up.clone().unwrap();
// update matches (the MBE "parse tree") by appending
// each tree as a subtree.
// I bet this is a perf problem: we're preemptively
// doing a lot of array work that will get thrown away
// most of the time.
// Only touch the binders we have actually bound
for idx in ei.match_lo..ei.match_hi {
let sub = (ei.matches[idx]).clone();
(&mut new_pos.matches[idx])
.push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo,
sp.hi))));
}
new_pos.match_cur = ei.match_hi;
new_pos.idx += 1;
cur_eis.push(new_pos);
}
// can we go around again?
// the *_t vars are workarounds for the lack of unary move
match ei.sep {
Some(ref t) if idx == len => { // we need a separator
// i'm conflicted about whether this should be hygienic....
// though in this case, if the separators are never legal
// idents, it shouldn't matter.
if token_name_eq(&tok, t) { //pass the separator
let mut ei_t = ei.clone();
// ei_t.match_cur = ei_t.match_lo;
ei_t.idx += 1;
next_eis.push(ei_t);
}
}
_ => { // we don't need a separator
let mut ei_t = ei;
ei_t.match_cur = ei_t.match_lo;
ei_t.idx = 0;
cur_eis.push(ei_t);
}
}
} else {
eof_eis.push(ei);
}
} else {
match ei.top_elts.get_tt(idx) {
/* need to descend into sequence */
TtSequence(sp, seq) => {
if seq.op == ast::ZeroOrMore {
let mut new_ei = ei.clone();
new_ei.match_cur += seq.num_captures;
new_ei.idx += 1;
//we specifically matched zero repeats.
for idx in ei.match_cur..ei.match_cur + seq.num_captures {
(&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp)));
}
cur_eis.push(new_ei);
}
let matches: Vec<_> = (0..ei.matches.len())
.map(|_| Vec::new()).collect();
let ei_t = ei;
cur_eis.push(Box::new(MatcherPos {
stack: vec![],
sep: seq.separator.clone(),
idx: 0,
matches: matches,
match_lo: ei_t.match_cur,
match_cur: ei_t.match_cur,
match_hi: ei_t.match_cur + seq.num_captures,
up: Some(ei_t),
sp_lo: sp.lo,
top_elts: Tt(TtSequence(sp, seq)),
}));
}
TtToken(_, MatchNt(..)) => {
// Built-in nonterminals never start with these tokens,
// so we can eliminate them from consideration.
match tok {
token::CloseDelim(_) => {},
_ => bb_eis.push(ei),
}
}
TtToken(sp, SubstNt(..)) => {
return Error(sp, "Cannot transcribe in macro LHS".to_string())
}
seq @ TtDelimited(..) | seq @ TtToken(_, DocComment(..)) => {
let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq));
let idx = ei.idx;
ei.stack.push(MatcherTtFrame {
elts: lower_elts,
idx: idx,
});
ei.idx = 0;
cur_eis.push(ei);
}
TtToken(_, ref t) => {
let mut ei_t = ei.clone();
if token_name_eq(t,&tok) {
ei_t.idx += 1;
next_eis.push(ei_t);
}
}
}
}
}
/* error messages here could be improved with links to orig. rules */
if token_name_eq(&tok, &token::Eof) {
if eof_eis.len() == 1 {
let mut v = Vec::new();
for dv in &mut (&mut eof_eis[0]).matches {
v.push(dv.pop().unwrap());
}
return Success(nameize(sess, ms, &v[..]));
} else if eof_eis.len() > 1 {
return Error(sp, "ambiguity: multiple successful parses".to_string());
} else {
return Failure(sp, "unexpected end of macro invocation".to_string());
}
} else {
if (!bb_eis.is_empty() && !next_eis.is_empty())
|| bb_eis.len() > 1 {
let nts = bb_eis.iter().map(|ei| {
match ei.top_elts.get_tt(ei.idx) {
TtToken(_, MatchNt(bind, name, _, _)) => {
(format!("{} ('{}')",
token::get_ident(name),
token::get_ident(bind))).to_string()
}
_ => panic!()
} }).collect::<Vec<String>>().connect(" or ");
return Error(sp, format!(
"local ambiguity: multiple parsing options: \
built-in NTs {} or {} other options.",
nts, next_eis.len()).to_string());
} else if bb_eis.is_empty() && next_eis.is_empty() {
return Failure(sp, format!("no rules expected the token `{}`",
pprust::token_to_string(&tok)).to_string());
} else if !next_eis.is_empty() {
/* Now process the next token */
while !next_eis.is_empty() {
cur_eis.push(next_eis.pop().unwrap());
}
rdr.next_token();
} else /* bb_eis.len() == 1 */ {
let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone()));
let mut ei = bb_eis.pop().unwrap();
match ei.top_elts.get_tt(ei.idx) {
TtToken(span, MatchNt(_, name, _, _)) => {
let name_string = token::get_ident(name);
let match_cur = ei.match_cur;
(&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal(
parse_nt(&mut rust_parser, span, &name_string))));
ei.idx += 1;
ei.match_cur += 1;
}
_ => panic!()
}
cur_eis.push(ei);
for _ in 0..rust_parser.tokens_consumed {
let _ = rdr.next_token();
}
}
}
assert!(!cur_eis.is_empty());
}
}
pub fn parse_nt(p: &mut Parser, sp: Span, name: &str) -> Nonterminal {
match name {
"tt" => {
p.quote_depth += 1; //but in theory, non-quoted tts might be useful
let res = token::NtTT(P(panictry!(p.parse_token_tree())));
p.quote_depth -= 1;
return res;
}
_ => {}
}
// check at the beginning and the parser checks after each bump
panictry!(p.check_unknown_macro_variable());
match name {
"item" => match p.parse_item() {
Some(i) => token::NtItem(i),
None => panic!(p.fatal("expected an item keyword"))
},
"block" => token::NtBlock(panictry!(p.parse_block())),
"stmt" => match p.parse_stmt() {
Some(s) => token::NtStmt(s),
None => panic!(p.fatal("expected a statement"))
},
"pat" => token::NtPat(p.parse_pat()),
"expr" => token::NtExpr(p.parse_expr()),
"ty" => token::NtTy(p.parse_ty()),
// this could be handled like a token, since it is one
"ident" => match p.token {
token::Ident(sn,b) => { panictry!(p.bump()); token::NtIdent(Box::new(sn),b) }
_ => {
let token_str = pprust::token_to_string(&p.token);
panic!(p.fatal(&format!("expected ident, found {}",
&token_str[..])))
}
},
"path" => {
token::NtPath(Box::new(panictry!(p.parse_path(LifetimeAndTypesWithoutColons))))
}
"meta" => token::NtMeta(p.parse_meta_item()),
_ => {
panic!(p.span_fatal_help(sp,
&format!("invalid fragment specifier `{}`", name),
"valid fragment specifiers are `ident`, `block`, \
`stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \
and `item`"))
}
}
}
| Vec<Match | identifier_name |
macro_parser.rs | // Copyright 2012-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.
//! This is an Earley-like parser, without support for in-grammar nonterminals,
//! only by calling out to the main rust parser for named nonterminals (which it
//! commits to fully when it hits one in a grammar). This means that there are no
//! completer or predictor rules, and therefore no need to store one column per
//! token: instead, there's a set of current Earley items and a set of next
//! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
//! pathological cases, is worse than traditional Earley parsing, but it's an
//! easier fit for Macro-by-Example-style rules, and I think the overhead is
//! lower. (In order to prevent the pathological case, we'd need to lazily
//! construct the resulting `NamedMatch`es at the very end. It'd be a pain,
//! and require more memory to keep around old items, but it would also save
//! overhead)
//!
//! Quick intro to how the parser works:
//!
//! A 'position' is a dot in the middle of a matcher, usually represented as a
//! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
//!
//! The parser walks through the input a character at a time, maintaining a list
//! of items consistent with the current position in the input string: `cur_eis`.
//!
//! As it processes them, it fills up `eof_eis` with items that would be valid if
//! the macro invocation is now over, `bb_eis` with items that are waiting on
//! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting
//! on the a particular token. Most of the logic concerns moving the · through the
//! repetitions indicated by Kleene stars. It only advances or calls out to the
//! real Rust parser when no `cur_eis` items remain
//!
//! Example: Start parsing `a a a a b` against [· a $( a )* a b].
//!
//! Remaining input: `a a a a b`
//! next_eis: [· a $( a )* a b]
//!
//! - - - Advance over an `a`. - - -
//!
//! Remaining input: `a a a b`
//! cur: [a · $( a )* a b]
//! Descend/Skip (first item).
//! next: [a $( · a )* a b] [a $( a )* · a b].
//!
//! - - - Advance over an `a`. - - -
//!
//! Remaining input: `a a b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
//!
//! - - - Advance over an `a`. - - - (this looks exactly like the last step)
//!
//! Remaining input: `a b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
//!
//! - - - Advance over an `a`. - - - (this looks exactly like the last step)
//!
//! Remaining input: `b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a `b`. - - -
//!
//! Remaining input: ``
//! eof: [a $( a )* a b ·]
pub use self::NamedMatch::*;
pub use self::ParseResult::*;
use self::TokenTreeOrTokenTreeVec::*;
use ast;
use ast::{TokenTree, Ident};
use ast::{TtDelimited, TtSequence, TtToken};
use codemap::{BytePos, mk_sp, Span};
use codemap;
use parse::lexer::*; //resolve bug?
use parse::ParseSess;
use parse::attr::ParserAttr;
use parse::parser::{LifetimeAndTypesWithoutColons, Parser};
use parse::token::{Eof, DocComment, MatchNt, SubstNt};
use parse::token::{Token, Nonterminal};
use parse::token;
use print::pprust;
use ptr::P;
use std::mem;
use std::rc::Rc;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
// To avoid costly uniqueness checks, we require that `MatchSeq` always has
// a nonempty body.
#[derive(Clone)]
enum TokenTreeOrTokenTreeVec {
Tt(ast::TokenTree),
TtSeq(Rc<Vec<ast::TokenTree>>),
}
impl TokenTreeOrTokenTreeVec {
fn len(&self) -> usize {
match self {
&TtSeq(ref v) => v.len(),
&Tt(ref tt) => tt.len(),
}
}
fn get_tt(&self, index: usize) -> TokenTree {
match self {
&TtSeq(ref v) => v[index].clone(),
&Tt(ref tt) => tt.get_tt(index),
}
}
}
/// an unzipping of `TokenTree`s
#[derive(Clone)]
struct MatcherTtFrame {
elts: TokenTreeOrTokenTreeVec,
idx: usize,
}
#[derive(Clone)]
pub struct MatcherPos {
stack: Vec<MatcherTtFrame>,
top_elts: TokenTreeOrTokenTreeVec,
sep: Option<Token>,
idx: usize,
up: Option<Box<MatcherPos>>,
matches: Vec<Vec<Rc<NamedMatch>>>,
match_lo: usize,
match_cur: usize,
match_hi: usize,
sp_lo: BytePos,
}
pub fn count_names(ms: &[TokenTree]) -> usize {
ms.iter().fold(0, | r_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos)
-> Box<MatcherPos> {
let match_idx_hi = count_names(&ms[..]);
let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect();
Box::new(MatcherPos {
stack: vec![],
top_elts: TtSeq(ms),
sep: sep,
idx: 0,
up: None,
matches: matches,
match_lo: 0,
match_cur: 0,
match_hi: match_idx_hi,
sp_lo: lo
})
}
/// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL:
/// so it is associated with a single ident in a parse, and all
/// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type
/// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a
/// single token::MATCH_NONTERMINAL in the TokenTree that produced it.
///
/// The in-memory structure of a particular NamedMatch represents the match
/// that occurred when a particular subset of a matcher was applied to a
/// particular token tree.
///
/// The width of each MatchedSeq in the NamedMatch, and the identity of the
/// `MatchedNonterminal`s, will depend on the token tree it was applied to:
/// each MatchedSeq corresponds to a single TTSeq in the originating
/// token tree. The depth of the NamedMatch structure will therefore depend
/// only on the nesting depth of `ast::TTSeq`s in the originating
/// token tree it was derived from.
pub enum NamedMatch {
MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span),
MatchedNonterminal(Nonterminal)
}
pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>])
-> HashMap<Ident, Rc<NamedMatch>> {
fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>],
ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) {
match m {
&TtSequence(_, ref seq) => {
for next_m in &seq.tts {
n_rec(p_s, next_m, res, ret_val, idx)
}
}
&TtDelimited(_, ref delim) => {
for next_m in &delim.tts {
n_rec(p_s, next_m, res, ret_val, idx)
}
}
&TtToken(sp, MatchNt(bind_name, _, _, _)) => {
match ret_val.entry(bind_name) {
Vacant(spot) => {
spot.insert(res[*idx].clone());
*idx += 1;
}
Occupied(..) => {
let string = token::get_ident(bind_name);
panic!(p_s.span_diagnostic
.span_fatal(sp,
&format!("duplicated bind name: {}",
&string)))
}
}
}
&TtToken(_, SubstNt(..)) => panic!("Cannot fill in a NT"),
&TtToken(_, _) => (),
}
}
let mut ret_val = HashMap::new();
let mut idx = 0;
for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) }
ret_val
}
pub enum ParseResult<T> {
Success(T),
Failure(codemap::Span, String),
Error(codemap::Span, String)
}
pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>;
pub fn parse_or_else(sess: &ParseSess,
cfg: ast::CrateConfig,
rdr: TtReader,
ms: Vec<TokenTree> )
-> HashMap<Ident, Rc<NamedMatch>> {
match parse(sess, cfg, rdr, &ms[..]) {
Success(m) => m,
Failure(sp, str) => {
panic!(sess.span_diagnostic.span_fatal(sp, &str[..]))
}
Error(sp, str) => {
panic!(sess.span_diagnostic.span_fatal(sp, &str[..]))
}
}
}
/// Perform a token equality check, ignoring syntax context (that is, an
/// unhygienic comparison)
pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
match (t1,t2) {
(&token::Ident(id1,_),&token::Ident(id2,_))
| (&token::Lifetime(id1),&token::Lifetime(id2)) =>
id1.name == id2.name,
_ => *t1 == *t2
}
}
pub fn parse(sess: &ParseSess,
cfg: ast::CrateConfig,
mut rdr: TtReader,
ms: &[TokenTree])
-> NamedParseResult {
let mut cur_eis = Vec::new();
cur_eis.push(initial_matcher_pos(Rc::new(ms.iter()
.cloned()
.collect()),
None,
rdr.peek().sp.lo));
loop {
let mut bb_eis = Vec::new(); // black-box parsed by parser.rs
let mut next_eis = Vec::new(); // or proceed normally
let mut eof_eis = Vec::new();
let TokenAndSpan { tok, sp } = rdr.peek();
/* we append new items to this while we go */
loop {
let mut ei = match cur_eis.pop() {
None => break, /* for each Earley Item */
Some(ei) => ei,
};
// When unzipped trees end, remove them
while ei.idx >= ei.top_elts.len() {
match ei.stack.pop() {
Some(MatcherTtFrame { elts, idx }) => {
ei.top_elts = elts;
ei.idx = idx + 1;
}
None => break
}
}
let idx = ei.idx;
let len = ei.top_elts.len();
/* at end of sequence */
if idx >= len {
// can't move out of `match`es, so:
if ei.up.is_some() {
// hack: a matcher sequence is repeating iff it has a
// parent (the top level is just a container)
// disregard separator, try to go up
// (remove this condition to make trailing seps ok)
if idx == len {
// pop from the matcher position
let mut new_pos = ei.up.clone().unwrap();
// update matches (the MBE "parse tree") by appending
// each tree as a subtree.
// I bet this is a perf problem: we're preemptively
// doing a lot of array work that will get thrown away
// most of the time.
// Only touch the binders we have actually bound
for idx in ei.match_lo..ei.match_hi {
let sub = (ei.matches[idx]).clone();
(&mut new_pos.matches[idx])
.push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo,
sp.hi))));
}
new_pos.match_cur = ei.match_hi;
new_pos.idx += 1;
cur_eis.push(new_pos);
}
// can we go around again?
// the *_t vars are workarounds for the lack of unary move
match ei.sep {
Some(ref t) if idx == len => { // we need a separator
// i'm conflicted about whether this should be hygienic....
// though in this case, if the separators are never legal
// idents, it shouldn't matter.
if token_name_eq(&tok, t) { //pass the separator
let mut ei_t = ei.clone();
// ei_t.match_cur = ei_t.match_lo;
ei_t.idx += 1;
next_eis.push(ei_t);
}
}
_ => { // we don't need a separator
let mut ei_t = ei;
ei_t.match_cur = ei_t.match_lo;
ei_t.idx = 0;
cur_eis.push(ei_t);
}
}
} else {
eof_eis.push(ei);
}
} else {
match ei.top_elts.get_tt(idx) {
/* need to descend into sequence */
TtSequence(sp, seq) => {
if seq.op == ast::ZeroOrMore {
let mut new_ei = ei.clone();
new_ei.match_cur += seq.num_captures;
new_ei.idx += 1;
//we specifically matched zero repeats.
for idx in ei.match_cur..ei.match_cur + seq.num_captures {
(&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp)));
}
cur_eis.push(new_ei);
}
let matches: Vec<_> = (0..ei.matches.len())
.map(|_| Vec::new()).collect();
let ei_t = ei;
cur_eis.push(Box::new(MatcherPos {
stack: vec![],
sep: seq.separator.clone(),
idx: 0,
matches: matches,
match_lo: ei_t.match_cur,
match_cur: ei_t.match_cur,
match_hi: ei_t.match_cur + seq.num_captures,
up: Some(ei_t),
sp_lo: sp.lo,
top_elts: Tt(TtSequence(sp, seq)),
}));
}
TtToken(_, MatchNt(..)) => {
// Built-in nonterminals never start with these tokens,
// so we can eliminate them from consideration.
match tok {
token::CloseDelim(_) => {},
_ => bb_eis.push(ei),
}
}
TtToken(sp, SubstNt(..)) => {
return Error(sp, "Cannot transcribe in macro LHS".to_string())
}
seq @ TtDelimited(..) | seq @ TtToken(_, DocComment(..)) => {
let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq));
let idx = ei.idx;
ei.stack.push(MatcherTtFrame {
elts: lower_elts,
idx: idx,
});
ei.idx = 0;
cur_eis.push(ei);
}
TtToken(_, ref t) => {
let mut ei_t = ei.clone();
if token_name_eq(t,&tok) {
ei_t.idx += 1;
next_eis.push(ei_t);
}
}
}
}
}
/* error messages here could be improved with links to orig. rules */
if token_name_eq(&tok, &token::Eof) {
if eof_eis.len() == 1 {
let mut v = Vec::new();
for dv in &mut (&mut eof_eis[0]).matches {
v.push(dv.pop().unwrap());
}
return Success(nameize(sess, ms, &v[..]));
} else if eof_eis.len() > 1 {
return Error(sp, "ambiguity: multiple successful parses".to_string());
} else {
return Failure(sp, "unexpected end of macro invocation".to_string());
}
} else {
if (!bb_eis.is_empty() && !next_eis.is_empty())
|| bb_eis.len() > 1 {
let nts = bb_eis.iter().map(|ei| {
match ei.top_elts.get_tt(ei.idx) {
TtToken(_, MatchNt(bind, name, _, _)) => {
(format!("{} ('{}')",
token::get_ident(name),
token::get_ident(bind))).to_string()
}
_ => panic!()
} }).collect::<Vec<String>>().connect(" or ");
return Error(sp, format!(
"local ambiguity: multiple parsing options: \
built-in NTs {} or {} other options.",
nts, next_eis.len()).to_string());
} else if bb_eis.is_empty() && next_eis.is_empty() {
return Failure(sp, format!("no rules expected the token `{}`",
pprust::token_to_string(&tok)).to_string());
} else if !next_eis.is_empty() {
/* Now process the next token */
while !next_eis.is_empty() {
cur_eis.push(next_eis.pop().unwrap());
}
rdr.next_token();
} else /* bb_eis.len() == 1 */ {
let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone()));
let mut ei = bb_eis.pop().unwrap();
match ei.top_elts.get_tt(ei.idx) {
TtToken(span, MatchNt(_, name, _, _)) => {
let name_string = token::get_ident(name);
let match_cur = ei.match_cur;
(&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal(
parse_nt(&mut rust_parser, span, &name_string))));
ei.idx += 1;
ei.match_cur += 1;
}
_ => panic!()
}
cur_eis.push(ei);
for _ in 0..rust_parser.tokens_consumed {
let _ = rdr.next_token();
}
}
}
assert!(!cur_eis.is_empty());
}
}
pub fn parse_nt(p: &mut Parser, sp: Span, name: &str) -> Nonterminal {
match name {
"tt" => {
p.quote_depth += 1; //but in theory, non-quoted tts might be useful
let res = token::NtTT(P(panictry!(p.parse_token_tree())));
p.quote_depth -= 1;
return res;
}
_ => {}
}
// check at the beginning and the parser checks after each bump
panictry!(p.check_unknown_macro_variable());
match name {
"item" => match p.parse_item() {
Some(i) => token::NtItem(i),
None => panic!(p.fatal("expected an item keyword"))
},
"block" => token::NtBlock(panictry!(p.parse_block())),
"stmt" => match p.parse_stmt() {
Some(s) => token::NtStmt(s),
None => panic!(p.fatal("expected a statement"))
},
"pat" => token::NtPat(p.parse_pat()),
"expr" => token::NtExpr(p.parse_expr()),
"ty" => token::NtTy(p.parse_ty()),
// this could be handled like a token, since it is one
"ident" => match p.token {
token::Ident(sn,b) => { panictry!(p.bump()); token::NtIdent(Box::new(sn),b) }
_ => {
let token_str = pprust::token_to_string(&p.token);
panic!(p.fatal(&format!("expected ident, found {}",
&token_str[..])))
}
},
"path" => {
token::NtPath(Box::new(panictry!(p.parse_path(LifetimeAndTypesWithoutColons))))
}
"meta" => token::NtMeta(p.parse_meta_item()),
_ => {
panic!(p.span_fatal_help(sp,
&format!("invalid fragment specifier `{}`", name),
"valid fragment specifiers are `ident`, `block`, \
`stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \
and `item`"))
}
}
}
| |count, elt| {
count + match elt {
&TtSequence(_, ref seq) => {
seq.num_captures
}
&TtDelimited(_, ref delim) => {
count_names(&delim.tts)
}
&TtToken(_, MatchNt(..)) => {
1
}
&TtToken(_, _) => 0,
}
})
}
pub fn initial_matche | identifier_body |
macro_parser.rs | // Copyright 2012-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.
//! This is an Earley-like parser, without support for in-grammar nonterminals,
//! only by calling out to the main rust parser for named nonterminals (which it
//! commits to fully when it hits one in a grammar). This means that there are no
//! completer or predictor rules, and therefore no need to store one column per
//! token: instead, there's a set of current Earley items and a set of next
//! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
//! pathological cases, is worse than traditional Earley parsing, but it's an
//! easier fit for Macro-by-Example-style rules, and I think the overhead is
//! lower. (In order to prevent the pathological case, we'd need to lazily
//! construct the resulting `NamedMatch`es at the very end. It'd be a pain,
//! and require more memory to keep around old items, but it would also save
//! overhead)
//!
//! Quick intro to how the parser works:
//!
//! A 'position' is a dot in the middle of a matcher, usually represented as a
//! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
//!
//! The parser walks through the input a character at a time, maintaining a list
//! of items consistent with the current position in the input string: `cur_eis`.
//!
//! As it processes them, it fills up `eof_eis` with items that would be valid if
//! the macro invocation is now over, `bb_eis` with items that are waiting on
//! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting
//! on the a particular token. Most of the logic concerns moving the · through the
//! repetitions indicated by Kleene stars. It only advances or calls out to the
//! real Rust parser when no `cur_eis` items remain
//!
//! Example: Start parsing `a a a a b` against [· a $( a )* a b].
//!
//! Remaining input: `a a a a b`
//! next_eis: [· a $( a )* a b]
//!
//! - - - Advance over an `a`. - - -
//!
//! Remaining input: `a a a b`
//! cur: [a · $( a )* a b]
//! Descend/Skip (first item).
//! next: [a $( · a )* a b] [a $( a )* · a b].
//!
//! - - - Advance over an `a`. - - -
//!
//! Remaining input: `a a b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
//!
//! - - - Advance over an `a`. - - - (this looks exactly like the last step)
//!
//! Remaining input: `a b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
//!
//! - - - Advance over an `a`. - - - (this looks exactly like the last step)
//!
//! Remaining input: `b`
//! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b]
//!
//! - - - Advance over a `b`. - - -
//!
//! Remaining input: ``
//! eof: [a $( a )* a b ·]
pub use self::NamedMatch::*;
pub use self::ParseResult::*;
use self::TokenTreeOrTokenTreeVec::*;
use ast;
use ast::{TokenTree, Ident};
use ast::{TtDelimited, TtSequence, TtToken};
use codemap::{BytePos, mk_sp, Span};
use codemap;
use parse::lexer::*; //resolve bug?
use parse::ParseSess;
use parse::attr::ParserAttr;
use parse::parser::{LifetimeAndTypesWithoutColons, Parser};
use parse::token::{Eof, DocComment, MatchNt, SubstNt};
use parse::token::{Token, Nonterminal};
use parse::token;
use print::pprust;
use ptr::P;
use std::mem;
use std::rc::Rc;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
// To avoid costly uniqueness checks, we require that `MatchSeq` always has
// a nonempty body.
#[derive(Clone)]
enum TokenTreeOrTokenTreeVec {
Tt(ast::TokenTree),
TtSeq(Rc<Vec<ast::TokenTree>>),
}
impl TokenTreeOrTokenTreeVec {
fn len(&self) -> usize {
match self {
&TtSeq(ref v) => v.len(),
&Tt(ref tt) => tt.len(),
}
}
fn get_tt(&self, index: usize) -> TokenTree {
match self {
&TtSeq(ref v) => v[index].clone(),
&Tt(ref tt) => tt.get_tt(index),
}
}
}
/// an unzipping of `TokenTree`s
#[derive(Clone)]
struct MatcherTtFrame {
elts: TokenTreeOrTokenTreeVec,
idx: usize,
}
#[derive(Clone)]
pub struct MatcherPos {
stack: Vec<MatcherTtFrame>,
top_elts: TokenTreeOrTokenTreeVec,
sep: Option<Token>,
idx: usize,
up: Option<Box<MatcherPos>>,
matches: Vec<Vec<Rc<NamedMatch>>>,
match_lo: usize,
match_cur: usize,
match_hi: usize,
sp_lo: BytePos,
}
pub fn count_names(ms: &[TokenTree]) -> usize {
ms.iter().fold(0, |count, elt| {
count + match elt {
&TtSequence(_, ref seq) => {
seq.num_captures
}
&TtDelimited(_, ref delim) => {
count_names(&delim.tts)
}
&TtToken(_, MatchNt(..)) => {
1
}
&TtToken(_, _) => 0,
}
})
}
pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos)
-> Box<MatcherPos> {
let match_idx_hi = count_names(&ms[..]);
let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect();
Box::new(MatcherPos {
stack: vec![],
top_elts: TtSeq(ms),
sep: sep,
idx: 0,
up: None,
matches: matches,
match_lo: 0,
match_cur: 0,
match_hi: match_idx_hi,
sp_lo: lo
})
}
/// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL:
/// so it is associated with a single ident in a parse, and all
/// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type
/// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a
/// single token::MATCH_NONTERMINAL in the TokenTree that produced it.
///
/// The in-memory structure of a particular NamedMatch represents the match
/// that occurred when a particular subset of a matcher was applied to a
/// particular token tree.
///
/// The width of each MatchedSeq in the NamedMatch, and the identity of the
/// `MatchedNonterminal`s, will depend on the token tree it was applied to:
/// each MatchedSeq corresponds to a single TTSeq in the originating
/// token tree. The depth of the NamedMatch structure will therefore depend
/// only on the nesting depth of `ast::TTSeq`s in the originating
/// token tree it was derived from.
pub enum NamedMatch {
MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span),
MatchedNonterminal(Nonterminal)
}
pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>])
-> HashMap<Ident, Rc<NamedMatch>> {
fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>],
ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) {
match m {
&TtSequence(_, ref seq) => {
for next_m in &seq.tts {
n_rec(p_s, next_m, res, ret_val, idx)
}
}
&TtDelimited(_, ref delim) => {
for next_m in &delim.tts {
n_rec(p_s, next_m, res, ret_val, idx)
}
}
&TtToken(sp, MatchNt(bind_name, _, _, _)) => {
match ret_val.entry(bind_name) {
Vacant(spot) => {
spot.insert(res[*idx].clone());
*idx += 1;
}
Occupied(..) => {
let string = token::get_ident(bind_name);
panic!(p_s.span_diagnostic
.span_fatal(sp,
&format!("duplicated bind name: {}",
&string)))
}
}
}
&TtToken(_, SubstNt(..)) => panic!("Cannot fill in a NT"),
&TtToken(_, _) => (),
}
}
let mut ret_val = HashMap::new();
let mut idx = 0;
for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) }
ret_val
}
pub enum ParseResult<T> {
Success(T),
Failure(codemap::Span, String),
Error(codemap::Span, String)
}
pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>;
pub fn parse_or_else(sess: &ParseSess,
cfg: ast::CrateConfig,
rdr: TtReader,
ms: Vec<TokenTree> )
-> HashMap<Ident, Rc<NamedMatch>> {
match parse(sess, cfg, rdr, &ms[..]) {
Success(m) => m,
Failure(sp, str) => {
panic!(sess.span_diagnostic.span_fatal(sp, &str[..]))
}
Error(sp, str) => {
panic!(sess.span_diagnostic.span_fatal(sp, &str[..]))
}
}
}
/// Perform a token equality check, ignoring syntax context (that is, an
/// unhygienic comparison)
pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
match (t1,t2) {
(&token::Ident(id1,_),&token::Ident(id2,_))
| (&token::Lifetime(id1),&token::Lifetime(id2)) =>
id1.name == id2.name,
_ => *t1 == *t2
}
}
pub fn parse(sess: &ParseSess,
cfg: ast::CrateConfig,
mut rdr: TtReader,
ms: &[TokenTree])
-> NamedParseResult {
let mut cur_eis = Vec::new();
cur_eis.push(initial_matcher_pos(Rc::new(ms.iter()
.cloned()
.collect()),
None,
rdr.peek().sp.lo));
loop {
let mut bb_eis = Vec::new(); // black-box parsed by parser.rs
let mut next_eis = Vec::new(); // or proceed normally
let mut eof_eis = Vec::new();
let TokenAndSpan { tok, sp } = rdr.peek();
/* we append new items to this while we go */
loop {
let mut ei = match cur_eis.pop() {
None => break, /* for each Earley Item */
Some(ei) => ei,
};
// When unzipped trees end, remove them
while ei.idx >= ei.top_elts.len() {
match ei.stack.pop() {
Some(MatcherTtFrame { elts, idx }) => {
ei.top_elts = elts;
ei.idx = idx + 1;
}
None => break
}
}
let idx = ei.idx;
let len = ei.top_elts.len();
/* at end of sequence */
if idx >= len {
// can't move out of `match`es, so:
if ei.up.is_some() {
// hack: a matcher sequence is repeating iff it has a
// parent (the top level is just a container)
// disregard separator, try to go up
// (remove this condition to make trailing seps ok)
if idx == len {
// pop from the matcher position
let mut new_pos = ei.up.clone().unwrap();
// update matches (the MBE "parse tree") by appending
// each tree as a subtree.
// I bet this is a perf problem: we're preemptively
// doing a lot of array work that will get thrown away
// most of the time.
// Only touch the binders we have actually bound
for idx in ei.match_lo..ei.match_hi {
let sub = (ei.matches[idx]).clone();
(&mut new_pos.matches[idx])
.push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo,
sp.hi))));
}
new_pos.match_cur = ei.match_hi;
new_pos.idx += 1;
cur_eis.push(new_pos);
}
// can we go around again?
// the *_t vars are workarounds for the lack of unary move
match ei.sep {
Some(ref t) if idx == len => { // we need a separator
// i'm conflicted about whether this should be hygienic....
// though in this case, if the separators are never legal
// idents, it shouldn't matter.
if token_name_eq(&tok, t) { //pass the separator
let mut ei_t = ei.clone();
// ei_t.match_cur = ei_t.match_lo;
ei_t.idx += 1;
next_eis.push(ei_t);
}
}
_ => { // we don't need a separator
let mut ei_t = ei;
ei_t.match_cur = ei_t.match_lo;
ei_t.idx = 0;
cur_eis.push(ei_t);
}
}
} else {
eof_eis.push(ei);
}
} else { | if seq.op == ast::ZeroOrMore {
let mut new_ei = ei.clone();
new_ei.match_cur += seq.num_captures;
new_ei.idx += 1;
//we specifically matched zero repeats.
for idx in ei.match_cur..ei.match_cur + seq.num_captures {
(&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp)));
}
cur_eis.push(new_ei);
}
let matches: Vec<_> = (0..ei.matches.len())
.map(|_| Vec::new()).collect();
let ei_t = ei;
cur_eis.push(Box::new(MatcherPos {
stack: vec![],
sep: seq.separator.clone(),
idx: 0,
matches: matches,
match_lo: ei_t.match_cur,
match_cur: ei_t.match_cur,
match_hi: ei_t.match_cur + seq.num_captures,
up: Some(ei_t),
sp_lo: sp.lo,
top_elts: Tt(TtSequence(sp, seq)),
}));
}
TtToken(_, MatchNt(..)) => {
// Built-in nonterminals never start with these tokens,
// so we can eliminate them from consideration.
match tok {
token::CloseDelim(_) => {},
_ => bb_eis.push(ei),
}
}
TtToken(sp, SubstNt(..)) => {
return Error(sp, "Cannot transcribe in macro LHS".to_string())
}
seq @ TtDelimited(..) | seq @ TtToken(_, DocComment(..)) => {
let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq));
let idx = ei.idx;
ei.stack.push(MatcherTtFrame {
elts: lower_elts,
idx: idx,
});
ei.idx = 0;
cur_eis.push(ei);
}
TtToken(_, ref t) => {
let mut ei_t = ei.clone();
if token_name_eq(t,&tok) {
ei_t.idx += 1;
next_eis.push(ei_t);
}
}
}
}
}
/* error messages here could be improved with links to orig. rules */
if token_name_eq(&tok, &token::Eof) {
if eof_eis.len() == 1 {
let mut v = Vec::new();
for dv in &mut (&mut eof_eis[0]).matches {
v.push(dv.pop().unwrap());
}
return Success(nameize(sess, ms, &v[..]));
} else if eof_eis.len() > 1 {
return Error(sp, "ambiguity: multiple successful parses".to_string());
} else {
return Failure(sp, "unexpected end of macro invocation".to_string());
}
} else {
if (!bb_eis.is_empty() && !next_eis.is_empty())
|| bb_eis.len() > 1 {
let nts = bb_eis.iter().map(|ei| {
match ei.top_elts.get_tt(ei.idx) {
TtToken(_, MatchNt(bind, name, _, _)) => {
(format!("{} ('{}')",
token::get_ident(name),
token::get_ident(bind))).to_string()
}
_ => panic!()
} }).collect::<Vec<String>>().connect(" or ");
return Error(sp, format!(
"local ambiguity: multiple parsing options: \
built-in NTs {} or {} other options.",
nts, next_eis.len()).to_string());
} else if bb_eis.is_empty() && next_eis.is_empty() {
return Failure(sp, format!("no rules expected the token `{}`",
pprust::token_to_string(&tok)).to_string());
} else if !next_eis.is_empty() {
/* Now process the next token */
while !next_eis.is_empty() {
cur_eis.push(next_eis.pop().unwrap());
}
rdr.next_token();
} else /* bb_eis.len() == 1 */ {
let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone()));
let mut ei = bb_eis.pop().unwrap();
match ei.top_elts.get_tt(ei.idx) {
TtToken(span, MatchNt(_, name, _, _)) => {
let name_string = token::get_ident(name);
let match_cur = ei.match_cur;
(&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal(
parse_nt(&mut rust_parser, span, &name_string))));
ei.idx += 1;
ei.match_cur += 1;
}
_ => panic!()
}
cur_eis.push(ei);
for _ in 0..rust_parser.tokens_consumed {
let _ = rdr.next_token();
}
}
}
assert!(!cur_eis.is_empty());
}
}
pub fn parse_nt(p: &mut Parser, sp: Span, name: &str) -> Nonterminal {
match name {
"tt" => {
p.quote_depth += 1; //but in theory, non-quoted tts might be useful
let res = token::NtTT(P(panictry!(p.parse_token_tree())));
p.quote_depth -= 1;
return res;
}
_ => {}
}
// check at the beginning and the parser checks after each bump
panictry!(p.check_unknown_macro_variable());
match name {
"item" => match p.parse_item() {
Some(i) => token::NtItem(i),
None => panic!(p.fatal("expected an item keyword"))
},
"block" => token::NtBlock(panictry!(p.parse_block())),
"stmt" => match p.parse_stmt() {
Some(s) => token::NtStmt(s),
None => panic!(p.fatal("expected a statement"))
},
"pat" => token::NtPat(p.parse_pat()),
"expr" => token::NtExpr(p.parse_expr()),
"ty" => token::NtTy(p.parse_ty()),
// this could be handled like a token, since it is one
"ident" => match p.token {
token::Ident(sn,b) => { panictry!(p.bump()); token::NtIdent(Box::new(sn),b) }
_ => {
let token_str = pprust::token_to_string(&p.token);
panic!(p.fatal(&format!("expected ident, found {}",
&token_str[..])))
}
},
"path" => {
token::NtPath(Box::new(panictry!(p.parse_path(LifetimeAndTypesWithoutColons))))
}
"meta" => token::NtMeta(p.parse_meta_item()),
_ => {
panic!(p.span_fatal_help(sp,
&format!("invalid fragment specifier `{}`", name),
"valid fragment specifiers are `ident`, `block`, \
`stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \
and `item`"))
}
}
} | match ei.top_elts.get_tt(idx) {
/* need to descend into sequence */
TtSequence(sp, seq) => { | random_line_split |
transitionService.d.ts | /**
* @coreapi
* @module transition
*/
/** for typedoc */
import { IHookRegistry, TransitionOptions, TransitionHookScope, TransitionHookPhase, TransitionCreateHookFn, HookMatchCriteria, HookRegOptions, PathTypes, PathType, RegisteredHooks, TransitionHookFn, TransitionStateHookFn } from "./interface";
import { Transition } from "./transition";
import { RegisteredHook } from "./hookRegistry";
import { TargetState } from "../state/targetState";
import { PathNode } from "../path/node";
import { ViewService } from "../view/view";
import { UIRouter } from "../router";
import { TransitionEventType } from "./transitionEventType";
import { GetResultHandler, GetErrorHandler } from "./transitionHook";
import { Disposable } from "../interface";
/**
* The default [[Transition]] options.
*
* Include this object when applying custom defaults:
* let reloadOpts = { reload: true, notify: true }
* let options = defaults(theirOpts, customDefaults, defaultOptions);
*/
export declare let defaultTransOpts: TransitionOptions;
/**
* Plugin API for Transition Service
* @internalapi
*/
export interface TransitionServicePluginAPI {
/**
* Adds a Path to be used as a criterion against a TreeChanges path
*
* For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.
* It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`
* Each state in the exiting path is checked against the criteria and returned as part of the match.
*
* Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.
* It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`
* Only the tail of the `to` path is checked against the criteria and returned as part of the match.
*/
_definePathType(name: string, hookScope: TransitionHookScope): any;
/**
* Gets a Path definition used as a criterion against a TreeChanges path
*/
_getPathTypes(): PathTypes;
/**
* Defines a transition hook type and returns a transition hook registration
* function (which can then be used to register hooks of this type).
*/
_defineEvent(name: string, hookPhase: TransitionHookPhase, hookOrder: number, criteriaMatchPath: PathType, reverseSort?: boolean, getResultHandler?: GetResultHandler, getErrorHandler?: GetErrorHandler, rejectIfSuperseded?: boolean): any;
/**
* Returns the known event types, such as `onBefore`
* If a phase argument is provided, returns only events for the given phase.
*/
_getEvents(phase?: TransitionHookPhase): TransitionEventType[];
/** Returns the hooks registered for the given hook name */
getHooks(hookName: string): RegisteredHook[];
}
/**
* This class provides services related to Transitions.
*
* - Most importantly, it allows global Transition Hooks to be registered.
* - It allows the default transition error handler to be set.
* - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]).
*
* At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class.
*/
export declare class | implements IHookRegistry, Disposable {
/** @hidden */
_transitionCount: number;
/**
* Registers a [[TransitionHookFn]], called *while a transition is being constructed*.
*
* Registers a transition lifecycle hook, which is invoked during transition construction.
*
* This low level hook should only be used by plugins.
* This can be a useful time for plugins to add resolves or mutate the transition as needed.
* The Sticky States plugin uses this hook to modify the treechanges.
*
* ### Lifecycle
*
* `onCreate` hooks are invoked *while a transition is being constructed*.
*
* ### Return value
*
* The hook's return value is ignored
*
* @internalapi
* @param criteria defines which Transitions the Hook should be invoked for.
* @param callback the hook function which will be invoked.
* @param options the registration options
* @returns a function which deregisters the hook.
*/
onCreate(criteria: HookMatchCriteria, callback: TransitionCreateHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @hidden */
$view: ViewService;
/** @hidden The transition hook types, such as `onEnter`, `onStart`, etc */
private _eventTypes;
/** @hidden The registered transition hooks */
_registeredHooks: RegisteredHooks;
/** @hidden The paths on a criteria object */
private _criteriaPaths;
/** @hidden */
private _router;
/** @internalapi */
_pluginapi: TransitionServicePluginAPI;
/**
* This object has hook de-registration functions for the built-in hooks.
* This can be used by third parties libraries that wish to customize the behaviors
*
* @hidden
*/
_deregisterHookFns: {
addCoreResolves: Function;
redirectTo: Function;
onExit: Function;
onRetain: Function;
onEnter: Function;
eagerResolve: Function;
lazyResolve: Function;
loadViews: Function;
activateViews: Function;
updateGlobals: Function;
updateUrl: Function;
lazyLoad: Function;
};
/** @hidden */
constructor(_router: UIRouter);
/**
* dispose
* @internalapi
*/
dispose(router: UIRouter): void;
/**
* Creates a new [[Transition]] object
*
* This is a factory function for creating new Transition objects.
* It is used internally by the [[StateService]] and should generally not be called by application code.
*
* @param fromPath the path to the current state (the from state)
* @param targetState the target state (destination)
* @returns a Transition
*/
create(fromPath: PathNode[], targetState: TargetState): Transition;
/** @hidden */
private _defineDefaultEvents();
/** @hidden */
private _defineDefaultPaths();
/** @hidden */
_defineEvent(name: string, hookPhase: TransitionHookPhase, hookOrder: number, criteriaMatchPath: PathType, reverseSort?: boolean, getResultHandler?: GetResultHandler, getErrorHandler?: GetErrorHandler, rejectIfSuperseded?: boolean): void;
/** @hidden */
private _getEvents(phase?);
/**
* Adds a Path to be used as a criterion against a TreeChanges path
*
* For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.
* It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`
* Each state in the exiting path is checked against the criteria and returned as part of the match.
*
* Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.
* It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`
* Only the tail of the `to` path is checked against the criteria and returned as part of the match.
*
* @hidden
*/
private _definePathType(name, hookScope);
/** * @hidden */
private _getPathTypes();
/** @hidden */
getHooks(hookName: string): RegisteredHook[];
/** @hidden */
private _registerCoreTransitionHooks();
}
| TransitionService | identifier_name |
transitionService.d.ts | /**
* @coreapi
* @module transition
*/
/** for typedoc */
import { IHookRegistry, TransitionOptions, TransitionHookScope, TransitionHookPhase, TransitionCreateHookFn, HookMatchCriteria, HookRegOptions, PathTypes, PathType, RegisteredHooks, TransitionHookFn, TransitionStateHookFn } from "./interface";
import { Transition } from "./transition";
import { RegisteredHook } from "./hookRegistry";
import { TargetState } from "../state/targetState";
import { PathNode } from "../path/node";
import { ViewService } from "../view/view";
import { UIRouter } from "../router";
import { TransitionEventType } from "./transitionEventType";
import { GetResultHandler, GetErrorHandler } from "./transitionHook";
import { Disposable } from "../interface";
/**
* The default [[Transition]] options.
*
* Include this object when applying custom defaults:
* let reloadOpts = { reload: true, notify: true }
* let options = defaults(theirOpts, customDefaults, defaultOptions);
*/
export declare let defaultTransOpts: TransitionOptions;
/**
* Plugin API for Transition Service
* @internalapi
*/
export interface TransitionServicePluginAPI {
/**
* Adds a Path to be used as a criterion against a TreeChanges path
*
* For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.
* It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`
* Each state in the exiting path is checked against the criteria and returned as part of the match.
*
* Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.
* It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`
* Only the tail of the `to` path is checked against the criteria and returned as part of the match.
*/
_definePathType(name: string, hookScope: TransitionHookScope): any;
/**
* Gets a Path definition used as a criterion against a TreeChanges path
*/
_getPathTypes(): PathTypes;
/**
* Defines a transition hook type and returns a transition hook registration
* function (which can then be used to register hooks of this type).
*/
_defineEvent(name: string, hookPhase: TransitionHookPhase, hookOrder: number, criteriaMatchPath: PathType, reverseSort?: boolean, getResultHandler?: GetResultHandler, getErrorHandler?: GetErrorHandler, rejectIfSuperseded?: boolean): any;
/**
* Returns the known event types, such as `onBefore`
* If a phase argument is provided, returns only events for the given phase.
*/
_getEvents(phase?: TransitionHookPhase): TransitionEventType[];
/** Returns the hooks registered for the given hook name */
getHooks(hookName: string): RegisteredHook[];
}
/**
* This class provides services related to Transitions.
*
* - Most importantly, it allows global Transition Hooks to be registered.
* - It allows the default transition error handler to be set.
* - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]).
*
* At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class.
*/
export declare class TransitionService implements IHookRegistry, Disposable {
/** @hidden */
_transitionCount: number;
/**
* Registers a [[TransitionHookFn]], called *while a transition is being constructed*.
*
* Registers a transition lifecycle hook, which is invoked during transition construction.
*
* This low level hook should only be used by plugins.
* This can be a useful time for plugins to add resolves or mutate the transition as needed.
* The Sticky States plugin uses this hook to modify the treechanges.
*
* ### Lifecycle
*
* `onCreate` hooks are invoked *while a transition is being constructed*.
*
* ### Return value
*
* The hook's return value is ignored
*
* @internalapi
* @param criteria defines which Transitions the Hook should be invoked for.
* @param callback the hook function which will be invoked.
* @param options the registration options
* @returns a function which deregisters the hook.
*/
onCreate(criteria: HookMatchCriteria, callback: TransitionCreateHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @inheritdoc */
onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;
/** @hidden */
$view: ViewService;
/** @hidden The transition hook types, such as `onEnter`, `onStart`, etc */
private _eventTypes;
/** @hidden The registered transition hooks */
_registeredHooks: RegisteredHooks; | _pluginapi: TransitionServicePluginAPI;
/**
* This object has hook de-registration functions for the built-in hooks.
* This can be used by third parties libraries that wish to customize the behaviors
*
* @hidden
*/
_deregisterHookFns: {
addCoreResolves: Function;
redirectTo: Function;
onExit: Function;
onRetain: Function;
onEnter: Function;
eagerResolve: Function;
lazyResolve: Function;
loadViews: Function;
activateViews: Function;
updateGlobals: Function;
updateUrl: Function;
lazyLoad: Function;
};
/** @hidden */
constructor(_router: UIRouter);
/**
* dispose
* @internalapi
*/
dispose(router: UIRouter): void;
/**
* Creates a new [[Transition]] object
*
* This is a factory function for creating new Transition objects.
* It is used internally by the [[StateService]] and should generally not be called by application code.
*
* @param fromPath the path to the current state (the from state)
* @param targetState the target state (destination)
* @returns a Transition
*/
create(fromPath: PathNode[], targetState: TargetState): Transition;
/** @hidden */
private _defineDefaultEvents();
/** @hidden */
private _defineDefaultPaths();
/** @hidden */
_defineEvent(name: string, hookPhase: TransitionHookPhase, hookOrder: number, criteriaMatchPath: PathType, reverseSort?: boolean, getResultHandler?: GetResultHandler, getErrorHandler?: GetErrorHandler, rejectIfSuperseded?: boolean): void;
/** @hidden */
private _getEvents(phase?);
/**
* Adds a Path to be used as a criterion against a TreeChanges path
*
* For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.
* It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`
* Each state in the exiting path is checked against the criteria and returned as part of the match.
*
* Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.
* It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`
* Only the tail of the `to` path is checked against the criteria and returned as part of the match.
*
* @hidden
*/
private _definePathType(name, hookScope);
/** * @hidden */
private _getPathTypes();
/** @hidden */
getHooks(hookName: string): RegisteredHook[];
/** @hidden */
private _registerCoreTransitionHooks();
} | /** @hidden The paths on a criteria object */
private _criteriaPaths;
/** @hidden */
private _router;
/** @internalapi */ | random_line_split |
setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import re
import os.path
from io import open
from setuptools import find_packages, setup
# Change the PACKAGE_NAME only to change folder and different name
PACKAGE_NAME = "azure-mgmt-servicefabric"
PACKAGE_PPRINT_NAME = "Service Fabric Management"
# a-b-c => a/b/c
package_folder_path = PACKAGE_NAME.replace('-', '/')
# a-b-c => a.b.c
namespace_name = PACKAGE_NAME.replace('-', '.')
# Version extraction inspired from 'requests'
with open(os.path.join(package_folder_path, 'version.py')
if os.path.exists(os.path.join(package_folder_path, 'version.py'))
else os.path.join(package_folder_path, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('CHANGELOG.md', encoding='utf-8') as f:
changelog = f.read()
setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + '\n\n' + changelog,
long_description_content_type='text/markdown',
license='MIT License',
author='Microsoft Corporation', | keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'License :: OSI Approved :: MIT License',
],
zip_safe=False,
packages=find_packages(exclude=[
'tests',
# Exclude packages that will be covered by PEP420 or nspkg
'azure',
'azure.mgmt',
]),
install_requires=[
'msrest>=0.6.21',
'azure-common~=1.1',
'azure-mgmt-core>=1.3.0,<2.0.0',
],
python_requires=">=3.6"
) | author_email='azpysdkhelp@microsoft.com',
url='https://github.com/Azure/azure-sdk-for-python', | random_line_split |
setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import re
import os.path
from io import open
from setuptools import find_packages, setup
# Change the PACKAGE_NAME only to change folder and different name
PACKAGE_NAME = "azure-mgmt-servicefabric"
PACKAGE_PPRINT_NAME = "Service Fabric Management"
# a-b-c => a/b/c
package_folder_path = PACKAGE_NAME.replace('-', '/')
# a-b-c => a.b.c
namespace_name = PACKAGE_NAME.replace('-', '.')
# Version extraction inspired from 'requests'
with open(os.path.join(package_folder_path, 'version.py')
if os.path.exists(os.path.join(package_folder_path, 'version.py'))
else os.path.join(package_folder_path, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
|
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('CHANGELOG.md', encoding='utf-8') as f:
changelog = f.read()
setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + '\n\n' + changelog,
long_description_content_type='text/markdown',
license='MIT License',
author='Microsoft Corporation',
author_email='azpysdkhelp@microsoft.com',
url='https://github.com/Azure/azure-sdk-for-python',
keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'License :: OSI Approved :: MIT License',
],
zip_safe=False,
packages=find_packages(exclude=[
'tests',
# Exclude packages that will be covered by PEP420 or nspkg
'azure',
'azure.mgmt',
]),
install_requires=[
'msrest>=0.6.21',
'azure-common~=1.1',
'azure-mgmt-core>=1.3.0,<2.0.0',
],
python_requires=">=3.6"
)
| raise RuntimeError('Cannot find version information') | conditional_block |
variable.rs | //! A basic `Variable` implementation.
//!
//! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable`
//! type parameter, to allow frontends that identify variables with
//! their own index types to use them directly. Frontends which don't
//! can use the `Variable` defined here.
use cretonne::entity::EntityRef;
use std::u32;
///! An opaque reference to a variable.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Variable(u32);
impl Variable {
/// Create a new Variable with the given index.
pub fn with_u32(index: u32) -> Self |
}
impl EntityRef for Variable {
fn new(index: usize) -> Self {
debug_assert!(index < (u32::MAX as usize));
Variable(index as u32)
}
fn index(self) -> usize {
self.0 as usize
}
}
| {
debug_assert!(index < u32::MAX);
Variable(index)
} | identifier_body |
variable.rs | //! A basic `Variable` implementation.
//!
//! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable`
//! type parameter, to allow frontends that identify variables with
//! their own index types to use them directly. Frontends which don't
//! can use the `Variable` defined here.
use cretonne::entity::EntityRef;
use std::u32;
///! An opaque reference to a variable.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Variable(u32);
impl Variable {
/// Create a new Variable with the given index.
pub fn with_u32(index: u32) -> Self {
debug_assert!(index < u32::MAX);
Variable(index)
}
}
impl EntityRef for Variable {
fn new(index: usize) -> Self {
debug_assert!(index < (u32::MAX as usize));
Variable(index as u32)
} |
fn index(self) -> usize {
self.0 as usize
}
} | random_line_split | |
variable.rs | //! A basic `Variable` implementation.
//!
//! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable`
//! type parameter, to allow frontends that identify variables with
//! their own index types to use them directly. Frontends which don't
//! can use the `Variable` defined here.
use cretonne::entity::EntityRef;
use std::u32;
///! An opaque reference to a variable.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Variable(u32);
impl Variable {
/// Create a new Variable with the given index.
pub fn with_u32(index: u32) -> Self {
debug_assert!(index < u32::MAX);
Variable(index)
}
}
impl EntityRef for Variable {
fn new(index: usize) -> Self {
debug_assert!(index < (u32::MAX as usize));
Variable(index as u32)
}
fn | (self) -> usize {
self.0 as usize
}
}
| index | identifier_name |
es_batch.py | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch = ElasticBatch(client, 1000)
with batch:
...
batch.add({
'_op_type': 'index',
'_index': index_name,
'_type': SearchDocument._doc_type.name,
'_id': document_id,
'title': 'Abc'
})
"""
def __init__(self, client, batch_size):
super(ElasticBatch, self).__init__(client, batch_size)
self.client = client
self.actions = []
def add(self, action):
|
def should_flush(self):
return len(self.actions) > self.batch_size
def flush(self):
if self.actions:
try:
helpers.bulk(self.client, self.actions)
except BulkIndexError:
# when trying to delete a document that does not exist, an
# error is raised, and other documents are not inserted
log.warning(
'error sending bulk update to ElasticSearch',
exc_info=True)
self.actions = []
| self.actions.append(action)
self.flush_or_not() | identifier_body |
es_batch.py | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch = ElasticBatch(client, 1000)
with batch:
...
batch.add({
'_op_type': 'index',
'_index': index_name,
'_type': SearchDocument._doc_type.name,
'_id': document_id,
'title': 'Abc'
})
"""
def __init__(self, client, batch_size):
super(ElasticBatch, self).__init__(client, batch_size)
self.client = client
self.actions = []
def add(self, action):
self.actions.append(action)
self.flush_or_not()
def | (self):
return len(self.actions) > self.batch_size
def flush(self):
if self.actions:
try:
helpers.bulk(self.client, self.actions)
except BulkIndexError:
# when trying to delete a document that does not exist, an
# error is raised, and other documents are not inserted
log.warning(
'error sending bulk update to ElasticSearch',
exc_info=True)
self.actions = []
| should_flush | identifier_name |
es_batch.py | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch = ElasticBatch(client, 1000)
with batch:
...
batch.add({
'_op_type': 'index',
'_index': index_name,
'_type': SearchDocument._doc_type.name,
'_id': document_id,
'title': 'Abc'
})
"""
def __init__(self, client, batch_size):
super(ElasticBatch, self).__init__(client, batch_size)
self.client = client
self.actions = []
def add(self, action):
self.actions.append(action)
self.flush_or_not()
def should_flush(self):
return len(self.actions) > self.batch_size
def flush(self):
if self.actions:
try:
helpers.bulk(self.client, self.actions)
except BulkIndexError:
# when trying to delete a document that does not exist, an
# error is raised, and other documents are not inserted | log.warning(
'error sending bulk update to ElasticSearch',
exc_info=True)
self.actions = [] | random_line_split | |
es_batch.py | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch = ElasticBatch(client, 1000)
with batch:
...
batch.add({
'_op_type': 'index',
'_index': index_name,
'_type': SearchDocument._doc_type.name,
'_id': document_id,
'title': 'Abc'
})
"""
def __init__(self, client, batch_size):
super(ElasticBatch, self).__init__(client, batch_size)
self.client = client
self.actions = []
def add(self, action):
self.actions.append(action)
self.flush_or_not()
def should_flush(self):
return len(self.actions) > self.batch_size
def flush(self):
if self.actions:
| try:
helpers.bulk(self.client, self.actions)
except BulkIndexError:
# when trying to delete a document that does not exist, an
# error is raised, and other documents are not inserted
log.warning(
'error sending bulk update to ElasticSearch',
exc_info=True)
self.actions = [] | conditional_block | |
enclosure_getters.rs | // This file is part of feed.
//
// Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com>
//
// 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; either version 3 of the License, or
// (at your option) any later version.
//! The fields under enclosure can be retrieved by using the methods under
//! `Enclosure`.
use EnclosureGetters;
use rss::Enclosure;
impl EnclosureGetters for Enclosure
{
/// Get the url that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_ref())
/// .mime_type("audio/ogg")
/// .finalize()
/// .unwrap();
///
/// assert_eq!(url.to_owned(), enclosure.url())
/// ```
fn url(&self) -> String
{
self.url.clone()
}
/// Get the length that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let length: i64 = 70772893;
///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_str())
/// .length(length)
/// .mime_type("audio/ogg")
/// .finalize()
/// .unwrap();
///
/// assert_eq!(length.to_string(), enclosure.length())
/// ```
fn length(&self) -> String
{
self.length.clone()
}
/// Get the enclosure type that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let enclosure_type = "audio/ogg";
///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_str())
/// .mime_type(enclosure_type)
/// .finalize()
/// .unwrap();
///
/// assert_eq!(enclosure_type.to_owned(), enclosure.mime_type())
/// ```
fn mime_type(&self) -> String
{ | }
|
self.mime_type.clone()
}
| identifier_body |
enclosure_getters.rs | // This file is part of feed.
//
// Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com>
//
// 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; either version 3 of the License, or
// (at your option) any later version.
//! The fields under enclosure can be retrieved by using the methods under
//! `Enclosure`.
use EnclosureGetters;
use rss::Enclosure;
impl EnclosureGetters for Enclosure
{
/// Get the url that exists under `Enclosure`.
///
/// # Examples | ///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_ref())
/// .mime_type("audio/ogg")
/// .finalize()
/// .unwrap();
///
/// assert_eq!(url.to_owned(), enclosure.url())
/// ```
fn url(&self) -> String
{
self.url.clone()
}
/// Get the length that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let length: i64 = 70772893;
///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_str())
/// .length(length)
/// .mime_type("audio/ogg")
/// .finalize()
/// .unwrap();
///
/// assert_eq!(length.to_string(), enclosure.length())
/// ```
fn length(&self) -> String
{
self.length.clone()
}
/// Get the enclosure type that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let enclosure_type = "audio/ogg";
///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_str())
/// .mime_type(enclosure_type)
/// .finalize()
/// .unwrap();
///
/// assert_eq!(enclosure_type.to_owned(), enclosure.mime_type())
/// ```
fn mime_type(&self) -> String
{
self.mime_type.clone()
}
} | ///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters}; | random_line_split |
enclosure_getters.rs | // This file is part of feed.
//
// Copyright © 2015-2017 Chris Palmer <pennstate5013@gmail.com>
//
// 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; either version 3 of the License, or
// (at your option) any later version.
//! The fields under enclosure can be retrieved by using the methods under
//! `Enclosure`.
use EnclosureGetters;
use rss::Enclosure;
impl EnclosureGetters for Enclosure
{
/// Get the url that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_ref())
/// .mime_type("audio/ogg")
/// .finalize()
/// .unwrap();
///
/// assert_eq!(url.to_owned(), enclosure.url())
/// ```
fn url(&self) -> String
{
self.url.clone()
}
/// Get the length that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let length: i64 = 70772893;
///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_str())
/// .length(length)
/// .mime_type("audio/ogg")
/// .finalize()
/// .unwrap();
///
/// assert_eq!(length.to_string(), enclosure.length())
/// ```
fn l | &self) -> String
{
self.length.clone()
}
/// Get the enclosure type that exists under `Enclosure`.
///
/// # Examples
///
/// ```
/// use feed::{EnclosureBuilder, EnclosureGetters};
///
/// let enclosure_type = "audio/ogg";
///
/// let url = "http://www.podtrac.com/pts/redirect.ogg/".to_owned()
/// + "traffic.libsyn.com/jnite/linuxactionshowep408.ogg";
///
/// let enclosure = EnclosureBuilder::new()
/// .url(url.as_str())
/// .mime_type(enclosure_type)
/// .finalize()
/// .unwrap();
///
/// assert_eq!(enclosure_type.to_owned(), enclosure.mime_type())
/// ```
fn mime_type(&self) -> String
{
self.mime_type.clone()
}
}
| ength( | identifier_name |
Search.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import {connect} from 'react-redux';
import StringList from './StringList/StringList'
import TwitterSelector from './DomainSelector/TwitterSelector'
import TweetFilter from './TweetFilter/TweetFilter'
class Search extends React.Component {
c | props) {
super(props);
this.state = {
includedWords: []
};
this.getWords = this.getWords.bind(this);
}
getWords(words) {
this.setState({
includedWords: words
});
}
render() {
const styles = {
fontFamily: 'Helvetica Neue',
fontSize: 14,
lineHeight: '10px',
color: 'white',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}
return (
<div>
<TweetFilter />
</div>
);
}
}
export default Search;
| onstructor( | identifier_name |
Search.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import {connect} from 'react-redux';
import StringList from './StringList/StringList'
import TwitterSelector from './DomainSelector/TwitterSelector'
import TweetFilter from './TweetFilter/TweetFilter'
class Search extends React.Component { | this.getWords = this.getWords.bind(this);
}
getWords(words) {
this.setState({
includedWords: words
});
}
render() {
const styles = {
fontFamily: 'Helvetica Neue',
fontSize: 14,
lineHeight: '10px',
color: 'white',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}
return (
<div>
<TweetFilter />
</div>
);
}
}
export default Search; | constructor(props) {
super(props);
this.state = {
includedWords: []
}; | random_line_split |
deref_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cell::RefCell;
use core::cell::RefMut;
use core::ops::DerefMut;
use core::ops::Deref;
// pub struct RefCell<T: ?Sized> {
// borrow: Cell<BorrowFlag>,
// value: UnsafeCell<T>,
// }
// impl<T> RefCell<T> {
// /// Creates a new `RefCell` containing `value`.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::cell::RefCell;
// ///
// /// let c = RefCell::new(5);
// /// ```
// #[stable(feature = "rust1", since = "1.0.0")]
// #[inline]
// pub fn new(value: T) -> RefCell<T> {
// RefCell {
// value: UnsafeCell::new(value),
// borrow: Cell::new(UNUSED),
// }
// }
//
// /// Consumes the `RefCell`, returning the wrapped value.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::cell::RefCell;
// ///
// /// let c = RefCell::new(5);
// ///
// /// let five = c.into_inner();
// /// ```
// #[stable(feature = "rust1", since = "1.0.0")]
// #[inline]
// pub fn into_inner(self) -> T {
// // Since this function takes `self` (the `RefCell`) by value, the
// // compiler statically verifies that it is not currently borrowed.
// // Therefore the following assertion is just a `debug_assert!`.
// debug_assert!(self.borrow.get() == UNUSED);
// unsafe { self.value.into_inner() }
// }
// }
// pub struct RefMut<'b, T: ?Sized + 'b> {
// // FIXME #12808: strange name to try to avoid interfering with
// // field accesses of the contained type via Deref
// _value: &'b mut T,
// _borrow: BorrowRefMut<'b>,
// }
// impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
// type Target = T;
//
// #[inline]
// fn deref<'a>(&'a self) -> &'a T {
// self._value
// }
// }
// impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
// #[inline]
// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
// self._value
// }
// }
type T = i32;
#[test]
fn deref_test1() |
}
| {
let value: T = 68;
let refcell: RefCell<T> = RefCell::<T>::new(value);
let mut value_refmut: RefMut<T> = refcell.borrow_mut();
{
let deref_mut: &mut T = value_refmut.deref_mut();
*deref_mut = 500;
}
let value_ref: &T = value_refmut.deref();
assert_eq!(*value_ref, 500);
} | identifier_body |
deref_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cell::RefCell;
use core::cell::RefMut;
use core::ops::DerefMut;
use core::ops::Deref;
// pub struct RefCell<T: ?Sized> {
// borrow: Cell<BorrowFlag>,
// value: UnsafeCell<T>,
// }
// impl<T> RefCell<T> {
// /// Creates a new `RefCell` containing `value`.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::cell::RefCell;
// ///
// /// let c = RefCell::new(5);
// /// ```
// #[stable(feature = "rust1", since = "1.0.0")]
// #[inline]
// pub fn new(value: T) -> RefCell<T> {
// RefCell {
// value: UnsafeCell::new(value),
// borrow: Cell::new(UNUSED),
// }
// }
//
// /// Consumes the `RefCell`, returning the wrapped value.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::cell::RefCell;
// ///
// /// let c = RefCell::new(5);
// ///
// /// let five = c.into_inner();
// /// ```
// #[stable(feature = "rust1", since = "1.0.0")]
// #[inline]
// pub fn into_inner(self) -> T {
// // Since this function takes `self` (the `RefCell`) by value, the
// // compiler statically verifies that it is not currently borrowed.
// // Therefore the following assertion is just a `debug_assert!`.
// debug_assert!(self.borrow.get() == UNUSED);
// unsafe { self.value.into_inner() }
// }
// }
// pub struct RefMut<'b, T: ?Sized + 'b> {
// // FIXME #12808: strange name to try to avoid interfering with
// // field accesses of the contained type via Deref
// _value: &'b mut T,
// _borrow: BorrowRefMut<'b>,
// }
// impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
// type Target = T;
//
// #[inline]
// fn deref<'a>(&'a self) -> &'a T {
// self._value
// }
// }
// impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
// #[inline]
// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
// self._value
// }
// }
type T = i32;
#[test]
fn | () {
let value: T = 68;
let refcell: RefCell<T> = RefCell::<T>::new(value);
let mut value_refmut: RefMut<T> = refcell.borrow_mut();
{
let deref_mut: &mut T = value_refmut.deref_mut();
*deref_mut = 500;
}
let value_ref: &T = value_refmut.deref();
assert_eq!(*value_ref, 500);
}
}
| deref_test1 | identifier_name |
deref_mut.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cell::RefCell;
use core::cell::RefMut;
use core::ops::DerefMut;
use core::ops::Deref;
// pub struct RefCell<T: ?Sized> {
// borrow: Cell<BorrowFlag>,
// value: UnsafeCell<T>,
// }
// impl<T> RefCell<T> {
// /// Creates a new `RefCell` containing `value`.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::cell::RefCell;
// ///
// /// let c = RefCell::new(5);
// /// ```
// #[stable(feature = "rust1", since = "1.0.0")]
// #[inline]
// pub fn new(value: T) -> RefCell<T> {
// RefCell {
// value: UnsafeCell::new(value),
// borrow: Cell::new(UNUSED),
// }
// }
//
// /// Consumes the `RefCell`, returning the wrapped value. | // /// ```
// /// use std::cell::RefCell;
// ///
// /// let c = RefCell::new(5);
// ///
// /// let five = c.into_inner();
// /// ```
// #[stable(feature = "rust1", since = "1.0.0")]
// #[inline]
// pub fn into_inner(self) -> T {
// // Since this function takes `self` (the `RefCell`) by value, the
// // compiler statically verifies that it is not currently borrowed.
// // Therefore the following assertion is just a `debug_assert!`.
// debug_assert!(self.borrow.get() == UNUSED);
// unsafe { self.value.into_inner() }
// }
// }
// pub struct RefMut<'b, T: ?Sized + 'b> {
// // FIXME #12808: strange name to try to avoid interfering with
// // field accesses of the contained type via Deref
// _value: &'b mut T,
// _borrow: BorrowRefMut<'b>,
// }
// impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
// type Target = T;
//
// #[inline]
// fn deref<'a>(&'a self) -> &'a T {
// self._value
// }
// }
// impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
// #[inline]
// fn deref_mut<'a>(&'a mut self) -> &'a mut T {
// self._value
// }
// }
type T = i32;
#[test]
fn deref_test1() {
let value: T = 68;
let refcell: RefCell<T> = RefCell::<T>::new(value);
let mut value_refmut: RefMut<T> = refcell.borrow_mut();
{
let deref_mut: &mut T = value_refmut.deref_mut();
*deref_mut = 500;
}
let value_ref: &T = value_refmut.deref();
assert_eq!(*value_ref, 500);
}
} | // ///
// /// # Examples
// /// | random_line_split |
main.py | import re
import datetime
import time
#niru's git commit
while True:
#open the file for reading
file = open("test.txt")
content = file.read()
#Get timestamp
ts = time.time()
ist = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
#open file for read and close it neatly(wrap code in try/except)
#with open('test.txt', 'r') as r:
#content = r.read()
#print content
#Search the entire content for '@' and replace it with time stamp.
new_content = re.sub(r'@.*', ist, content)
print new_content
#open file for write and close it neatly(wrap code in try/except)
with open('test.txt', 'w') as f:
f.write(new_content)
print "torpid loop complete"
| time.sleep(5) | random_line_split | |
main.py | import re
import datetime
import time
#niru's git commit
while True:
#open the file for reading
| file = open("test.txt")
content = file.read()
#Get timestamp
ts = time.time()
ist = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
#open file for read and close it neatly(wrap code in try/except)
#with open('test.txt', 'r') as r:
#content = r.read()
#print content
#Search the entire content for '@' and replace it with time stamp.
new_content = re.sub(r'@.*', ist, content)
print new_content
#open file for write and close it neatly(wrap code in try/except)
with open('test.txt', 'w') as f:
f.write(new_content)
print "torpid loop complete"
time.sleep(5) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.