repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_last | def get_last(self, table=None):
"""Just the last entry."""
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | python | def get_last(self, table=None):
"""Just the last entry."""
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | [
"def",
"get_last",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"query",
"=",
"'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;'",
"%",
"table",
"return",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"query",
")",
".",
"fetchone",
"(",
")"
] | Just the last entry. | [
"Just",
"the",
"last",
"entry",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L283-L287 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_number | def get_number(self, num, table=None):
"""Get a specific entry by its number."""
if table is None: table = self.main_table
self.own_cursor.execute('SELECT * from "%s" LIMIT 1 OFFSET %i;' % (self.main_table, num))
return self.own_cursor.fetchone() | python | def get_number(self, num, table=None):
"""Get a specific entry by its number."""
if table is None: table = self.main_table
self.own_cursor.execute('SELECT * from "%s" LIMIT 1 OFFSET %i;' % (self.main_table, num))
return self.own_cursor.fetchone() | [
"def",
"get_number",
"(",
"self",
",",
"num",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT * from \"%s\" LIMIT 1 OFFSET %i;'",
"%",
"(",
"self",
".",
"main_table",
",",
"num",
")",
")",
"return",
"self",
".",
"own_cursor",
".",
"fetchone",
"(",
")"
] | Get a specific entry by its number. | [
"Get",
"a",
"specific",
"entry",
"by",
"its",
"number",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L289-L293 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_entry | def get_entry(self, key, column=None, table=None):
"""Get a specific entry."""
if table is None: table = self.main_table
if column is None: column = "id"
if isinstance(key, basestring): key = key.replace("'","''")
query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;'
query = query % (table, column, key)
self.own_cursor.execute(query)
return self.own_cursor.fetchone() | python | def get_entry(self, key, column=None, table=None):
"""Get a specific entry."""
if table is None: table = self.main_table
if column is None: column = "id"
if isinstance(key, basestring): key = key.replace("'","''")
query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;'
query = query % (table, column, key)
self.own_cursor.execute(query)
return self.own_cursor.fetchone() | [
"def",
"get_entry",
"(",
"self",
",",
"key",
",",
"column",
"=",
"None",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"if",
"column",
"is",
"None",
":",
"column",
"=",
"\"id\"",
"if",
"isinstance",
"(",
"key",
",",
"basestring",
")",
":",
"key",
"=",
"key",
".",
"replace",
"(",
"\"'\"",
",",
"\"''\"",
")",
"query",
"=",
"'SELECT * from \"%s\" where \"%s\"==\"%s\" LIMIT 1;'",
"query",
"=",
"query",
"%",
"(",
"table",
",",
"column",
",",
"key",
")",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"query",
")",
"return",
"self",
".",
"own_cursor",
".",
"fetchone",
"(",
")"
] | Get a specific entry. | [
"Get",
"a",
"specific",
"entry",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L296-L304 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.insert_df | def insert_df(self, table_name, df):
"""Create a table and populate it with data from a dataframe."""
df.to_sql(table_name, con=self.own_connection) | python | def insert_df(self, table_name, df):
"""Create a table and populate it with data from a dataframe."""
df.to_sql(table_name, con=self.own_connection) | [
"def",
"insert_df",
"(",
"self",
",",
"table_name",
",",
"df",
")",
":",
"df",
".",
"to_sql",
"(",
"table_name",
",",
"con",
"=",
"self",
".",
"own_connection",
")"
] | Create a table and populate it with data from a dataframe. | [
"Create",
"a",
"table",
"and",
"populate",
"it",
"with",
"data",
"from",
"a",
"dataframe",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L316-L318 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_and_order | def get_and_order(self, ids, column=None, table=None):
"""Get specific entries and order them in the same way."""
command = """
SELECT rowid, * from "data"
WHERE rowid in (%s)
ORDER BY CASE rowid
%s
END;
"""
ordered = ','.join(map(str,ids))
rowids = '\n'.join("WHEN '%s' THEN %s" % (row,i) for i,row in enumerate(ids))
command = command % (ordered, rowids) | python | def get_and_order(self, ids, column=None, table=None):
"""Get specific entries and order them in the same way."""
command = """
SELECT rowid, * from "data"
WHERE rowid in (%s)
ORDER BY CASE rowid
%s
END;
"""
ordered = ','.join(map(str,ids))
rowids = '\n'.join("WHEN '%s' THEN %s" % (row,i) for i,row in enumerate(ids))
command = command % (ordered, rowids) | [
"def",
"get_and_order",
"(",
"self",
",",
"ids",
",",
"column",
"=",
"None",
",",
"table",
"=",
"None",
")",
":",
"command",
"=",
"\"\"\"\n SELECT rowid, * from \"data\"\n WHERE rowid in (%s)\n ORDER BY CASE rowid\n %s\n END;\n \"\"\"",
"ordered",
"=",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"ids",
")",
")",
"rowids",
"=",
"'\\n'",
".",
"join",
"(",
"\"WHEN '%s' THEN %s\"",
"%",
"(",
"row",
",",
"i",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"ids",
")",
")",
"command",
"=",
"command",
"%",
"(",
"ordered",
",",
"rowids",
")"
] | Get specific entries and order them in the same way. | [
"Get",
"specific",
"entries",
"and",
"order",
"them",
"in",
"the",
"same",
"way",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L334-L345 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.import_table | def import_table(self, source, table_name):
"""Copy a table from another SQLite database to this one."""
query = "SELECT * FROM `%s`" % table_name.lower()
df = pandas.read_sql(query, source.connection)
df.to_sql(table_name, con=self.own_connection) | python | def import_table(self, source, table_name):
"""Copy a table from another SQLite database to this one."""
query = "SELECT * FROM `%s`" % table_name.lower()
df = pandas.read_sql(query, source.connection)
df.to_sql(table_name, con=self.own_connection) | [
"def",
"import_table",
"(",
"self",
",",
"source",
",",
"table_name",
")",
":",
"query",
"=",
"\"SELECT * FROM `%s`\"",
"%",
"table_name",
".",
"lower",
"(",
")",
"df",
"=",
"pandas",
".",
"read_sql",
"(",
"query",
",",
"source",
".",
"connection",
")",
"df",
".",
"to_sql",
"(",
"table_name",
",",
"con",
"=",
"self",
".",
"own_connection",
")"
] | Copy a table from another SQLite database to this one. | [
"Copy",
"a",
"table",
"from",
"another",
"SQLite",
"database",
"to",
"this",
"one",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L350-L354 |
dusktreader/flask-buzz | flask_buzz/__init__.py | FlaskBuzz.jsonify | def jsonify(self, status_code=None, message=None, headers=None):
"""
Returns a representation of the error in a jsonic form that is
compatible with flask's error handling.
Keyword arguments allow custom error handlers to override parts of the
exception when it is jsonified
"""
if status_code is None:
status_code = self.status_code
if message is None:
message = self.message
if headers is None:
headers = self.headers
response = flask.jsonify({
'status_code': status_code,
'error': repr(self),
'message': message,
})
if status_code is not None:
response.status_code = status_code
if headers is not None:
response.headers = headers
return response | python | def jsonify(self, status_code=None, message=None, headers=None):
"""
Returns a representation of the error in a jsonic form that is
compatible with flask's error handling.
Keyword arguments allow custom error handlers to override parts of the
exception when it is jsonified
"""
if status_code is None:
status_code = self.status_code
if message is None:
message = self.message
if headers is None:
headers = self.headers
response = flask.jsonify({
'status_code': status_code,
'error': repr(self),
'message': message,
})
if status_code is not None:
response.status_code = status_code
if headers is not None:
response.headers = headers
return response | [
"def",
"jsonify",
"(",
"self",
",",
"status_code",
"=",
"None",
",",
"message",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"if",
"status_code",
"is",
"None",
":",
"status_code",
"=",
"self",
".",
"status_code",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"self",
".",
"message",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"self",
".",
"headers",
"response",
"=",
"flask",
".",
"jsonify",
"(",
"{",
"'status_code'",
":",
"status_code",
",",
"'error'",
":",
"repr",
"(",
"self",
")",
",",
"'message'",
":",
"message",
",",
"}",
")",
"if",
"status_code",
"is",
"not",
"None",
":",
"response",
".",
"status_code",
"=",
"status_code",
"if",
"headers",
"is",
"not",
"None",
":",
"response",
".",
"headers",
"=",
"headers",
"return",
"response"
] | Returns a representation of the error in a jsonic form that is
compatible with flask's error handling.
Keyword arguments allow custom error handlers to override parts of the
exception when it is jsonified | [
"Returns",
"a",
"representation",
"of",
"the",
"error",
"in",
"a",
"jsonic",
"form",
"that",
"is",
"compatible",
"with",
"flask",
"s",
"error",
"handling",
"."
] | train | https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L21-L44 |
dusktreader/flask-buzz | flask_buzz/__init__.py | FlaskBuzz.build_error_handler | def build_error_handler(*tasks):
"""
Provides a generic error function that packages a flask_buzz exception
so that it can be handled nicely by the flask error handler::
app.register_error_handler(
FlaskBuzz, FlaskBuzz.build_error_handler(),
)
Additionally, extra tasks may be applied to the error prior to
packaging::
app.register_error_handler(
FlaskBuzz,
build_error_handler(print, lambda e: foo(e)),
)
This latter example will print the error to stdout and also call the
foo() function with the error prior to packaing it for flask's handler
"""
def _handler(error, tasks=[]):
[t(error) for t in tasks]
return error.jsonify(), error.status_code, error.headers
return functools.partial(_handler, tasks=tasks) | python | def build_error_handler(*tasks):
"""
Provides a generic error function that packages a flask_buzz exception
so that it can be handled nicely by the flask error handler::
app.register_error_handler(
FlaskBuzz, FlaskBuzz.build_error_handler(),
)
Additionally, extra tasks may be applied to the error prior to
packaging::
app.register_error_handler(
FlaskBuzz,
build_error_handler(print, lambda e: foo(e)),
)
This latter example will print the error to stdout and also call the
foo() function with the error prior to packaing it for flask's handler
"""
def _handler(error, tasks=[]):
[t(error) for t in tasks]
return error.jsonify(), error.status_code, error.headers
return functools.partial(_handler, tasks=tasks) | [
"def",
"build_error_handler",
"(",
"*",
"tasks",
")",
":",
"def",
"_handler",
"(",
"error",
",",
"tasks",
"=",
"[",
"]",
")",
":",
"[",
"t",
"(",
"error",
")",
"for",
"t",
"in",
"tasks",
"]",
"return",
"error",
".",
"jsonify",
"(",
")",
",",
"error",
".",
"status_code",
",",
"error",
".",
"headers",
"return",
"functools",
".",
"partial",
"(",
"_handler",
",",
"tasks",
"=",
"tasks",
")"
] | Provides a generic error function that packages a flask_buzz exception
so that it can be handled nicely by the flask error handler::
app.register_error_handler(
FlaskBuzz, FlaskBuzz.build_error_handler(),
)
Additionally, extra tasks may be applied to the error prior to
packaging::
app.register_error_handler(
FlaskBuzz,
build_error_handler(print, lambda e: foo(e)),
)
This latter example will print the error to stdout and also call the
foo() function with the error prior to packaing it for flask's handler | [
"Provides",
"a",
"generic",
"error",
"function",
"that",
"packages",
"a",
"flask_buzz",
"exception",
"so",
"that",
"it",
"can",
"be",
"handled",
"nicely",
"by",
"the",
"flask",
"error",
"handler",
"::"
] | train | https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L47-L72 |
dusktreader/flask-buzz | flask_buzz/__init__.py | FlaskBuzz.build_error_handler_for_flask_restplus | def build_error_handler_for_flask_restplus(*tasks):
"""
Provides a generic error function that packages a flask_buzz exception
so that it can be handled by the flask-restplus error handler::
@api.errorhandler(SFBDError)
def do_it(error):
return SFBDError.build_error_handler_for_flask_restplus()()
or::
api.errorhandler(SFBDError)(
SFBDError.build_error_handler_for_flask_restplus()
)
Flask-restplus handles exceptions differently than Flask, and it is
awkward. For further reading on why special functionality is needed for
flask-restplus, observe and compare:
* http://flask.pocoo.org/docs/0.12/patterns/apierrors/
* http://flask-restplus.readthedocs.io/en/stable/errors.html#
Additionally, extra tasks may be applied to the error prior to
packaging as in ``build_error_handler``
"""
def _handler(error, tasks=[]):
[t(error) for t in tasks]
response = error.jsonify()
return flask.json.loads(response.get_data()), response.status_code
return functools.partial(_handler, tasks=tasks) | python | def build_error_handler_for_flask_restplus(*tasks):
"""
Provides a generic error function that packages a flask_buzz exception
so that it can be handled by the flask-restplus error handler::
@api.errorhandler(SFBDError)
def do_it(error):
return SFBDError.build_error_handler_for_flask_restplus()()
or::
api.errorhandler(SFBDError)(
SFBDError.build_error_handler_for_flask_restplus()
)
Flask-restplus handles exceptions differently than Flask, and it is
awkward. For further reading on why special functionality is needed for
flask-restplus, observe and compare:
* http://flask.pocoo.org/docs/0.12/patterns/apierrors/
* http://flask-restplus.readthedocs.io/en/stable/errors.html#
Additionally, extra tasks may be applied to the error prior to
packaging as in ``build_error_handler``
"""
def _handler(error, tasks=[]):
[t(error) for t in tasks]
response = error.jsonify()
return flask.json.loads(response.get_data()), response.status_code
return functools.partial(_handler, tasks=tasks) | [
"def",
"build_error_handler_for_flask_restplus",
"(",
"*",
"tasks",
")",
":",
"def",
"_handler",
"(",
"error",
",",
"tasks",
"=",
"[",
"]",
")",
":",
"[",
"t",
"(",
"error",
")",
"for",
"t",
"in",
"tasks",
"]",
"response",
"=",
"error",
".",
"jsonify",
"(",
")",
"return",
"flask",
".",
"json",
".",
"loads",
"(",
"response",
".",
"get_data",
"(",
")",
")",
",",
"response",
".",
"status_code",
"return",
"functools",
".",
"partial",
"(",
"_handler",
",",
"tasks",
"=",
"tasks",
")"
] | Provides a generic error function that packages a flask_buzz exception
so that it can be handled by the flask-restplus error handler::
@api.errorhandler(SFBDError)
def do_it(error):
return SFBDError.build_error_handler_for_flask_restplus()()
or::
api.errorhandler(SFBDError)(
SFBDError.build_error_handler_for_flask_restplus()
)
Flask-restplus handles exceptions differently than Flask, and it is
awkward. For further reading on why special functionality is needed for
flask-restplus, observe and compare:
* http://flask.pocoo.org/docs/0.12/patterns/apierrors/
* http://flask-restplus.readthedocs.io/en/stable/errors.html#
Additionally, extra tasks may be applied to the error prior to
packaging as in ``build_error_handler`` | [
"Provides",
"a",
"generic",
"error",
"function",
"that",
"packages",
"a",
"flask_buzz",
"exception",
"so",
"that",
"it",
"can",
"be",
"handled",
"by",
"the",
"flask",
"-",
"restplus",
"error",
"handler",
"::"
] | train | https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L75-L105 |
dusktreader/flask-buzz | flask_buzz/__init__.py | FlaskBuzz.register_error_handler_with_flask_restplus | def register_error_handler_with_flask_restplus(cls, api, *tasks):
"""
Registers an error handler for FlaskBuzz derived errors that are
currently imported. This is useful since flask-restplus
(prior to 0.11.0) does not handle derived errors. This is probably the
easist way to register error handlers for FlaskBuzz errors with
flask-restplus::
FlaskBuzz.register_error_handler_with_flask_restplus(
api, print, lambda e: foo(e),
)
"""
for buzz_subclass in [cls] + cls.__subclasses__():
api.errorhandler(buzz_subclass)(
cls.build_error_handler_for_flask_restplus(*tasks)
) | python | def register_error_handler_with_flask_restplus(cls, api, *tasks):
"""
Registers an error handler for FlaskBuzz derived errors that are
currently imported. This is useful since flask-restplus
(prior to 0.11.0) does not handle derived errors. This is probably the
easist way to register error handlers for FlaskBuzz errors with
flask-restplus::
FlaskBuzz.register_error_handler_with_flask_restplus(
api, print, lambda e: foo(e),
)
"""
for buzz_subclass in [cls] + cls.__subclasses__():
api.errorhandler(buzz_subclass)(
cls.build_error_handler_for_flask_restplus(*tasks)
) | [
"def",
"register_error_handler_with_flask_restplus",
"(",
"cls",
",",
"api",
",",
"*",
"tasks",
")",
":",
"for",
"buzz_subclass",
"in",
"[",
"cls",
"]",
"+",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"api",
".",
"errorhandler",
"(",
"buzz_subclass",
")",
"(",
"cls",
".",
"build_error_handler_for_flask_restplus",
"(",
"*",
"tasks",
")",
")"
] | Registers an error handler for FlaskBuzz derived errors that are
currently imported. This is useful since flask-restplus
(prior to 0.11.0) does not handle derived errors. This is probably the
easist way to register error handlers for FlaskBuzz errors with
flask-restplus::
FlaskBuzz.register_error_handler_with_flask_restplus(
api, print, lambda e: foo(e),
) | [
"Registers",
"an",
"error",
"handler",
"for",
"FlaskBuzz",
"derived",
"errors",
"that",
"are",
"currently",
"imported",
".",
"This",
"is",
"useful",
"since",
"flask",
"-",
"restplus",
"(",
"prior",
"to",
"0",
".",
"11",
".",
"0",
")",
"does",
"not",
"handle",
"derived",
"errors",
".",
"This",
"is",
"probably",
"the",
"easist",
"way",
"to",
"register",
"error",
"handlers",
"for",
"FlaskBuzz",
"errors",
"with",
"flask",
"-",
"restplus",
"::"
] | train | https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L108-L124 |
matllubos/django-is-core | is_core/forms/models.py | humanized_model_to_dict | def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None):
"""
Returns a dict containing the humanized data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed in
the ``fields`` argument.
"""
opts = instance._meta
data = {}
for f in itertools.chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
if not getattr(f, 'editable', False):
continue
if fields and f.name not in fields:
continue
if f.name not in readonly_fields:
continue
if exclude and f.name in exclude:
continue
if f.humanized:
data[f.name] = f.humanized(getattr(instance, f.name), instance)
return data | python | def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None):
"""
Returns a dict containing the humanized data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed in
the ``fields`` argument.
"""
opts = instance._meta
data = {}
for f in itertools.chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
if not getattr(f, 'editable', False):
continue
if fields and f.name not in fields:
continue
if f.name not in readonly_fields:
continue
if exclude and f.name in exclude:
continue
if f.humanized:
data[f.name] = f.humanized(getattr(instance, f.name), instance)
return data | [
"def",
"humanized_model_to_dict",
"(",
"instance",
",",
"readonly_fields",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"opts",
"=",
"instance",
".",
"_meta",
"data",
"=",
"{",
"}",
"for",
"f",
"in",
"itertools",
".",
"chain",
"(",
"opts",
".",
"concrete_fields",
",",
"opts",
".",
"private_fields",
",",
"opts",
".",
"many_to_many",
")",
":",
"if",
"not",
"getattr",
"(",
"f",
",",
"'editable'",
",",
"False",
")",
":",
"continue",
"if",
"fields",
"and",
"f",
".",
"name",
"not",
"in",
"fields",
":",
"continue",
"if",
"f",
".",
"name",
"not",
"in",
"readonly_fields",
":",
"continue",
"if",
"exclude",
"and",
"f",
".",
"name",
"in",
"exclude",
":",
"continue",
"if",
"f",
".",
"humanized",
":",
"data",
"[",
"f",
".",
"name",
"]",
"=",
"f",
".",
"humanized",
"(",
"getattr",
"(",
"instance",
",",
"f",
".",
"name",
")",
",",
"instance",
")",
"return",
"data"
] | Returns a dict containing the humanized data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed in
the ``fields`` argument. | [
"Returns",
"a",
"dict",
"containing",
"the",
"humanized",
"data",
"in",
"instance",
"suitable",
"for",
"passing",
"as",
"a",
"Form",
"s",
"initial",
"keyword",
"argument",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/models.py#L170-L196 |
codeforamerica/three | three/cities.py | find_info | def find_info(name=None):
"""Find the needed city server information."""
if not name:
return list(servers.keys())
name = name.lower()
if name in servers:
info = servers[name]
else:
raise CityNotFound("Could not find the specified city: %s" % name)
return info | python | def find_info(name=None):
"""Find the needed city server information."""
if not name:
return list(servers.keys())
name = name.lower()
if name in servers:
info = servers[name]
else:
raise CityNotFound("Could not find the specified city: %s" % name)
return info | [
"def",
"find_info",
"(",
"name",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"return",
"list",
"(",
"servers",
".",
"keys",
"(",
")",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
"in",
"servers",
":",
"info",
"=",
"servers",
"[",
"name",
"]",
"else",
":",
"raise",
"CityNotFound",
"(",
"\"Could not find the specified city: %s\"",
"%",
"name",
")",
"return",
"info"
] | Find the needed city server information. | [
"Find",
"the",
"needed",
"city",
"server",
"information",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/cities.py#L10-L19 |
vcs-python/libvcs | libvcs/util.py | which | def which(
exe=None, default_paths=['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin']
):
"""Return path of bin. Python clone of /usr/bin/which.
from salt.util - https://www.github.com/saltstack/salt - license apache
:param exe: Application to search PATHs for.
:type exe: str
:param default_path: Application to search PATHs for.
:type default_path: list
:rtype: str
"""
def _is_executable_file_or_link(exe):
# check for os.X_OK doesn't suffice because directory may executable
return os.access(exe, os.X_OK) and (os.path.isfile(exe) or os.path.islink(exe))
if _is_executable_file_or_link(exe):
# executable in cwd or fullpath
return exe
# Enhance POSIX path for the reliability at some environments, when
# $PATH is changing. This also keeps order, where 'first came, first
# win' for cases to find optional alternatives
search_path = (
os.environ.get('PATH') and os.environ['PATH'].split(os.pathsep) or list()
)
for default_path in default_paths:
if default_path not in search_path:
search_path.append(default_path)
os.environ['PATH'] = os.pathsep.join(search_path)
for path in search_path:
full_path = os.path.join(path, exe)
if _is_executable_file_or_link(full_path):
return full_path
logger.info(
'\'{0}\' could not be found in the following search path: '
'\'{1}\''.format(exe, search_path)
)
return None | python | def which(
exe=None, default_paths=['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin']
):
"""Return path of bin. Python clone of /usr/bin/which.
from salt.util - https://www.github.com/saltstack/salt - license apache
:param exe: Application to search PATHs for.
:type exe: str
:param default_path: Application to search PATHs for.
:type default_path: list
:rtype: str
"""
def _is_executable_file_or_link(exe):
# check for os.X_OK doesn't suffice because directory may executable
return os.access(exe, os.X_OK) and (os.path.isfile(exe) or os.path.islink(exe))
if _is_executable_file_or_link(exe):
# executable in cwd or fullpath
return exe
# Enhance POSIX path for the reliability at some environments, when
# $PATH is changing. This also keeps order, where 'first came, first
# win' for cases to find optional alternatives
search_path = (
os.environ.get('PATH') and os.environ['PATH'].split(os.pathsep) or list()
)
for default_path in default_paths:
if default_path not in search_path:
search_path.append(default_path)
os.environ['PATH'] = os.pathsep.join(search_path)
for path in search_path:
full_path = os.path.join(path, exe)
if _is_executable_file_or_link(full_path):
return full_path
logger.info(
'\'{0}\' could not be found in the following search path: '
'\'{1}\''.format(exe, search_path)
)
return None | [
"def",
"which",
"(",
"exe",
"=",
"None",
",",
"default_paths",
"=",
"[",
"'/bin'",
",",
"'/sbin'",
",",
"'/usr/bin'",
",",
"'/usr/sbin'",
",",
"'/usr/local/bin'",
"]",
")",
":",
"def",
"_is_executable_file_or_link",
"(",
"exe",
")",
":",
"# check for os.X_OK doesn't suffice because directory may executable",
"return",
"os",
".",
"access",
"(",
"exe",
",",
"os",
".",
"X_OK",
")",
"and",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"exe",
")",
"or",
"os",
".",
"path",
".",
"islink",
"(",
"exe",
")",
")",
"if",
"_is_executable_file_or_link",
"(",
"exe",
")",
":",
"# executable in cwd or fullpath",
"return",
"exe",
"# Enhance POSIX path for the reliability at some environments, when",
"# $PATH is changing. This also keeps order, where 'first came, first",
"# win' for cases to find optional alternatives",
"search_path",
"=",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
")",
"and",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"or",
"list",
"(",
")",
")",
"for",
"default_path",
"in",
"default_paths",
":",
"if",
"default_path",
"not",
"in",
"search_path",
":",
"search_path",
".",
"append",
"(",
"default_path",
")",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
"=",
"os",
".",
"pathsep",
".",
"join",
"(",
"search_path",
")",
"for",
"path",
"in",
"search_path",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"exe",
")",
"if",
"_is_executable_file_or_link",
"(",
"full_path",
")",
":",
"return",
"full_path",
"logger",
".",
"info",
"(",
"'\\'{0}\\' could not be found in the following search path: '",
"'\\'{1}\\''",
".",
"format",
"(",
"exe",
",",
"search_path",
")",
")",
"return",
"None"
] | Return path of bin. Python clone of /usr/bin/which.
from salt.util - https://www.github.com/saltstack/salt - license apache
:param exe: Application to search PATHs for.
:type exe: str
:param default_path: Application to search PATHs for.
:type default_path: list
:rtype: str | [
"Return",
"path",
"of",
"bin",
".",
"Python",
"clone",
"of",
"/",
"usr",
"/",
"bin",
"/",
"which",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/util.py#L22-L63 |
vcs-python/libvcs | libvcs/util.py | run | def run(
cmd,
shell=False,
cwd=None,
log_in_real_time=True,
check_returncode=True,
callback=None,
):
""" Run 'cmd' in a shell and return the combined contents of stdout and
stderr (Blocking). Throws an exception if the command exits non-zero.
:param cmd: list of str (or single str, if shell==True) indicating
the command to run
:param shell: boolean indicating whether we are using advanced shell
features. Use only when absolutely necessary, since this allows a lot
more freedom which could be exploited by malicious code. See the
warning here:
http://docs.python.org/library/subprocess.html#popen-constructor
:param cwd: dir command is run from.
:type cwd: str
:param log_in_real_time: boolean indicating whether to read stdout from the
subprocess in real time instead of when the process finishes.
:param check_returncode: Indicate whether a :exc:`~exc.CommandError`
should be raised if return code is different from 0.
:type check_returncode: :class:`bool`
:param cwd: dir command is run from, defaults :attr:`~.path`.
:type cwd: str
:param callback: callback to return output as a command executes, accepts
a function signature of ``(output, timestamp)``. Example usage::
def progress_cb(output, timestamp):
sys.stdout.write(output)
sys.stdout.flush()
run(['git', 'pull'], callback=progrses_cb)
:type callback: func
"""
proc = subprocess.Popen(
cmd,
shell=shell,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
creationflags=0,
bufsize=1,
cwd=cwd,
)
all_output = []
code = None
line = None
while code is None:
code = proc.poll()
# output = console_to_str(proc.stdout.readline())
# all_output.append(output)
if callback and callable(callback):
line = console_to_str(proc.stderr.read(128))
if line:
callback(output=line, timestamp=datetime.datetime.now())
if callback and callable(callback):
callback(output='\r', timestamp=datetime.datetime.now())
lines = filter(None, (line.strip() for line in proc.stdout.readlines()))
all_output = console_to_str(b'\n'.join(lines))
if code:
stderr_lines = filter(None, (line.strip() for line in proc.stderr.readlines()))
all_output = console_to_str(b''.join(stderr_lines))
output = ''.join(all_output)
if code != 0 and check_returncode:
raise exc.CommandError(output=output, returncode=code, cmd=cmd)
return output | python | def run(
cmd,
shell=False,
cwd=None,
log_in_real_time=True,
check_returncode=True,
callback=None,
):
""" Run 'cmd' in a shell and return the combined contents of stdout and
stderr (Blocking). Throws an exception if the command exits non-zero.
:param cmd: list of str (or single str, if shell==True) indicating
the command to run
:param shell: boolean indicating whether we are using advanced shell
features. Use only when absolutely necessary, since this allows a lot
more freedom which could be exploited by malicious code. See the
warning here:
http://docs.python.org/library/subprocess.html#popen-constructor
:param cwd: dir command is run from.
:type cwd: str
:param log_in_real_time: boolean indicating whether to read stdout from the
subprocess in real time instead of when the process finishes.
:param check_returncode: Indicate whether a :exc:`~exc.CommandError`
should be raised if return code is different from 0.
:type check_returncode: :class:`bool`
:param cwd: dir command is run from, defaults :attr:`~.path`.
:type cwd: str
:param callback: callback to return output as a command executes, accepts
a function signature of ``(output, timestamp)``. Example usage::
def progress_cb(output, timestamp):
sys.stdout.write(output)
sys.stdout.flush()
run(['git', 'pull'], callback=progrses_cb)
:type callback: func
"""
proc = subprocess.Popen(
cmd,
shell=shell,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
creationflags=0,
bufsize=1,
cwd=cwd,
)
all_output = []
code = None
line = None
while code is None:
code = proc.poll()
# output = console_to_str(proc.stdout.readline())
# all_output.append(output)
if callback and callable(callback):
line = console_to_str(proc.stderr.read(128))
if line:
callback(output=line, timestamp=datetime.datetime.now())
if callback and callable(callback):
callback(output='\r', timestamp=datetime.datetime.now())
lines = filter(None, (line.strip() for line in proc.stdout.readlines()))
all_output = console_to_str(b'\n'.join(lines))
if code:
stderr_lines = filter(None, (line.strip() for line in proc.stderr.readlines()))
all_output = console_to_str(b''.join(stderr_lines))
output = ''.join(all_output)
if code != 0 and check_returncode:
raise exc.CommandError(output=output, returncode=code, cmd=cmd)
return output | [
"def",
"run",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"log_in_real_time",
"=",
"True",
",",
"check_returncode",
"=",
"True",
",",
"callback",
"=",
"None",
",",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"shell",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"creationflags",
"=",
"0",
",",
"bufsize",
"=",
"1",
",",
"cwd",
"=",
"cwd",
",",
")",
"all_output",
"=",
"[",
"]",
"code",
"=",
"None",
"line",
"=",
"None",
"while",
"code",
"is",
"None",
":",
"code",
"=",
"proc",
".",
"poll",
"(",
")",
"# output = console_to_str(proc.stdout.readline())",
"# all_output.append(output)",
"if",
"callback",
"and",
"callable",
"(",
"callback",
")",
":",
"line",
"=",
"console_to_str",
"(",
"proc",
".",
"stderr",
".",
"read",
"(",
"128",
")",
")",
"if",
"line",
":",
"callback",
"(",
"output",
"=",
"line",
",",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"if",
"callback",
"and",
"callable",
"(",
"callback",
")",
":",
"callback",
"(",
"output",
"=",
"'\\r'",
",",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"lines",
"=",
"filter",
"(",
"None",
",",
"(",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"proc",
".",
"stdout",
".",
"readlines",
"(",
")",
")",
")",
"all_output",
"=",
"console_to_str",
"(",
"b'\\n'",
".",
"join",
"(",
"lines",
")",
")",
"if",
"code",
":",
"stderr_lines",
"=",
"filter",
"(",
"None",
",",
"(",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"proc",
".",
"stderr",
".",
"readlines",
"(",
")",
")",
")",
"all_output",
"=",
"console_to_str",
"(",
"b''",
".",
"join",
"(",
"stderr_lines",
")",
")",
"output",
"=",
"''",
".",
"join",
"(",
"all_output",
")",
"if",
"code",
"!=",
"0",
"and",
"check_returncode",
":",
"raise",
"exc",
".",
"CommandError",
"(",
"output",
"=",
"output",
",",
"returncode",
"=",
"code",
",",
"cmd",
"=",
"cmd",
")",
"return",
"output"
] | Run 'cmd' in a shell and return the combined contents of stdout and
stderr (Blocking). Throws an exception if the command exits non-zero.
:param cmd: list of str (or single str, if shell==True) indicating
the command to run
:param shell: boolean indicating whether we are using advanced shell
features. Use only when absolutely necessary, since this allows a lot
more freedom which could be exploited by malicious code. See the
warning here:
http://docs.python.org/library/subprocess.html#popen-constructor
:param cwd: dir command is run from.
:type cwd: str
:param log_in_real_time: boolean indicating whether to read stdout from the
subprocess in real time instead of when the process finishes.
:param check_returncode: Indicate whether a :exc:`~exc.CommandError`
should be raised if return code is different from 0.
:type check_returncode: :class:`bool`
:param cwd: dir command is run from, defaults :attr:`~.path`.
:type cwd: str
:param callback: callback to return output as a command executes, accepts
a function signature of ``(output, timestamp)``. Example usage::
def progress_cb(output, timestamp):
sys.stdout.write(output)
sys.stdout.flush()
run(['git', 'pull'], callback=progrses_cb)
:type callback: func | [
"Run",
"cmd",
"in",
"a",
"shell",
"and",
"return",
"the",
"combined",
"contents",
"of",
"stdout",
"and",
"stderr",
"(",
"Blocking",
")",
".",
"Throws",
"an",
"exception",
"if",
"the",
"command",
"exits",
"non",
"-",
"zero",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/util.py#L116-L185 |
vcs-python/libvcs | libvcs/util.py | RepoLoggingAdapter.process | def process(self, msg, kwargs):
"""Add additional context information for loggers."""
prefixed_dict = {}
prefixed_dict['repo_vcs'] = self.bin_name
prefixed_dict['repo_name'] = self.name
kwargs["extra"] = prefixed_dict
return msg, kwargs | python | def process(self, msg, kwargs):
"""Add additional context information for loggers."""
prefixed_dict = {}
prefixed_dict['repo_vcs'] = self.bin_name
prefixed_dict['repo_name'] = self.name
kwargs["extra"] = prefixed_dict
return msg, kwargs | [
"def",
"process",
"(",
"self",
",",
"msg",
",",
"kwargs",
")",
":",
"prefixed_dict",
"=",
"{",
"}",
"prefixed_dict",
"[",
"'repo_vcs'",
"]",
"=",
"self",
".",
"bin_name",
"prefixed_dict",
"[",
"'repo_name'",
"]",
"=",
"self",
".",
"name",
"kwargs",
"[",
"\"extra\"",
"]",
"=",
"prefixed_dict",
"return",
"msg",
",",
"kwargs"
] | Add additional context information for loggers. | [
"Add",
"additional",
"context",
"information",
"for",
"loggers",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/util.py#L105-L113 |
IwoHerka/sexpr | sexpr/types/sequence.py | Sequence.pop | def pop(self, sexp):
'''
Notes: Sequence works a bit different than other nodes.
This method (like others) expectes a list. However, sequence matches
against the list, whereas other nodes try to match against elements
of the list.
'''
for t in self.terms:
sexp = t.pop(sexp)
return sexp | python | def pop(self, sexp):
'''
Notes: Sequence works a bit different than other nodes.
This method (like others) expectes a list. However, sequence matches
against the list, whereas other nodes try to match against elements
of the list.
'''
for t in self.terms:
sexp = t.pop(sexp)
return sexp | [
"def",
"pop",
"(",
"self",
",",
"sexp",
")",
":",
"for",
"t",
"in",
"self",
".",
"terms",
":",
"sexp",
"=",
"t",
".",
"pop",
"(",
"sexp",
")",
"return",
"sexp"
] | Notes: Sequence works a bit different than other nodes.
This method (like others) expectes a list. However, sequence matches
against the list, whereas other nodes try to match against elements
of the list. | [
"Notes",
":",
"Sequence",
"works",
"a",
"bit",
"different",
"than",
"other",
"nodes",
".",
"This",
"method",
"(",
"like",
"others",
")",
"expectes",
"a",
"list",
".",
"However",
"sequence",
"matches",
"against",
"the",
"list",
"whereas",
"other",
"nodes",
"try",
"to",
"match",
"against",
"elements",
"of",
"the",
"list",
"."
] | train | https://github.com/IwoHerka/sexpr/blob/28e32f543a127bbbf832b2dba7cb93f9e57db3b6/sexpr/types/sequence.py#L11-L20 |
xapple/plumbing | plumbing/git.py | GitRepo.branches | def branches(self):
"""All branches in a list"""
result = self.git(self.default + ['branch', '-a', '--no-color'])
return [l.strip(' *\n') for l in result.split('\n') if l.strip(' *\n')] | python | def branches(self):
"""All branches in a list"""
result = self.git(self.default + ['branch', '-a', '--no-color'])
return [l.strip(' *\n') for l in result.split('\n') if l.strip(' *\n')] | [
"def",
"branches",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"git",
"(",
"self",
".",
"default",
"+",
"[",
"'branch'",
",",
"'-a'",
",",
"'--no-color'",
"]",
")",
"return",
"[",
"l",
".",
"strip",
"(",
"' *\\n'",
")",
"for",
"l",
"in",
"result",
".",
"split",
"(",
"'\\n'",
")",
"if",
"l",
".",
"strip",
"(",
"' *\\n'",
")",
"]"
] | All branches in a list | [
"All",
"branches",
"in",
"a",
"list"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/git.py#L64-L67 |
xapple/plumbing | plumbing/git.py | GitRepo.re_clone | def re_clone(self, repo_dir):
"""Clone again, somewhere else"""
self.git('clone', self.remote_url, repo_dir)
return GitRepo(repo_dir) | python | def re_clone(self, repo_dir):
"""Clone again, somewhere else"""
self.git('clone', self.remote_url, repo_dir)
return GitRepo(repo_dir) | [
"def",
"re_clone",
"(",
"self",
",",
"repo_dir",
")",
":",
"self",
".",
"git",
"(",
"'clone'",
",",
"self",
".",
"remote_url",
",",
"repo_dir",
")",
"return",
"GitRepo",
"(",
"repo_dir",
")"
] | Clone again, somewhere else | [
"Clone",
"again",
"somewhere",
"else"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/git.py#L87-L90 |
xapple/plumbing | plumbing/trees/__init__.py | Node.path | def path(self):
"""Iterate over all parent nodes and one-self."""
yield self
if not self.parent: return
for node in self.parent.path: yield node | python | def path(self):
"""Iterate over all parent nodes and one-self."""
yield self
if not self.parent: return
for node in self.parent.path: yield node | [
"def",
"path",
"(",
"self",
")",
":",
"yield",
"self",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"for",
"node",
"in",
"self",
".",
"parent",
".",
"path",
":",
"yield",
"node"
] | Iterate over all parent nodes and one-self. | [
"Iterate",
"over",
"all",
"parent",
"nodes",
"and",
"one",
"-",
"self",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L40-L44 |
xapple/plumbing | plumbing/trees/__init__.py | Node.others | def others(self):
"""Iterate over all nodes of the tree excluding one self and one's children."""
if not self.parent: return
yield self.parent
for sibling in self.parent.children.values():
if sibling.name == self.name: continue
for node in sibling: yield node
for node in self.parent.others: yield node | python | def others(self):
"""Iterate over all nodes of the tree excluding one self and one's children."""
if not self.parent: return
yield self.parent
for sibling in self.parent.children.values():
if sibling.name == self.name: continue
for node in sibling: yield node
for node in self.parent.others: yield node | [
"def",
"others",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"yield",
"self",
".",
"parent",
"for",
"sibling",
"in",
"self",
".",
"parent",
".",
"children",
".",
"values",
"(",
")",
":",
"if",
"sibling",
".",
"name",
"==",
"self",
".",
"name",
":",
"continue",
"for",
"node",
"in",
"sibling",
":",
"yield",
"node",
"for",
"node",
"in",
"self",
".",
"parent",
".",
"others",
":",
"yield",
"node"
] | Iterate over all nodes of the tree excluding one self and one's children. | [
"Iterate",
"over",
"all",
"nodes",
"of",
"the",
"tree",
"excluding",
"one",
"self",
"and",
"one",
"s",
"children",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L47-L54 |
xapple/plumbing | plumbing/trees/__init__.py | Node.get_children | def get_children(self, depth=1):
"""Iterate over all children (until a certain level) and one-self."""
yield self
if depth == 0: return
for child in self.children.values():
for node in child.get_children(depth-1): yield node | python | def get_children(self, depth=1):
"""Iterate over all children (until a certain level) and one-self."""
yield self
if depth == 0: return
for child in self.children.values():
for node in child.get_children(depth-1): yield node | [
"def",
"get_children",
"(",
"self",
",",
"depth",
"=",
"1",
")",
":",
"yield",
"self",
"if",
"depth",
"==",
"0",
":",
"return",
"for",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"for",
"node",
"in",
"child",
".",
"get_children",
"(",
"depth",
"-",
"1",
")",
":",
"yield",
"node"
] | Iterate over all children (until a certain level) and one-self. | [
"Iterate",
"over",
"all",
"children",
"(",
"until",
"a",
"certain",
"level",
")",
"and",
"one",
"-",
"self",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L56-L61 |
xapple/plumbing | plumbing/trees/__init__.py | Node.get_level | def get_level(self, level=2):
"""Get all nodes that are exactly this far away."""
if level == 1:
for child in self.children.values(): yield child
else:
for child in self.children.values():
for node in child.get_level(level-1): yield node | python | def get_level(self, level=2):
"""Get all nodes that are exactly this far away."""
if level == 1:
for child in self.children.values(): yield child
else:
for child in self.children.values():
for node in child.get_level(level-1): yield node | [
"def",
"get_level",
"(",
"self",
",",
"level",
"=",
"2",
")",
":",
"if",
"level",
"==",
"1",
":",
"for",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"yield",
"child",
"else",
":",
"for",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"for",
"node",
"in",
"child",
".",
"get_level",
"(",
"level",
"-",
"1",
")",
":",
"yield",
"node"
] | Get all nodes that are exactly this far away. | [
"Get",
"all",
"nodes",
"that",
"are",
"exactly",
"this",
"far",
"away",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L63-L69 |
xapple/plumbing | plumbing/trees/__init__.py | Node.trim | def trim(self, length):
"""Cut all branches over a certain length making new leaves at *length*."""
if length > 0:
for child in self.children.values(): child.trim(length-1)
else:
if hasattr(self, 'count'): self.count = sum(map(lambda x: x.count, self))
self.children = OrderedDict() | python | def trim(self, length):
"""Cut all branches over a certain length making new leaves at *length*."""
if length > 0:
for child in self.children.values(): child.trim(length-1)
else:
if hasattr(self, 'count'): self.count = sum(map(lambda x: x.count, self))
self.children = OrderedDict() | [
"def",
"trim",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
">",
"0",
":",
"for",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"child",
".",
"trim",
"(",
"length",
"-",
"1",
")",
"else",
":",
"if",
"hasattr",
"(",
"self",
",",
"'count'",
")",
":",
"self",
".",
"count",
"=",
"sum",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"count",
",",
"self",
")",
")",
"self",
".",
"children",
"=",
"OrderedDict",
"(",
")"
] | Cut all branches over a certain length making new leaves at *length*. | [
"Cut",
"all",
"branches",
"over",
"a",
"certain",
"length",
"making",
"new",
"leaves",
"at",
"*",
"length",
"*",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L88-L94 |
xapple/plumbing | plumbing/trees/__init__.py | Node.mend | def mend(self, length):
"""Cut all branches from this node to its children and adopt
all nodes at certain level."""
if length == 0: raise Exception("Can't mend the root !")
if length == 1: return
self.children = OrderedDict((node.name, node) for node in self.get_level(length))
for child in self.children.values(): child.parent = self | python | def mend(self, length):
"""Cut all branches from this node to its children and adopt
all nodes at certain level."""
if length == 0: raise Exception("Can't mend the root !")
if length == 1: return
self.children = OrderedDict((node.name, node) for node in self.get_level(length))
for child in self.children.values(): child.parent = self | [
"def",
"mend",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"Can't mend the root !\"",
")",
"if",
"length",
"==",
"1",
":",
"return",
"self",
".",
"children",
"=",
"OrderedDict",
"(",
"(",
"node",
".",
"name",
",",
"node",
")",
"for",
"node",
"in",
"self",
".",
"get_level",
"(",
"length",
")",
")",
"for",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"child",
".",
"parent",
"=",
"self"
] | Cut all branches from this node to its children and adopt
all nodes at certain level. | [
"Cut",
"all",
"branches",
"from",
"this",
"node",
"to",
"its",
"children",
"and",
"adopt",
"all",
"nodes",
"at",
"certain",
"level",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L96-L102 |
softwarefactory-project/distroinfo | distroinfo/info.py | DistroInfo.get_info | def get_info(self, apply_tag=None, info_dicts=False):
"""
Get data from distroinfo instance.
:param apply_tag: apply supplied tag to info
:param info_dicts: return packages and releases as dicts
:return: parsed info metadata
"""
raw_infos = self.fetcher.fetch(*self.info_files)
raw_info = parse.merge_infos(*raw_infos, info_dicts=info_dicts)
info = parse.parse_info(raw_info, apply_tag=apply_tag)
return info | python | def get_info(self, apply_tag=None, info_dicts=False):
"""
Get data from distroinfo instance.
:param apply_tag: apply supplied tag to info
:param info_dicts: return packages and releases as dicts
:return: parsed info metadata
"""
raw_infos = self.fetcher.fetch(*self.info_files)
raw_info = parse.merge_infos(*raw_infos, info_dicts=info_dicts)
info = parse.parse_info(raw_info, apply_tag=apply_tag)
return info | [
"def",
"get_info",
"(",
"self",
",",
"apply_tag",
"=",
"None",
",",
"info_dicts",
"=",
"False",
")",
":",
"raw_infos",
"=",
"self",
".",
"fetcher",
".",
"fetch",
"(",
"*",
"self",
".",
"info_files",
")",
"raw_info",
"=",
"parse",
".",
"merge_infos",
"(",
"*",
"raw_infos",
",",
"info_dicts",
"=",
"info_dicts",
")",
"info",
"=",
"parse",
".",
"parse_info",
"(",
"raw_info",
",",
"apply_tag",
"=",
"apply_tag",
")",
"return",
"info"
] | Get data from distroinfo instance.
:param apply_tag: apply supplied tag to info
:param info_dicts: return packages and releases as dicts
:return: parsed info metadata | [
"Get",
"data",
"from",
"distroinfo",
"instance",
"."
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/info.py#L53-L64 |
sprockets/sprockets.http | sprockets/http/__init__.py | run | def run(create_application, settings=None, log_config=None):
"""
Run a Tornado create_application.
:param create_application: function to call to create a new
application instance
:param dict|None settings: optional configuration dictionary
that will be passed through to ``create_application``
as kwargs.
:param dict|None log_config: optional logging configuration
dictionary to use. By default, a reasonable logging
configuration is generated based on settings. If you
need to override the configuration, then use this parameter.
It is passed as-is to :func:`logging.config.dictConfig`.
.. rubric:: settings['debug']
If the `settings` parameter includes a value for the ``debug``
key, then the application will be run in Tornado debug mode.
If the `settings` parameter does not include a ``debug`` key,
then debug mode will be enabled based on the :envvar:`DEBUG`
environment variable.
.. rubric:: settings['port']
If the `settings` parameter includes a value for the ``port``
key, then the application will be configured to listen on the
specified port. If this key is not present, then the :envvar:`PORT`
environment variable determines which port to bind to. The
default port is 8000 if nothing overrides it.
.. rubric:: settings['number_of_procs']
If the `settings` parameter includes a value for the ``number_of_procs``
key, then the application will be configured to run this many processes
unless in *debug* mode. This is passed to ``HTTPServer.start``.
.. rubric:: settings['xheaders']
If the `settings` parameter includes a value for the ``xheaders``
key, then the application will be configured to use headers, like
X-Real-IP, to get the user's IP address instead of attributing all
traffic to the load balancer's IP address. When running behind a load
balancer like nginx, it is recommended to pass xheaders=True. The default
value is False if nothing overrides it.
"""
from . import runner
app_settings = {} if settings is None else settings.copy()
debug_mode = bool(app_settings.get('debug',
int(os.environ.get('DEBUG', 0)) != 0))
app_settings['debug'] = debug_mode
logging.config.dictConfig(_get_logging_config(debug_mode)
if log_config is None else log_config)
port_number = int(app_settings.pop('port', os.environ.get('PORT', 8000)))
num_procs = int(app_settings.pop('number_of_procs', '0'))
server = runner.Runner(create_application(**app_settings))
server.run(port_number, num_procs) | python | def run(create_application, settings=None, log_config=None):
"""
Run a Tornado create_application.
:param create_application: function to call to create a new
application instance
:param dict|None settings: optional configuration dictionary
that will be passed through to ``create_application``
as kwargs.
:param dict|None log_config: optional logging configuration
dictionary to use. By default, a reasonable logging
configuration is generated based on settings. If you
need to override the configuration, then use this parameter.
It is passed as-is to :func:`logging.config.dictConfig`.
.. rubric:: settings['debug']
If the `settings` parameter includes a value for the ``debug``
key, then the application will be run in Tornado debug mode.
If the `settings` parameter does not include a ``debug`` key,
then debug mode will be enabled based on the :envvar:`DEBUG`
environment variable.
.. rubric:: settings['port']
If the `settings` parameter includes a value for the ``port``
key, then the application will be configured to listen on the
specified port. If this key is not present, then the :envvar:`PORT`
environment variable determines which port to bind to. The
default port is 8000 if nothing overrides it.
.. rubric:: settings['number_of_procs']
If the `settings` parameter includes a value for the ``number_of_procs``
key, then the application will be configured to run this many processes
unless in *debug* mode. This is passed to ``HTTPServer.start``.
.. rubric:: settings['xheaders']
If the `settings` parameter includes a value for the ``xheaders``
key, then the application will be configured to use headers, like
X-Real-IP, to get the user's IP address instead of attributing all
traffic to the load balancer's IP address. When running behind a load
balancer like nginx, it is recommended to pass xheaders=True. The default
value is False if nothing overrides it.
"""
from . import runner
app_settings = {} if settings is None else settings.copy()
debug_mode = bool(app_settings.get('debug',
int(os.environ.get('DEBUG', 0)) != 0))
app_settings['debug'] = debug_mode
logging.config.dictConfig(_get_logging_config(debug_mode)
if log_config is None else log_config)
port_number = int(app_settings.pop('port', os.environ.get('PORT', 8000)))
num_procs = int(app_settings.pop('number_of_procs', '0'))
server = runner.Runner(create_application(**app_settings))
server.run(port_number, num_procs) | [
"def",
"run",
"(",
"create_application",
",",
"settings",
"=",
"None",
",",
"log_config",
"=",
"None",
")",
":",
"from",
".",
"import",
"runner",
"app_settings",
"=",
"{",
"}",
"if",
"settings",
"is",
"None",
"else",
"settings",
".",
"copy",
"(",
")",
"debug_mode",
"=",
"bool",
"(",
"app_settings",
".",
"get",
"(",
"'debug'",
",",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'DEBUG'",
",",
"0",
")",
")",
"!=",
"0",
")",
")",
"app_settings",
"[",
"'debug'",
"]",
"=",
"debug_mode",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"_get_logging_config",
"(",
"debug_mode",
")",
"if",
"log_config",
"is",
"None",
"else",
"log_config",
")",
"port_number",
"=",
"int",
"(",
"app_settings",
".",
"pop",
"(",
"'port'",
",",
"os",
".",
"environ",
".",
"get",
"(",
"'PORT'",
",",
"8000",
")",
")",
")",
"num_procs",
"=",
"int",
"(",
"app_settings",
".",
"pop",
"(",
"'number_of_procs'",
",",
"'0'",
")",
")",
"server",
"=",
"runner",
".",
"Runner",
"(",
"create_application",
"(",
"*",
"*",
"app_settings",
")",
")",
"server",
".",
"run",
"(",
"port_number",
",",
"num_procs",
")"
] | Run a Tornado create_application.
:param create_application: function to call to create a new
application instance
:param dict|None settings: optional configuration dictionary
that will be passed through to ``create_application``
as kwargs.
:param dict|None log_config: optional logging configuration
dictionary to use. By default, a reasonable logging
configuration is generated based on settings. If you
need to override the configuration, then use this parameter.
It is passed as-is to :func:`logging.config.dictConfig`.
.. rubric:: settings['debug']
If the `settings` parameter includes a value for the ``debug``
key, then the application will be run in Tornado debug mode.
If the `settings` parameter does not include a ``debug`` key,
then debug mode will be enabled based on the :envvar:`DEBUG`
environment variable.
.. rubric:: settings['port']
If the `settings` parameter includes a value for the ``port``
key, then the application will be configured to listen on the
specified port. If this key is not present, then the :envvar:`PORT`
environment variable determines which port to bind to. The
default port is 8000 if nothing overrides it.
.. rubric:: settings['number_of_procs']
If the `settings` parameter includes a value for the ``number_of_procs``
key, then the application will be configured to run this many processes
unless in *debug* mode. This is passed to ``HTTPServer.start``.
.. rubric:: settings['xheaders']
If the `settings` parameter includes a value for the ``xheaders``
key, then the application will be configured to use headers, like
X-Real-IP, to get the user's IP address instead of attributing all
traffic to the load balancer's IP address. When running behind a load
balancer like nginx, it is recommended to pass xheaders=True. The default
value is False if nothing overrides it. | [
"Run",
"a",
"Tornado",
"create_application",
"."
] | train | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/__init__.py#L10-L71 |
vcs-python/libvcs | libvcs/git.py | GitRepo.get_url_and_revision_from_pip_url | def get_url_and_revision_from_pip_url(cls, pip_url):
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes doesn't
work with a ssh:// scheme (e.g. Github). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
The manpage for git-clone(1) refers to this as the "scp-like styntax".
"""
if '://' not in pip_url:
assert 'file:' not in pip_url
pip_url = pip_url.replace('git+', 'git+ssh://')
url, rev = super(GitRepo, cls).get_url_and_revision_from_pip_url(pip_url)
url = url.replace('ssh://', '')
elif 'github.com:' in pip_url:
raise exc.LibVCSException(
"Repo %s is malformatted, please use the convention %s for"
"ssh / private GitHub repositories."
% (pip_url, "git+https://github.com/username/repo.git")
)
else:
url, rev = super(GitRepo, cls).get_url_and_revision_from_pip_url(pip_url)
return url, rev | python | def get_url_and_revision_from_pip_url(cls, pip_url):
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes doesn't
work with a ssh:// scheme (e.g. Github). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
The manpage for git-clone(1) refers to this as the "scp-like styntax".
"""
if '://' not in pip_url:
assert 'file:' not in pip_url
pip_url = pip_url.replace('git+', 'git+ssh://')
url, rev = super(GitRepo, cls).get_url_and_revision_from_pip_url(pip_url)
url = url.replace('ssh://', '')
elif 'github.com:' in pip_url:
raise exc.LibVCSException(
"Repo %s is malformatted, please use the convention %s for"
"ssh / private GitHub repositories."
% (pip_url, "git+https://github.com/username/repo.git")
)
else:
url, rev = super(GitRepo, cls).get_url_and_revision_from_pip_url(pip_url)
return url, rev | [
"def",
"get_url_and_revision_from_pip_url",
"(",
"cls",
",",
"pip_url",
")",
":",
"if",
"'://'",
"not",
"in",
"pip_url",
":",
"assert",
"'file:'",
"not",
"in",
"pip_url",
"pip_url",
"=",
"pip_url",
".",
"replace",
"(",
"'git+'",
",",
"'git+ssh://'",
")",
"url",
",",
"rev",
"=",
"super",
"(",
"GitRepo",
",",
"cls",
")",
".",
"get_url_and_revision_from_pip_url",
"(",
"pip_url",
")",
"url",
"=",
"url",
".",
"replace",
"(",
"'ssh://'",
",",
"''",
")",
"elif",
"'github.com:'",
"in",
"pip_url",
":",
"raise",
"exc",
".",
"LibVCSException",
"(",
"\"Repo %s is malformatted, please use the convention %s for\"",
"\"ssh / private GitHub repositories.\"",
"%",
"(",
"pip_url",
",",
"\"git+https://github.com/username/repo.git\"",
")",
")",
"else",
":",
"url",
",",
"rev",
"=",
"super",
"(",
"GitRepo",
",",
"cls",
")",
".",
"get_url_and_revision_from_pip_url",
"(",
"pip_url",
")",
"return",
"url",
",",
"rev"
] | Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes doesn't
work with a ssh:// scheme (e.g. Github). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
The manpage for git-clone(1) refers to this as the "scp-like styntax". | [
"Prefixes",
"stub",
"URLs",
"like",
"user"
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L85-L107 |
vcs-python/libvcs | libvcs/git.py | GitRepo.obtain | def obtain(self):
"""Retrieve the repository, clone if doesn't exist."""
self.check_destination()
url = self.url
cmd = ['clone', '--progress']
if self.git_shallow:
cmd.extend(['--depth', '1'])
if self.tls_verify:
cmd.extend(['-c', 'http.sslVerify=false'])
cmd.extend([url, self.path])
self.info('Cloning.')
self.run(cmd, log_in_real_time=True)
if self.remotes:
for r in self.remotes:
self.error('Adding remote %s <%s>' % (r['remote_name'], r['url']))
self.remote_set(name=r['remote_name'], url=r['url'])
self.info('Initializing submodules.')
self.run(['submodule', 'init'], log_in_real_time=True)
cmd = ['submodule', 'update', '--recursive', '--init']
cmd.extend(self.git_submodules)
self.run(cmd, log_in_real_time=True) | python | def obtain(self):
"""Retrieve the repository, clone if doesn't exist."""
self.check_destination()
url = self.url
cmd = ['clone', '--progress']
if self.git_shallow:
cmd.extend(['--depth', '1'])
if self.tls_verify:
cmd.extend(['-c', 'http.sslVerify=false'])
cmd.extend([url, self.path])
self.info('Cloning.')
self.run(cmd, log_in_real_time=True)
if self.remotes:
for r in self.remotes:
self.error('Adding remote %s <%s>' % (r['remote_name'], r['url']))
self.remote_set(name=r['remote_name'], url=r['url'])
self.info('Initializing submodules.')
self.run(['submodule', 'init'], log_in_real_time=True)
cmd = ['submodule', 'update', '--recursive', '--init']
cmd.extend(self.git_submodules)
self.run(cmd, log_in_real_time=True) | [
"def",
"obtain",
"(",
"self",
")",
":",
"self",
".",
"check_destination",
"(",
")",
"url",
"=",
"self",
".",
"url",
"cmd",
"=",
"[",
"'clone'",
",",
"'--progress'",
"]",
"if",
"self",
".",
"git_shallow",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--depth'",
",",
"'1'",
"]",
")",
"if",
"self",
".",
"tls_verify",
":",
"cmd",
".",
"extend",
"(",
"[",
"'-c'",
",",
"'http.sslVerify=false'",
"]",
")",
"cmd",
".",
"extend",
"(",
"[",
"url",
",",
"self",
".",
"path",
"]",
")",
"self",
".",
"info",
"(",
"'Cloning.'",
")",
"self",
".",
"run",
"(",
"cmd",
",",
"log_in_real_time",
"=",
"True",
")",
"if",
"self",
".",
"remotes",
":",
"for",
"r",
"in",
"self",
".",
"remotes",
":",
"self",
".",
"error",
"(",
"'Adding remote %s <%s>'",
"%",
"(",
"r",
"[",
"'remote_name'",
"]",
",",
"r",
"[",
"'url'",
"]",
")",
")",
"self",
".",
"remote_set",
"(",
"name",
"=",
"r",
"[",
"'remote_name'",
"]",
",",
"url",
"=",
"r",
"[",
"'url'",
"]",
")",
"self",
".",
"info",
"(",
"'Initializing submodules.'",
")",
"self",
".",
"run",
"(",
"[",
"'submodule'",
",",
"'init'",
"]",
",",
"log_in_real_time",
"=",
"True",
")",
"cmd",
"=",
"[",
"'submodule'",
",",
"'update'",
",",
"'--recursive'",
",",
"'--init'",
"]",
"cmd",
".",
"extend",
"(",
"self",
".",
"git_submodules",
")",
"self",
".",
"run",
"(",
"cmd",
",",
"log_in_real_time",
"=",
"True",
")"
] | Retrieve the repository, clone if doesn't exist. | [
"Retrieve",
"the",
"repository",
"clone",
"if",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L109-L134 |
vcs-python/libvcs | libvcs/git.py | GitRepo.remotes_get | def remotes_get(self):
"""Return remotes like git remote -v.
:rtype: dict of tuples
"""
remotes = {}
cmd = self.run(['remote'])
ret = filter(None, cmd.split('\n'))
for remote_name in ret:
remotes[remote_name] = self.remote_get(remote_name)
return remotes | python | def remotes_get(self):
"""Return remotes like git remote -v.
:rtype: dict of tuples
"""
remotes = {}
cmd = self.run(['remote'])
ret = filter(None, cmd.split('\n'))
for remote_name in ret:
remotes[remote_name] = self.remote_get(remote_name)
return remotes | [
"def",
"remotes_get",
"(",
"self",
")",
":",
"remotes",
"=",
"{",
"}",
"cmd",
"=",
"self",
".",
"run",
"(",
"[",
"'remote'",
"]",
")",
"ret",
"=",
"filter",
"(",
"None",
",",
"cmd",
".",
"split",
"(",
"'\\n'",
")",
")",
"for",
"remote_name",
"in",
"ret",
":",
"remotes",
"[",
"remote_name",
"]",
"=",
"self",
".",
"remote_get",
"(",
"remote_name",
")",
"return",
"remotes"
] | Return remotes like git remote -v.
:rtype: dict of tuples | [
"Return",
"remotes",
"like",
"git",
"remote",
"-",
"v",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L273-L285 |
vcs-python/libvcs | libvcs/git.py | GitRepo.remote_get | def remote_get(self, remote='origin'):
"""Get the fetch and push URL for a specified remote name.
:param remote: the remote name used to define the fetch and push URL
:type remote: str
:returns: remote name and url in tuple form
:rtype: tuple
"""
try:
ret = self.run(['remote', 'show', '-n', remote])
lines = ret.split('\n')
remote_fetch_url = lines[1].replace('Fetch URL: ', '').strip()
remote_push_url = lines[2].replace('Push URL: ', '').strip()
if remote_fetch_url != remote and remote_push_url != remote:
res = (remote_fetch_url, remote_push_url)
return res
else:
return None
except exc.LibVCSException:
return None | python | def remote_get(self, remote='origin'):
"""Get the fetch and push URL for a specified remote name.
:param remote: the remote name used to define the fetch and push URL
:type remote: str
:returns: remote name and url in tuple form
:rtype: tuple
"""
try:
ret = self.run(['remote', 'show', '-n', remote])
lines = ret.split('\n')
remote_fetch_url = lines[1].replace('Fetch URL: ', '').strip()
remote_push_url = lines[2].replace('Push URL: ', '').strip()
if remote_fetch_url != remote and remote_push_url != remote:
res = (remote_fetch_url, remote_push_url)
return res
else:
return None
except exc.LibVCSException:
return None | [
"def",
"remote_get",
"(",
"self",
",",
"remote",
"=",
"'origin'",
")",
":",
"try",
":",
"ret",
"=",
"self",
".",
"run",
"(",
"[",
"'remote'",
",",
"'show'",
",",
"'-n'",
",",
"remote",
"]",
")",
"lines",
"=",
"ret",
".",
"split",
"(",
"'\\n'",
")",
"remote_fetch_url",
"=",
"lines",
"[",
"1",
"]",
".",
"replace",
"(",
"'Fetch URL: '",
",",
"''",
")",
".",
"strip",
"(",
")",
"remote_push_url",
"=",
"lines",
"[",
"2",
"]",
".",
"replace",
"(",
"'Push URL: '",
",",
"''",
")",
".",
"strip",
"(",
")",
"if",
"remote_fetch_url",
"!=",
"remote",
"and",
"remote_push_url",
"!=",
"remote",
":",
"res",
"=",
"(",
"remote_fetch_url",
",",
"remote_push_url",
")",
"return",
"res",
"else",
":",
"return",
"None",
"except",
"exc",
".",
"LibVCSException",
":",
"return",
"None"
] | Get the fetch and push URL for a specified remote name.
:param remote: the remote name used to define the fetch and push URL
:type remote: str
:returns: remote name and url in tuple form
:rtype: tuple | [
"Get",
"the",
"fetch",
"and",
"push",
"URL",
"for",
"a",
"specified",
"remote",
"name",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L287-L306 |
vcs-python/libvcs | libvcs/git.py | GitRepo.remote_set | def remote_set(self, url, name='origin'):
"""Set remote with name and URL like git remote add.
:param url: defines the remote URL
:type url: str
:param name: defines the remote name.
:type name: str
"""
url = self.chomp_protocol(url)
if self.remote_get(name):
self.run(['remote', 'rm', 'name'])
self.run(['remote', 'add', name, url])
return self.remote_get(remote=name) | python | def remote_set(self, url, name='origin'):
"""Set remote with name and URL like git remote add.
:param url: defines the remote URL
:type url: str
:param name: defines the remote name.
:type name: str
"""
url = self.chomp_protocol(url)
if self.remote_get(name):
self.run(['remote', 'rm', 'name'])
self.run(['remote', 'add', name, url])
return self.remote_get(remote=name) | [
"def",
"remote_set",
"(",
"self",
",",
"url",
",",
"name",
"=",
"'origin'",
")",
":",
"url",
"=",
"self",
".",
"chomp_protocol",
"(",
"url",
")",
"if",
"self",
".",
"remote_get",
"(",
"name",
")",
":",
"self",
".",
"run",
"(",
"[",
"'remote'",
",",
"'rm'",
",",
"'name'",
"]",
")",
"self",
".",
"run",
"(",
"[",
"'remote'",
",",
"'add'",
",",
"name",
",",
"url",
"]",
")",
"return",
"self",
".",
"remote_get",
"(",
"remote",
"=",
"name",
")"
] | Set remote with name and URL like git remote add.
:param url: defines the remote URL
:type url: str
:param name: defines the remote name.
:type name: str | [
"Set",
"remote",
"with",
"name",
"and",
"URL",
"like",
"git",
"remote",
"add",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L308-L323 |
vcs-python/libvcs | libvcs/git.py | GitRepo.chomp_protocol | def chomp_protocol(url):
"""Return clean VCS url from RFC-style url
:param url: url
:type url: str
:rtype: str
:returns: url as VCS software would accept it
:seealso: #14
"""
if '+' in url:
url = url.split('+', 1)[1]
scheme, netloc, path, query, frag = urlparse.urlsplit(url)
rev = None
if '@' in path:
path, rev = path.rsplit('@', 1)
url = urlparse.urlunsplit((scheme, netloc, path, query, ''))
if url.startswith('ssh://git@github.com/'):
url = url.replace('ssh://', 'git+ssh://')
elif '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
url = url.replace('ssh://', '')
return url | python | def chomp_protocol(url):
"""Return clean VCS url from RFC-style url
:param url: url
:type url: str
:rtype: str
:returns: url as VCS software would accept it
:seealso: #14
"""
if '+' in url:
url = url.split('+', 1)[1]
scheme, netloc, path, query, frag = urlparse.urlsplit(url)
rev = None
if '@' in path:
path, rev = path.rsplit('@', 1)
url = urlparse.urlunsplit((scheme, netloc, path, query, ''))
if url.startswith('ssh://git@github.com/'):
url = url.replace('ssh://', 'git+ssh://')
elif '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
url = url.replace('ssh://', '')
return url | [
"def",
"chomp_protocol",
"(",
"url",
")",
":",
"if",
"'+'",
"in",
"url",
":",
"url",
"=",
"url",
".",
"split",
"(",
"'+'",
",",
"1",
")",
"[",
"1",
"]",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"frag",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"rev",
"=",
"None",
"if",
"'@'",
"in",
"path",
":",
"path",
",",
"rev",
"=",
"path",
".",
"rsplit",
"(",
"'@'",
",",
"1",
")",
"url",
"=",
"urlparse",
".",
"urlunsplit",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"''",
")",
")",
"if",
"url",
".",
"startswith",
"(",
"'ssh://git@github.com/'",
")",
":",
"url",
"=",
"url",
".",
"replace",
"(",
"'ssh://'",
",",
"'git+ssh://'",
")",
"elif",
"'://'",
"not",
"in",
"url",
":",
"assert",
"'file:'",
"not",
"in",
"url",
"url",
"=",
"url",
".",
"replace",
"(",
"'git+'",
",",
"'git+ssh://'",
")",
"url",
"=",
"url",
".",
"replace",
"(",
"'ssh://'",
",",
"''",
")",
"return",
"url"
] | Return clean VCS url from RFC-style url
:param url: url
:type url: str
:rtype: str
:returns: url as VCS software would accept it
:seealso: #14 | [
"Return",
"clean",
"VCS",
"url",
"from",
"RFC",
"-",
"style",
"url"
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L326-L348 |
confirm/ansibleci | ansibleci/logger.py | Logger._log | def _log(self, message, stream, color=None, newline=False):
'''
Logs the message to the sys.stdout or sys.stderr stream.
When color is defined and the TERM environemnt variable contains the
string "color", then the output will be colored.
'''
if color and self.color_term:
colorend = Logger.COLOR_END
else:
color = colorend = ''
stream.write('{color}{message}{colorend}\n'.format(
color=color,
message=message,
colorend=colorend
))
if newline:
sys.stdout.write('\n')
stream.flush() | python | def _log(self, message, stream, color=None, newline=False):
'''
Logs the message to the sys.stdout or sys.stderr stream.
When color is defined and the TERM environemnt variable contains the
string "color", then the output will be colored.
'''
if color and self.color_term:
colorend = Logger.COLOR_END
else:
color = colorend = ''
stream.write('{color}{message}{colorend}\n'.format(
color=color,
message=message,
colorend=colorend
))
if newline:
sys.stdout.write('\n')
stream.flush() | [
"def",
"_log",
"(",
"self",
",",
"message",
",",
"stream",
",",
"color",
"=",
"None",
",",
"newline",
"=",
"False",
")",
":",
"if",
"color",
"and",
"self",
".",
"color_term",
":",
"colorend",
"=",
"Logger",
".",
"COLOR_END",
"else",
":",
"color",
"=",
"colorend",
"=",
"''",
"stream",
".",
"write",
"(",
"'{color}{message}{colorend}\\n'",
".",
"format",
"(",
"color",
"=",
"color",
",",
"message",
"=",
"message",
",",
"colorend",
"=",
"colorend",
")",
")",
"if",
"newline",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"stream",
".",
"flush",
"(",
")"
] | Logs the message to the sys.stdout or sys.stderr stream.
When color is defined and the TERM environemnt variable contains the
string "color", then the output will be colored. | [
"Logs",
"the",
"message",
"to",
"the",
"sys",
".",
"stdout",
"or",
"sys",
".",
"stderr",
"stream",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L43-L65 |
confirm/ansibleci | ansibleci/logger.py | Logger.info | def info(self, message):
'''
Logs an informational message to stdout.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout
) | python | def info(self, message):
'''
Logs an informational message to stdout.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout
) | [
"def",
"info",
"(",
"self",
",",
"message",
")",
":",
"return",
"self",
".",
"_log",
"(",
"message",
"=",
"message",
".",
"upper",
"(",
")",
",",
"stream",
"=",
"sys",
".",
"stdout",
")"
] | Logs an informational message to stdout.
This method should only be used by the Runner. | [
"Logs",
"an",
"informational",
"message",
"to",
"stdout",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L78-L87 |
confirm/ansibleci | ansibleci/logger.py | Logger.passed | def passed(self, message):
'''
Logs as whole test result as PASSED.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout,
color=Logger.COLOR_GREEN_BOLD,
newline=True
) | python | def passed(self, message):
'''
Logs as whole test result as PASSED.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout,
color=Logger.COLOR_GREEN_BOLD,
newline=True
) | [
"def",
"passed",
"(",
"self",
",",
"message",
")",
":",
"return",
"self",
".",
"_log",
"(",
"message",
"=",
"message",
".",
"upper",
"(",
")",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"color",
"=",
"Logger",
".",
"COLOR_GREEN_BOLD",
",",
"newline",
"=",
"True",
")"
] | Logs as whole test result as PASSED.
This method should only be used by the Runner. | [
"Logs",
"as",
"whole",
"test",
"result",
"as",
"PASSED",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L89-L100 |
confirm/ansibleci | ansibleci/logger.py | Logger.failed | def failed(self, message):
'''
Logs as whole test result as FAILED.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stderr,
color=Logger.COLOR_RED_BOLD,
newline=True
) | python | def failed(self, message):
'''
Logs as whole test result as FAILED.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stderr,
color=Logger.COLOR_RED_BOLD,
newline=True
) | [
"def",
"failed",
"(",
"self",
",",
"message",
")",
":",
"return",
"self",
".",
"_log",
"(",
"message",
"=",
"message",
".",
"upper",
"(",
")",
",",
"stream",
"=",
"sys",
".",
"stderr",
",",
"color",
"=",
"Logger",
".",
"COLOR_RED_BOLD",
",",
"newline",
"=",
"True",
")"
] | Logs as whole test result as FAILED.
This method should only be used by the Runner. | [
"Logs",
"as",
"whole",
"test",
"result",
"as",
"FAILED",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L102-L113 |
xapple/plumbing | plumbing/thread.py | non_blocking | def non_blocking(func):
"""Decorator to run a function in a different thread.
It can be used to execute a command in a non-blocking way
like this::
@non_blocking
def add_one(n):
print 'starting'
import time
time.sleep(2)
print 'ending'
return n+1
thread = add_one(5) # Starts the function
result = thread.join() # Waits for it to complete
print result
"""
from functools import wraps
@wraps(func)
def non_blocking_version(*args, **kwargs):
t = ReturnThread(target=func, args=args, kwargs=kwargs)
t.start()
return t
return non_blocking_version | python | def non_blocking(func):
"""Decorator to run a function in a different thread.
It can be used to execute a command in a non-blocking way
like this::
@non_blocking
def add_one(n):
print 'starting'
import time
time.sleep(2)
print 'ending'
return n+1
thread = add_one(5) # Starts the function
result = thread.join() # Waits for it to complete
print result
"""
from functools import wraps
@wraps(func)
def non_blocking_version(*args, **kwargs):
t = ReturnThread(target=func, args=args, kwargs=kwargs)
t.start()
return t
return non_blocking_version | [
"def",
"non_blocking",
"(",
"func",
")",
":",
"from",
"functools",
"import",
"wraps",
"@",
"wraps",
"(",
"func",
")",
"def",
"non_blocking_version",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"ReturnThread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"t",
".",
"start",
"(",
")",
"return",
"t",
"return",
"non_blocking_version"
] | Decorator to run a function in a different thread.
It can be used to execute a command in a non-blocking way
like this::
@non_blocking
def add_one(n):
print 'starting'
import time
time.sleep(2)
print 'ending'
return n+1
thread = add_one(5) # Starts the function
result = thread.join() # Waits for it to complete
print result | [
"Decorator",
"to",
"run",
"a",
"function",
"in",
"a",
"different",
"thread",
".",
"It",
"can",
"be",
"used",
"to",
"execute",
"a",
"command",
"in",
"a",
"non",
"-",
"blocking",
"way",
"like",
"this",
"::"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/thread.py#L32-L55 |
sunlightlabs/django-mediasync | mediasync/backends/__init__.py | BaseClient.media_url | def media_url(self, with_ssl=False):
"""
Used to return a base media URL. Depending on whether we're serving
media remotely or locally, this either hands the decision off to the
backend, or just uses the value in settings.STATIC_URL.
args:
with_ssl: (bool) If True, return an HTTPS url (depending on how
the backend handles it).
"""
if self.serve_remote:
# Hand this off to whichever backend is being used.
url = self.remote_media_url(with_ssl)
else:
# Serving locally, just use the value in settings.py.
url = self.local_media_url
return url.rstrip('/') | python | def media_url(self, with_ssl=False):
"""
Used to return a base media URL. Depending on whether we're serving
media remotely or locally, this either hands the decision off to the
backend, or just uses the value in settings.STATIC_URL.
args:
with_ssl: (bool) If True, return an HTTPS url (depending on how
the backend handles it).
"""
if self.serve_remote:
# Hand this off to whichever backend is being used.
url = self.remote_media_url(with_ssl)
else:
# Serving locally, just use the value in settings.py.
url = self.local_media_url
return url.rstrip('/') | [
"def",
"media_url",
"(",
"self",
",",
"with_ssl",
"=",
"False",
")",
":",
"if",
"self",
".",
"serve_remote",
":",
"# Hand this off to whichever backend is being used.",
"url",
"=",
"self",
".",
"remote_media_url",
"(",
"with_ssl",
")",
"else",
":",
"# Serving locally, just use the value in settings.py.",
"url",
"=",
"self",
".",
"local_media_url",
"return",
"url",
".",
"rstrip",
"(",
"'/'",
")"
] | Used to return a base media URL. Depending on whether we're serving
media remotely or locally, this either hands the decision off to the
backend, or just uses the value in settings.STATIC_URL.
args:
with_ssl: (bool) If True, return an HTTPS url (depending on how
the backend handles it). | [
"Used",
"to",
"return",
"a",
"base",
"media",
"URL",
".",
"Depending",
"on",
"whether",
"we",
"re",
"serving",
"media",
"remotely",
"or",
"locally",
"this",
"either",
"hands",
"the",
"decision",
"off",
"to",
"the",
"backend",
"or",
"just",
"uses",
"the",
"value",
"in",
"settings",
".",
"STATIC_URL",
".",
"args",
":",
"with_ssl",
":",
"(",
"bool",
")",
"If",
"True",
"return",
"an",
"HTTPS",
"url",
"(",
"depending",
"on",
"how",
"the",
"backend",
"handles",
"it",
")",
"."
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/backends/__init__.py#L69-L85 |
xapple/plumbing | plumbing/runner.py | Runner.logs | def logs(self):
"""Find the log directory and return all the logs sorted."""
if not self.parent.loaded: self.parent.load()
logs = self.parent.p.logs_dir.flat_directories
logs.sort(key=lambda x: x.mod_time)
return logs | python | def logs(self):
"""Find the log directory and return all the logs sorted."""
if not self.parent.loaded: self.parent.load()
logs = self.parent.p.logs_dir.flat_directories
logs.sort(key=lambda x: x.mod_time)
return logs | [
"def",
"logs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
".",
"loaded",
":",
"self",
".",
"parent",
".",
"load",
"(",
")",
"logs",
"=",
"self",
".",
"parent",
".",
"p",
".",
"logs_dir",
".",
"flat_directories",
"logs",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"mod_time",
")",
"return",
"logs"
] | Find the log directory and return all the logs sorted. | [
"Find",
"the",
"log",
"directory",
"and",
"return",
"all",
"the",
"logs",
"sorted",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L108-L113 |
xapple/plumbing | plumbing/runner.py | Runner.run_locally | def run_locally(self, steps=None, **kwargs):
"""A convenience method to run the same result as a SLURM job
but locally in a non-blocking way."""
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
modules = self.modules,
**kwargs)
self.slurm_job.run_locally() | python | def run_locally(self, steps=None, **kwargs):
"""A convenience method to run the same result as a SLURM job
but locally in a non-blocking way."""
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
modules = self.modules,
**kwargs)
self.slurm_job.run_locally() | [
"def",
"run_locally",
"(",
"self",
",",
"steps",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"slurm_job",
"=",
"LoggedJobSLURM",
"(",
"self",
".",
"command",
"(",
"steps",
")",
",",
"base_dir",
"=",
"self",
".",
"parent",
".",
"p",
".",
"logs_dir",
",",
"modules",
"=",
"self",
".",
"modules",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"slurm_job",
".",
"run_locally",
"(",
")"
] | A convenience method to run the same result as a SLURM job
but locally in a non-blocking way. | [
"A",
"convenience",
"method",
"to",
"run",
"the",
"same",
"result",
"as",
"a",
"SLURM",
"job",
"but",
"locally",
"in",
"a",
"non",
"-",
"blocking",
"way",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L121-L128 |
xapple/plumbing | plumbing/runner.py | Runner.run_slurm | def run_slurm(self, steps=None, **kwargs):
"""Run the steps via the SLURM queue."""
# Optional extra SLURM parameters #
params = self.extra_slurm_params
params.update(kwargs)
# Mandatory extra SLURM parameters #
if 'time' not in params: params['time'] = self.default_time
if 'job_name' not in params: params['job_name'] = self.job_name
if 'email' not in params: params['email'] = None
if 'dependency' not in params: params['dependency'] = 'singleton'
# Send it #
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
modules = self.modules,
**params)
# Return the Job ID #
return self.slurm_job.run() | python | def run_slurm(self, steps=None, **kwargs):
"""Run the steps via the SLURM queue."""
# Optional extra SLURM parameters #
params = self.extra_slurm_params
params.update(kwargs)
# Mandatory extra SLURM parameters #
if 'time' not in params: params['time'] = self.default_time
if 'job_name' not in params: params['job_name'] = self.job_name
if 'email' not in params: params['email'] = None
if 'dependency' not in params: params['dependency'] = 'singleton'
# Send it #
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
modules = self.modules,
**params)
# Return the Job ID #
return self.slurm_job.run() | [
"def",
"run_slurm",
"(",
"self",
",",
"steps",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Optional extra SLURM parameters #",
"params",
"=",
"self",
".",
"extra_slurm_params",
"params",
".",
"update",
"(",
"kwargs",
")",
"# Mandatory extra SLURM parameters #",
"if",
"'time'",
"not",
"in",
"params",
":",
"params",
"[",
"'time'",
"]",
"=",
"self",
".",
"default_time",
"if",
"'job_name'",
"not",
"in",
"params",
":",
"params",
"[",
"'job_name'",
"]",
"=",
"self",
".",
"job_name",
"if",
"'email'",
"not",
"in",
"params",
":",
"params",
"[",
"'email'",
"]",
"=",
"None",
"if",
"'dependency'",
"not",
"in",
"params",
":",
"params",
"[",
"'dependency'",
"]",
"=",
"'singleton'",
"# Send it #",
"self",
".",
"slurm_job",
"=",
"LoggedJobSLURM",
"(",
"self",
".",
"command",
"(",
"steps",
")",
",",
"base_dir",
"=",
"self",
".",
"parent",
".",
"p",
".",
"logs_dir",
",",
"modules",
"=",
"self",
".",
"modules",
",",
"*",
"*",
"params",
")",
"# Return the Job ID #",
"return",
"self",
".",
"slurm_job",
".",
"run",
"(",
")"
] | Run the steps via the SLURM queue. | [
"Run",
"the",
"steps",
"via",
"the",
"SLURM",
"queue",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L131-L147 |
matllubos/django-is-core | is_core/forms/generic.py | smart_generic_inlineformset_factory | def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet,
ct_field='content_type', fk_field='object_id', fields=None, exclude=None,
extra=3, can_order=False, can_delete=True, min_num=None, max_num=None,
formfield_callback=None, widgets=None, validate_min=False, validate_max=False,
localized_fields=None, labels=None, help_texts=None, error_messages=None,
formreadonlyfield_callback=None, readonly_fields=None, for_concrete_model=True,
readonly=False):
"""
Returns a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``fk_field`` if they are different from
the defaults ``content_type`` and ``object_id`` respectively.
"""
opts = model._meta
# if there is no field called `ct_field` let the exception propagate
ct_field = opts.get_field(ct_field)
if not isinstance(ct_field, models.ForeignKey) or ct_field.related_model != ContentType:
raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
fk_field = opts.get_field(fk_field) # let the exception propagate
if exclude is not None:
exclude = list(exclude)
exclude.extend([ct_field.name, fk_field.name])
else:
exclude = [ct_field.name, fk_field.name]
kwargs = {
'form': form,
'formfield_callback': formfield_callback,
'formset': formset,
'extra': extra,
'can_delete': can_delete,
'can_order': can_order,
'fields': fields,
'exclude': exclude,
'max_num': max_num,
'min_num': min_num,
'widgets': widgets,
'validate_min': validate_min,
'validate_max': validate_max,
'localized_fields': localized_fields,
'formreadonlyfield_callback': formreadonlyfield_callback,
'readonly_fields': readonly_fields,
'readonly': readonly,
'labels': labels,
'help_texts': help_texts,
'error_messages': error_messages,
}
FormSet = smartmodelformset_factory(model, request, **kwargs)
FormSet.ct_field = ct_field
FormSet.ct_fk_field = fk_field
FormSet.for_concrete_model = for_concrete_model
return FormSet | python | def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet,
ct_field='content_type', fk_field='object_id', fields=None, exclude=None,
extra=3, can_order=False, can_delete=True, min_num=None, max_num=None,
formfield_callback=None, widgets=None, validate_min=False, validate_max=False,
localized_fields=None, labels=None, help_texts=None, error_messages=None,
formreadonlyfield_callback=None, readonly_fields=None, for_concrete_model=True,
readonly=False):
"""
Returns a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``fk_field`` if they are different from
the defaults ``content_type`` and ``object_id`` respectively.
"""
opts = model._meta
# if there is no field called `ct_field` let the exception propagate
ct_field = opts.get_field(ct_field)
if not isinstance(ct_field, models.ForeignKey) or ct_field.related_model != ContentType:
raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
fk_field = opts.get_field(fk_field) # let the exception propagate
if exclude is not None:
exclude = list(exclude)
exclude.extend([ct_field.name, fk_field.name])
else:
exclude = [ct_field.name, fk_field.name]
kwargs = {
'form': form,
'formfield_callback': formfield_callback,
'formset': formset,
'extra': extra,
'can_delete': can_delete,
'can_order': can_order,
'fields': fields,
'exclude': exclude,
'max_num': max_num,
'min_num': min_num,
'widgets': widgets,
'validate_min': validate_min,
'validate_max': validate_max,
'localized_fields': localized_fields,
'formreadonlyfield_callback': formreadonlyfield_callback,
'readonly_fields': readonly_fields,
'readonly': readonly,
'labels': labels,
'help_texts': help_texts,
'error_messages': error_messages,
}
FormSet = smartmodelformset_factory(model, request, **kwargs)
FormSet.ct_field = ct_field
FormSet.ct_fk_field = fk_field
FormSet.for_concrete_model = for_concrete_model
return FormSet | [
"def",
"smart_generic_inlineformset_factory",
"(",
"model",
",",
"request",
",",
"form",
"=",
"ModelForm",
",",
"formset",
"=",
"BaseGenericInlineFormSet",
",",
"ct_field",
"=",
"'content_type'",
",",
"fk_field",
"=",
"'object_id'",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"extra",
"=",
"3",
",",
"can_order",
"=",
"False",
",",
"can_delete",
"=",
"True",
",",
"min_num",
"=",
"None",
",",
"max_num",
"=",
"None",
",",
"formfield_callback",
"=",
"None",
",",
"widgets",
"=",
"None",
",",
"validate_min",
"=",
"False",
",",
"validate_max",
"=",
"False",
",",
"localized_fields",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"help_texts",
"=",
"None",
",",
"error_messages",
"=",
"None",
",",
"formreadonlyfield_callback",
"=",
"None",
",",
"readonly_fields",
"=",
"None",
",",
"for_concrete_model",
"=",
"True",
",",
"readonly",
"=",
"False",
")",
":",
"opts",
"=",
"model",
".",
"_meta",
"# if there is no field called `ct_field` let the exception propagate",
"ct_field",
"=",
"opts",
".",
"get_field",
"(",
"ct_field",
")",
"if",
"not",
"isinstance",
"(",
"ct_field",
",",
"models",
".",
"ForeignKey",
")",
"or",
"ct_field",
".",
"related_model",
"!=",
"ContentType",
":",
"raise",
"Exception",
"(",
"\"fk_name '%s' is not a ForeignKey to ContentType\"",
"%",
"ct_field",
")",
"fk_field",
"=",
"opts",
".",
"get_field",
"(",
"fk_field",
")",
"# let the exception propagate",
"if",
"exclude",
"is",
"not",
"None",
":",
"exclude",
"=",
"list",
"(",
"exclude",
")",
"exclude",
".",
"extend",
"(",
"[",
"ct_field",
".",
"name",
",",
"fk_field",
".",
"name",
"]",
")",
"else",
":",
"exclude",
"=",
"[",
"ct_field",
".",
"name",
",",
"fk_field",
".",
"name",
"]",
"kwargs",
"=",
"{",
"'form'",
":",
"form",
",",
"'formfield_callback'",
":",
"formfield_callback",
",",
"'formset'",
":",
"formset",
",",
"'extra'",
":",
"extra",
",",
"'can_delete'",
":",
"can_delete",
",",
"'can_order'",
":",
"can_order",
",",
"'fields'",
":",
"fields",
",",
"'exclude'",
":",
"exclude",
",",
"'max_num'",
":",
"max_num",
",",
"'min_num'",
":",
"min_num",
",",
"'widgets'",
":",
"widgets",
",",
"'validate_min'",
":",
"validate_min",
",",
"'validate_max'",
":",
"validate_max",
",",
"'localized_fields'",
":",
"localized_fields",
",",
"'formreadonlyfield_callback'",
":",
"formreadonlyfield_callback",
",",
"'readonly_fields'",
":",
"readonly_fields",
",",
"'readonly'",
":",
"readonly",
",",
"'labels'",
":",
"labels",
",",
"'help_texts'",
":",
"help_texts",
",",
"'error_messages'",
":",
"error_messages",
",",
"}",
"FormSet",
"=",
"smartmodelformset_factory",
"(",
"model",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
"FormSet",
".",
"ct_field",
"=",
"ct_field",
"FormSet",
".",
"ct_fk_field",
"=",
"fk_field",
"FormSet",
".",
"for_concrete_model",
"=",
"for_concrete_model",
"return",
"FormSet"
] | Returns a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``fk_field`` if they are different from
the defaults ``content_type`` and ``object_id`` respectively. | [
"Returns",
"a",
"GenericInlineFormSet",
"for",
"the",
"given",
"kwargs",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/generic.py#L14-L66 |
xapple/plumbing | plumbing/ec2.py | InstanceEC2.rename | def rename(self, name):
"""Set the name of the machine."""
self.ec2.create_tags(Resources = [self.instance_id],
Tags = [{'Key': 'Name',
'Value': name}])
self.refresh_info() | python | def rename(self, name):
"""Set the name of the machine."""
self.ec2.create_tags(Resources = [self.instance_id],
Tags = [{'Key': 'Name',
'Value': name}])
self.refresh_info() | [
"def",
"rename",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"ec2",
".",
"create_tags",
"(",
"Resources",
"=",
"[",
"self",
".",
"instance_id",
"]",
",",
"Tags",
"=",
"[",
"{",
"'Key'",
":",
"'Name'",
",",
"'Value'",
":",
"name",
"}",
"]",
")",
"self",
".",
"refresh_info",
"(",
")"
] | Set the name of the machine. | [
"Set",
"the",
"name",
"of",
"the",
"machine",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/ec2.py#L70-L75 |
xapple/plumbing | plumbing/ec2.py | InstanceEC2.update_ssh_config | def update_ssh_config(self, path="~/.ssh/config"):
"""Put the DNS into the ssh config file."""
# Read the config file #
import sshconf
config = sshconf.read_ssh_config(os.path.expanduser(path))
# In case it doesn't exist #
if not config.host(self.instance_name): config.add(self.instance_name)
# Add the new DNS #
config.set(self.instance_name, Hostname=self.dns)
# Write result #
config.write(os.path.expanduser(path)) | python | def update_ssh_config(self, path="~/.ssh/config"):
"""Put the DNS into the ssh config file."""
# Read the config file #
import sshconf
config = sshconf.read_ssh_config(os.path.expanduser(path))
# In case it doesn't exist #
if not config.host(self.instance_name): config.add(self.instance_name)
# Add the new DNS #
config.set(self.instance_name, Hostname=self.dns)
# Write result #
config.write(os.path.expanduser(path)) | [
"def",
"update_ssh_config",
"(",
"self",
",",
"path",
"=",
"\"~/.ssh/config\"",
")",
":",
"# Read the config file #",
"import",
"sshconf",
"config",
"=",
"sshconf",
".",
"read_ssh_config",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
")",
"# In case it doesn't exist #",
"if",
"not",
"config",
".",
"host",
"(",
"self",
".",
"instance_name",
")",
":",
"config",
".",
"add",
"(",
"self",
".",
"instance_name",
")",
"# Add the new DNS #",
"config",
".",
"set",
"(",
"self",
".",
"instance_name",
",",
"Hostname",
"=",
"self",
".",
"dns",
")",
"# Write result #",
"config",
".",
"write",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
")"
] | Put the DNS into the ssh config file. | [
"Put",
"the",
"DNS",
"into",
"the",
"ssh",
"config",
"file",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/ec2.py#L77-L87 |
matllubos/django-is-core | is_core/filters/default_filters.py | RelatedUIFilter._update_widget_choices | def _update_widget_choices(self, widget):
"""
Updates widget choices with special choice iterator that removes blank values and adds none value to clear
filter data.
:param widget: widget with choices
:return: updated widget with filter choices
"""
widget.choices = FilterChoiceIterator(widget.choices, self.field)
return widget | python | def _update_widget_choices(self, widget):
"""
Updates widget choices with special choice iterator that removes blank values and adds none value to clear
filter data.
:param widget: widget with choices
:return: updated widget with filter choices
"""
widget.choices = FilterChoiceIterator(widget.choices, self.field)
return widget | [
"def",
"_update_widget_choices",
"(",
"self",
",",
"widget",
")",
":",
"widget",
".",
"choices",
"=",
"FilterChoiceIterator",
"(",
"widget",
".",
"choices",
",",
"self",
".",
"field",
")",
"return",
"widget"
] | Updates widget choices with special choice iterator that removes blank values and adds none value to clear
filter data.
:param widget: widget with choices
:return: updated widget with filter choices | [
"Updates",
"widget",
"choices",
"with",
"special",
"choice",
"iterator",
"that",
"removes",
"blank",
"values",
"and",
"adds",
"none",
"value",
"to",
"clear",
"filter",
"data",
".",
":",
"param",
"widget",
":",
"widget",
"with",
"choices",
":",
"return",
":",
"updated",
"widget",
"with",
"filter",
"choices"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/default_filters.py#L33-L42 |
matllubos/django-is-core | is_core/filters/default_filters.py | UIForeignKeyFilter.get_widget | def get_widget(self, request):
"""
Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for
filtering.
"""
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget) | python | def get_widget(self, request):
"""
Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for
filtering.
"""
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget) | [
"def",
"get_widget",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"_update_widget_choices",
"(",
"self",
".",
"field",
".",
"formfield",
"(",
"widget",
"=",
"RestrictedSelectWidget",
")",
".",
"widget",
")"
] | Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for
filtering. | [
"Field",
"widget",
"is",
"replaced",
"with",
"RestrictedSelectWidget",
"because",
"we",
"not",
"want",
"to",
"use",
"modified",
"widgets",
"for",
"filtering",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/default_filters.py#L56-L61 |
matllubos/django-is-core | is_core/filters/default_filters.py | UIForeignObjectRelFilter.get_widget | def get_widget(self, request):
"""
Table view is not able to get form field from reverse relation.
Therefore this widget returns similar form field as direct relation (ModelChoiceField).
Because there is used "RestrictedSelectWidget" it is returned textarea or selectox with choices according to
count objects in the queryset.
"""
return self._update_widget_choices(
forms.ModelChoiceField(
widget=RestrictedSelectWidget, queryset=self.field.related_model._default_manager.all()
).widget
) | python | def get_widget(self, request):
"""
Table view is not able to get form field from reverse relation.
Therefore this widget returns similar form field as direct relation (ModelChoiceField).
Because there is used "RestrictedSelectWidget" it is returned textarea or selectox with choices according to
count objects in the queryset.
"""
return self._update_widget_choices(
forms.ModelChoiceField(
widget=RestrictedSelectWidget, queryset=self.field.related_model._default_manager.all()
).widget
) | [
"def",
"get_widget",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"_update_widget_choices",
"(",
"forms",
".",
"ModelChoiceField",
"(",
"widget",
"=",
"RestrictedSelectWidget",
",",
"queryset",
"=",
"self",
".",
"field",
".",
"related_model",
".",
"_default_manager",
".",
"all",
"(",
")",
")",
".",
"widget",
")"
] | Table view is not able to get form field from reverse relation.
Therefore this widget returns similar form field as direct relation (ModelChoiceField).
Because there is used "RestrictedSelectWidget" it is returned textarea or selectox with choices according to
count objects in the queryset. | [
"Table",
"view",
"is",
"not",
"able",
"to",
"get",
"form",
"field",
"from",
"reverse",
"relation",
".",
"Therefore",
"this",
"widget",
"returns",
"similar",
"form",
"field",
"as",
"direct",
"relation",
"(",
"ModelChoiceField",
")",
".",
"Because",
"there",
"is",
"used",
"RestrictedSelectWidget",
"it",
"is",
"returned",
"textarea",
"or",
"selectox",
"with",
"choices",
"according",
"to",
"count",
"objects",
"in",
"the",
"queryset",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/default_filters.py#L76-L87 |
softwarefactory-project/distroinfo | distroinfo/query.py | strip_project_url | def strip_project_url(url):
"""strip proto:// | openstack/ prefixes and .git | -distgit suffixes"""
m = re.match(r'(?:[^:]+://)?(.*)', url)
if m:
url = m.group(1)
if url.endswith('.git'):
url, _, _ = url.rpartition('.')
if url.endswith('-distgit'):
url, _, _ = url.rpartition('-')
if url.startswith('openstack/'):
# openstack is always special :-p
_, _, url = url.partition('/')
return url | python | def strip_project_url(url):
"""strip proto:// | openstack/ prefixes and .git | -distgit suffixes"""
m = re.match(r'(?:[^:]+://)?(.*)', url)
if m:
url = m.group(1)
if url.endswith('.git'):
url, _, _ = url.rpartition('.')
if url.endswith('-distgit'):
url, _, _ = url.rpartition('-')
if url.startswith('openstack/'):
# openstack is always special :-p
_, _, url = url.partition('/')
return url | [
"def",
"strip_project_url",
"(",
"url",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'(?:[^:]+://)?(.*)'",
",",
"url",
")",
"if",
"m",
":",
"url",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"url",
".",
"endswith",
"(",
"'.git'",
")",
":",
"url",
",",
"_",
",",
"_",
"=",
"url",
".",
"rpartition",
"(",
"'.'",
")",
"if",
"url",
".",
"endswith",
"(",
"'-distgit'",
")",
":",
"url",
",",
"_",
",",
"_",
"=",
"url",
".",
"rpartition",
"(",
"'-'",
")",
"if",
"url",
".",
"startswith",
"(",
"'openstack/'",
")",
":",
"# openstack is always special :-p",
"_",
",",
"_",
",",
"url",
"=",
"url",
".",
"partition",
"(",
"'/'",
")",
"return",
"url"
] | strip proto:// | openstack/ prefixes and .git | -distgit suffixes | [
"strip",
"proto",
":",
"//",
"|",
"openstack",
"/",
"prefixes",
"and",
".",
"git",
"|",
"-",
"distgit",
"suffixes"
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/query.py#L138-L150 |
vcs-python/libvcs | libvcs/svn.py | get_rev_options | def get_rev_options(url, rev):
"""Return revision options.
from pip pip.vcs.subversion.
"""
if rev:
rev_options = ['-r', rev]
else:
rev_options = []
r = urlparse.urlsplit(url)
if hasattr(r, 'username'):
# >= Python-2.5
username, password = r.username, r.password
else:
netloc = r[1]
if '@' in netloc:
auth = netloc.split('@')[0]
if ':' in auth:
username, password = auth.split(':', 1)
else:
username, password = auth, None
else:
username, password = None, None
if username:
rev_options += ['--username', username]
if password:
rev_options += ['--password', password]
return rev_options | python | def get_rev_options(url, rev):
"""Return revision options.
from pip pip.vcs.subversion.
"""
if rev:
rev_options = ['-r', rev]
else:
rev_options = []
r = urlparse.urlsplit(url)
if hasattr(r, 'username'):
# >= Python-2.5
username, password = r.username, r.password
else:
netloc = r[1]
if '@' in netloc:
auth = netloc.split('@')[0]
if ':' in auth:
username, password = auth.split(':', 1)
else:
username, password = auth, None
else:
username, password = None, None
if username:
rev_options += ['--username', username]
if password:
rev_options += ['--password', password]
return rev_options | [
"def",
"get_rev_options",
"(",
"url",
",",
"rev",
")",
":",
"if",
"rev",
":",
"rev_options",
"=",
"[",
"'-r'",
",",
"rev",
"]",
"else",
":",
"rev_options",
"=",
"[",
"]",
"r",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"if",
"hasattr",
"(",
"r",
",",
"'username'",
")",
":",
"# >= Python-2.5",
"username",
",",
"password",
"=",
"r",
".",
"username",
",",
"r",
".",
"password",
"else",
":",
"netloc",
"=",
"r",
"[",
"1",
"]",
"if",
"'@'",
"in",
"netloc",
":",
"auth",
"=",
"netloc",
".",
"split",
"(",
"'@'",
")",
"[",
"0",
"]",
"if",
"':'",
"in",
"auth",
":",
"username",
",",
"password",
"=",
"auth",
".",
"split",
"(",
"':'",
",",
"1",
")",
"else",
":",
"username",
",",
"password",
"=",
"auth",
",",
"None",
"else",
":",
"username",
",",
"password",
"=",
"None",
",",
"None",
"if",
"username",
":",
"rev_options",
"+=",
"[",
"'--username'",
",",
"username",
"]",
"if",
"password",
":",
"rev_options",
"+=",
"[",
"'--password'",
",",
"password",
"]",
"return",
"rev_options"
] | Return revision options.
from pip pip.vcs.subversion. | [
"Return",
"revision",
"options",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/svn.py#L146-L176 |
vcs-python/libvcs | libvcs/svn.py | SubversionRepo.get_revision_file | def get_revision_file(self, location):
"""Return revision for a file."""
current_rev = self.run(['info', location])
_INI_RE = re.compile(r"^([^:]+):\s+(\S.*)$", re.M)
info_list = _INI_RE.findall(current_rev)
return int(dict(info_list)['Revision']) | python | def get_revision_file(self, location):
"""Return revision for a file."""
current_rev = self.run(['info', location])
_INI_RE = re.compile(r"^([^:]+):\s+(\S.*)$", re.M)
info_list = _INI_RE.findall(current_rev)
return int(dict(info_list)['Revision']) | [
"def",
"get_revision_file",
"(",
"self",
",",
"location",
")",
":",
"current_rev",
"=",
"self",
".",
"run",
"(",
"[",
"'info'",
",",
"location",
"]",
")",
"_INI_RE",
"=",
"re",
".",
"compile",
"(",
"r\"^([^:]+):\\s+(\\S.*)$\"",
",",
"re",
".",
"M",
")",
"info_list",
"=",
"_INI_RE",
".",
"findall",
"(",
"current_rev",
")",
"return",
"int",
"(",
"dict",
"(",
"info_list",
")",
"[",
"'Revision'",
"]",
")"
] | Return revision for a file. | [
"Return",
"revision",
"for",
"a",
"file",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/svn.py#L77-L85 |
The-Politico/django-slackchat-serializer | slackchat/serializers/channel.py | ChannelSerializer.get_publish_path | def get_publish_path(self, obj):
"""
publish_path joins the publish_paths for the chat type and the channel.
"""
return os.path.join(
obj.chat_type.publish_path, obj.publish_path.lstrip("/")
) | python | def get_publish_path(self, obj):
"""
publish_path joins the publish_paths for the chat type and the channel.
"""
return os.path.join(
obj.chat_type.publish_path, obj.publish_path.lstrip("/")
) | [
"def",
"get_publish_path",
"(",
"self",
",",
"obj",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"obj",
".",
"chat_type",
".",
"publish_path",
",",
"obj",
".",
"publish_path",
".",
"lstrip",
"(",
"\"/\"",
")",
")"
] | publish_path joins the publish_paths for the chat type and the channel. | [
"publish_path",
"joins",
"the",
"publish_paths",
"for",
"the",
"chat",
"type",
"and",
"the",
"channel",
"."
] | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/serializers/channel.py#L37-L43 |
intelligenia/modeltranslation | modeltranslation/models.py | trans_attr | def trans_attr(attr, lang):
"""
Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>.
For example: name_es (name attribute in Spanish)
@param attr Attribute whose name will form the name translated attribute.
@param lang ISO Language code that will be the suffix of the translated attribute.
@return: string with the name of the translated attribute.
"""
lang = lang.replace("-","_").lower()
return "{0}_{1}".format(attr,lang) | python | def trans_attr(attr, lang):
"""
Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>.
For example: name_es (name attribute in Spanish)
@param attr Attribute whose name will form the name translated attribute.
@param lang ISO Language code that will be the suffix of the translated attribute.
@return: string with the name of the translated attribute.
"""
lang = lang.replace("-","_").lower()
return "{0}_{1}".format(attr,lang) | [
"def",
"trans_attr",
"(",
"attr",
",",
"lang",
")",
":",
"lang",
"=",
"lang",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
".",
"lower",
"(",
")",
"return",
"\"{0}_{1}\"",
".",
"format",
"(",
"attr",
",",
"lang",
")"
] | Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>.
For example: name_es (name attribute in Spanish)
@param attr Attribute whose name will form the name translated attribute.
@param lang ISO Language code that will be the suffix of the translated attribute.
@return: string with the name of the translated attribute. | [
"Returns",
"the",
"name",
"of",
"the",
"translated",
"attribute",
"of",
"the",
"object",
"<attribute",
">",
"_<lang_iso_code",
">",
".",
"For",
"example",
":",
"name_es",
"(",
"name",
"attribute",
"in",
"Spanish",
")"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L50-L59 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation._init_module_cache | def _init_module_cache():
"""
Module caching, it helps with not having to import again and again same modules.
@return: boolean, True if module caching has been done, False if module caching was already done.
"""
# While there are not loaded modules, load these ones
if len(FieldTranslation._modules) < len(FieldTranslation._model_module_paths):
for module_path in FieldTranslation._model_module_paths:
FieldTranslation._modules[module_path] = importlib.import_module(module_path)
return True
return False | python | def _init_module_cache():
"""
Module caching, it helps with not having to import again and again same modules.
@return: boolean, True if module caching has been done, False if module caching was already done.
"""
# While there are not loaded modules, load these ones
if len(FieldTranslation._modules) < len(FieldTranslation._model_module_paths):
for module_path in FieldTranslation._model_module_paths:
FieldTranslation._modules[module_path] = importlib.import_module(module_path)
return True
return False | [
"def",
"_init_module_cache",
"(",
")",
":",
"# While there are not loaded modules, load these ones",
"if",
"len",
"(",
"FieldTranslation",
".",
"_modules",
")",
"<",
"len",
"(",
"FieldTranslation",
".",
"_model_module_paths",
")",
":",
"for",
"module_path",
"in",
"FieldTranslation",
".",
"_model_module_paths",
":",
"FieldTranslation",
".",
"_modules",
"[",
"module_path",
"]",
"=",
"importlib",
".",
"import_module",
"(",
"module_path",
")",
"return",
"True",
"return",
"False"
] | Module caching, it helps with not having to import again and again same modules.
@return: boolean, True if module caching has been done, False if module caching was already done. | [
"Module",
"caching",
"it",
"helps",
"with",
"not",
"having",
"to",
"import",
"again",
"and",
"again",
"same",
"modules",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L155-L166 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation._load_source_model | def _load_source_model(self):
"""
Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting
orphan translations (translations without a parent object associated).
"""
# If source_model exists, return it
if hasattr(self, "source_model"):
return self.source_model
# Getting the source model
module = self.get_python_module()
# Test if module has inside the model we are looking for
if hasattr(module, self.model):
# Setting of source model
self.source_model = getattr(module, self.model)
# Setting of verbose name and its plural for later use
self.source_model.meta__verbose_name = self.source_model._meta.verbose_name
self.source_model.meta__verbose_name_plural = self.source_model._meta.verbose_name_plural
return self.source_model
raise ValueError(u"Model {0} does not exist in module".format(self.model, self.module)) | python | def _load_source_model(self):
"""
Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting
orphan translations (translations without a parent object associated).
"""
# If source_model exists, return it
if hasattr(self, "source_model"):
return self.source_model
# Getting the source model
module = self.get_python_module()
# Test if module has inside the model we are looking for
if hasattr(module, self.model):
# Setting of source model
self.source_model = getattr(module, self.model)
# Setting of verbose name and its plural for later use
self.source_model.meta__verbose_name = self.source_model._meta.verbose_name
self.source_model.meta__verbose_name_plural = self.source_model._meta.verbose_name_plural
return self.source_model
raise ValueError(u"Model {0} does not exist in module".format(self.model, self.module)) | [
"def",
"_load_source_model",
"(",
"self",
")",
":",
"# If source_model exists, return it",
"if",
"hasattr",
"(",
"self",
",",
"\"source_model\"",
")",
":",
"return",
"self",
".",
"source_model",
"# Getting the source model",
"module",
"=",
"self",
".",
"get_python_module",
"(",
")",
"# Test if module has inside the model we are looking for",
"if",
"hasattr",
"(",
"module",
",",
"self",
".",
"model",
")",
":",
"# Setting of source model",
"self",
".",
"source_model",
"=",
"getattr",
"(",
"module",
",",
"self",
".",
"model",
")",
"# Setting of verbose name and its plural for later use",
"self",
".",
"source_model",
".",
"meta__verbose_name",
"=",
"self",
".",
"source_model",
".",
"_meta",
".",
"verbose_name",
"self",
".",
"source_model",
".",
"meta__verbose_name_plural",
"=",
"self",
".",
"source_model",
".",
"_meta",
".",
"verbose_name_plural",
"return",
"self",
".",
"source_model",
"raise",
"ValueError",
"(",
"u\"Model {0} does not exist in module\"",
".",
"format",
"(",
"self",
".",
"model",
",",
"self",
".",
"module",
")",
")"
] | Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting
orphan translations (translations without a parent object associated). | [
"Loads",
"and",
"gets",
"the",
"source",
"model",
"of",
"the",
"FieldTranslation",
"as",
"a",
"dynamic",
"attribute",
".",
"It",
"is",
"used",
"only",
"when",
"deleting",
"orphan",
"translations",
"(",
"translations",
"without",
"a",
"parent",
"object",
"associated",
")",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L179-L201 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation._load_source_object | def _load_source_object(self):
"""
Loads related object in a dynamic attribute and returns it.
"""
if hasattr(self, "source_obj"):
self.source_text = getattr(self.source_obj, self.field)
return self.source_obj
self._load_source_model()
self.source_obj = self.source_model.objects.get(id=self.object_id)
return self.source_obj | python | def _load_source_object(self):
"""
Loads related object in a dynamic attribute and returns it.
"""
if hasattr(self, "source_obj"):
self.source_text = getattr(self.source_obj, self.field)
return self.source_obj
self._load_source_model()
self.source_obj = self.source_model.objects.get(id=self.object_id)
return self.source_obj | [
"def",
"_load_source_object",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"source_obj\"",
")",
":",
"self",
".",
"source_text",
"=",
"getattr",
"(",
"self",
".",
"source_obj",
",",
"self",
".",
"field",
")",
"return",
"self",
".",
"source_obj",
"self",
".",
"_load_source_model",
"(",
")",
"self",
".",
"source_obj",
"=",
"self",
".",
"source_model",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"self",
".",
"object_id",
")",
"return",
"self",
".",
"source_obj"
] | Loads related object in a dynamic attribute and returns it. | [
"Loads",
"related",
"object",
"in",
"a",
"dynamic",
"attribute",
"and",
"returns",
"it",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L206-L216 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation.delete_orphan_translations | def delete_orphan_translations(condition=None):
"""
Delete orphan translations.
This method needs refactoring to be improve its performance.
"""
if condition is None:
condition = {}
# TODO: optimize using one SQL sentence
translations = FieldTranslation.objects.all()
for translation in translations:
translation._load_source_model()
condition["id"] = translation.object_id
if not translation.source_model.objects.filter(**condition).exists():
translation.delete() | python | def delete_orphan_translations(condition=None):
"""
Delete orphan translations.
This method needs refactoring to be improve its performance.
"""
if condition is None:
condition = {}
# TODO: optimize using one SQL sentence
translations = FieldTranslation.objects.all()
for translation in translations:
translation._load_source_model()
condition["id"] = translation.object_id
if not translation.source_model.objects.filter(**condition).exists():
translation.delete() | [
"def",
"delete_orphan_translations",
"(",
"condition",
"=",
"None",
")",
":",
"if",
"condition",
"is",
"None",
":",
"condition",
"=",
"{",
"}",
"# TODO: optimize using one SQL sentence",
"translations",
"=",
"FieldTranslation",
".",
"objects",
".",
"all",
"(",
")",
"for",
"translation",
"in",
"translations",
":",
"translation",
".",
"_load_source_model",
"(",
")",
"condition",
"[",
"\"id\"",
"]",
"=",
"translation",
".",
"object_id",
"if",
"not",
"translation",
".",
"source_model",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"condition",
")",
".",
"exists",
"(",
")",
":",
"translation",
".",
"delete",
"(",
")"
] | Delete orphan translations.
This method needs refactoring to be improve its performance. | [
"Delete",
"orphan",
"translations",
".",
"This",
"method",
"needs",
"refactoring",
"to",
"be",
"improve",
"its",
"performance",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L222-L235 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation.update_translations | def update_translations(condition=None):
"""
Updates FieldTranslations table
"""
if condition is None:
condition = {}
# Number of updated translations
num_translations = 0
# Module caching
FieldTranslation._init_module_cache()
# Current languages dict
LANGUAGES = dict(lang for lang in MODELTRANSLATION_LANG_CHOICES)
if settings.LANGUAGE_CODE in LANGUAGES:
del LANGUAGES[settings.LANGUAGE_CODE]
# For each module, we are going to update the translations
for key in FieldTranslation._modules.keys():
module = FieldTranslation._modules[key]
# Class of the module
clsmembers = inspect.getmembers(sys.modules[key], inspect.isclass)
for cls in clsmembers:
cls = cls[1]
# If the model has in Meta "translatable_fields", we insert this fields
if hasattr(cls,"_meta") and not cls._meta.abstract and hasattr(cls._meta,"translatable_fields") and len(cls._meta.translatable_fields)>0:
objects = cls.objects.filter(**condition)
# For each object, language and field are updated
for obj in objects:
for lang in LANGUAGES.keys():
for field in cls._meta.translatable_fields:
if FieldTranslation.update(obj=obj, field=field, lang=lang, context=""):
num_translations += 1
return num_translations | python | def update_translations(condition=None):
"""
Updates FieldTranslations table
"""
if condition is None:
condition = {}
# Number of updated translations
num_translations = 0
# Module caching
FieldTranslation._init_module_cache()
# Current languages dict
LANGUAGES = dict(lang for lang in MODELTRANSLATION_LANG_CHOICES)
if settings.LANGUAGE_CODE in LANGUAGES:
del LANGUAGES[settings.LANGUAGE_CODE]
# For each module, we are going to update the translations
for key in FieldTranslation._modules.keys():
module = FieldTranslation._modules[key]
# Class of the module
clsmembers = inspect.getmembers(sys.modules[key], inspect.isclass)
for cls in clsmembers:
cls = cls[1]
# If the model has in Meta "translatable_fields", we insert this fields
if hasattr(cls,"_meta") and not cls._meta.abstract and hasattr(cls._meta,"translatable_fields") and len(cls._meta.translatable_fields)>0:
objects = cls.objects.filter(**condition)
# For each object, language and field are updated
for obj in objects:
for lang in LANGUAGES.keys():
for field in cls._meta.translatable_fields:
if FieldTranslation.update(obj=obj, field=field, lang=lang, context=""):
num_translations += 1
return num_translations | [
"def",
"update_translations",
"(",
"condition",
"=",
"None",
")",
":",
"if",
"condition",
"is",
"None",
":",
"condition",
"=",
"{",
"}",
"# Number of updated translations",
"num_translations",
"=",
"0",
"# Module caching",
"FieldTranslation",
".",
"_init_module_cache",
"(",
")",
"# Current languages dict",
"LANGUAGES",
"=",
"dict",
"(",
"lang",
"for",
"lang",
"in",
"MODELTRANSLATION_LANG_CHOICES",
")",
"if",
"settings",
".",
"LANGUAGE_CODE",
"in",
"LANGUAGES",
":",
"del",
"LANGUAGES",
"[",
"settings",
".",
"LANGUAGE_CODE",
"]",
"# For each module, we are going to update the translations",
"for",
"key",
"in",
"FieldTranslation",
".",
"_modules",
".",
"keys",
"(",
")",
":",
"module",
"=",
"FieldTranslation",
".",
"_modules",
"[",
"key",
"]",
"# Class of the module",
"clsmembers",
"=",
"inspect",
".",
"getmembers",
"(",
"sys",
".",
"modules",
"[",
"key",
"]",
",",
"inspect",
".",
"isclass",
")",
"for",
"cls",
"in",
"clsmembers",
":",
"cls",
"=",
"cls",
"[",
"1",
"]",
"# If the model has in Meta \"translatable_fields\", we insert this fields",
"if",
"hasattr",
"(",
"cls",
",",
"\"_meta\"",
")",
"and",
"not",
"cls",
".",
"_meta",
".",
"abstract",
"and",
"hasattr",
"(",
"cls",
".",
"_meta",
",",
"\"translatable_fields\"",
")",
"and",
"len",
"(",
"cls",
".",
"_meta",
".",
"translatable_fields",
")",
">",
"0",
":",
"objects",
"=",
"cls",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"condition",
")",
"# For each object, language and field are updated",
"for",
"obj",
"in",
"objects",
":",
"for",
"lang",
"in",
"LANGUAGES",
".",
"keys",
"(",
")",
":",
"for",
"field",
"in",
"cls",
".",
"_meta",
".",
"translatable_fields",
":",
"if",
"FieldTranslation",
".",
"update",
"(",
"obj",
"=",
"obj",
",",
"field",
"=",
"field",
",",
"lang",
"=",
"lang",
",",
"context",
"=",
"\"\"",
")",
":",
"num_translations",
"+=",
"1",
"return",
"num_translations"
] | Updates FieldTranslations table | [
"Updates",
"FieldTranslations",
"table"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L241-L278 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation.factory | def factory(obj, field, source_text, lang, context=""):
"""
Static method that constructs a translation based on its contents.
"""
# Model name
obj_classname = obj.__class__.__name__
# Module name
obj_module = obj.__module__
# Computation of MD5 of the source text
source_md5 = checksum(source_text)
# Translated text
translation = ""
# Translation text attribute name
field_lang = trans_attr(field,lang)
# If in source object there is a translation and is not empty, we asume it was assigned and it's correct
if hasattr(obj,field_lang) and getattr(obj,field_lang)!="":
translation = getattr(obj,field_lang)
# Is the translation fuzzy?
is_fuzzy = True
is_fuzzy_lang = trans_is_fuzzy_attr(field,lang)
if hasattr(obj,is_fuzzy_lang):
is_fuzzy = getattr(obj,is_fuzzy_lang)
# Construction of the translation
trans = FieldTranslation(module=obj_module, model=obj_classname, object_id=obj.id,
field=field, lang=lang, source_text=source_text, source_md5=source_md5,
translation=translation, is_fuzzy=is_fuzzy, context=context)
return trans | python | def factory(obj, field, source_text, lang, context=""):
"""
Static method that constructs a translation based on its contents.
"""
# Model name
obj_classname = obj.__class__.__name__
# Module name
obj_module = obj.__module__
# Computation of MD5 of the source text
source_md5 = checksum(source_text)
# Translated text
translation = ""
# Translation text attribute name
field_lang = trans_attr(field,lang)
# If in source object there is a translation and is not empty, we asume it was assigned and it's correct
if hasattr(obj,field_lang) and getattr(obj,field_lang)!="":
translation = getattr(obj,field_lang)
# Is the translation fuzzy?
is_fuzzy = True
is_fuzzy_lang = trans_is_fuzzy_attr(field,lang)
if hasattr(obj,is_fuzzy_lang):
is_fuzzy = getattr(obj,is_fuzzy_lang)
# Construction of the translation
trans = FieldTranslation(module=obj_module, model=obj_classname, object_id=obj.id,
field=field, lang=lang, source_text=source_text, source_md5=source_md5,
translation=translation, is_fuzzy=is_fuzzy, context=context)
return trans | [
"def",
"factory",
"(",
"obj",
",",
"field",
",",
"source_text",
",",
"lang",
",",
"context",
"=",
"\"\"",
")",
":",
"# Model name",
"obj_classname",
"=",
"obj",
".",
"__class__",
".",
"__name__",
"# Module name",
"obj_module",
"=",
"obj",
".",
"__module__",
"# Computation of MD5 of the source text",
"source_md5",
"=",
"checksum",
"(",
"source_text",
")",
"# Translated text",
"translation",
"=",
"\"\"",
"# Translation text attribute name",
"field_lang",
"=",
"trans_attr",
"(",
"field",
",",
"lang",
")",
"# If in source object there is a translation and is not empty, we asume it was assigned and it's correct",
"if",
"hasattr",
"(",
"obj",
",",
"field_lang",
")",
"and",
"getattr",
"(",
"obj",
",",
"field_lang",
")",
"!=",
"\"\"",
":",
"translation",
"=",
"getattr",
"(",
"obj",
",",
"field_lang",
")",
"# Is the translation fuzzy?",
"is_fuzzy",
"=",
"True",
"is_fuzzy_lang",
"=",
"trans_is_fuzzy_attr",
"(",
"field",
",",
"lang",
")",
"if",
"hasattr",
"(",
"obj",
",",
"is_fuzzy_lang",
")",
":",
"is_fuzzy",
"=",
"getattr",
"(",
"obj",
",",
"is_fuzzy_lang",
")",
"# Construction of the translation",
"trans",
"=",
"FieldTranslation",
"(",
"module",
"=",
"obj_module",
",",
"model",
"=",
"obj_classname",
",",
"object_id",
"=",
"obj",
".",
"id",
",",
"field",
"=",
"field",
",",
"lang",
"=",
"lang",
",",
"source_text",
"=",
"source_text",
",",
"source_md5",
"=",
"source_md5",
",",
"translation",
"=",
"translation",
",",
"is_fuzzy",
"=",
"is_fuzzy",
",",
"context",
"=",
"context",
")",
"return",
"trans"
] | Static method that constructs a translation based on its contents. | [
"Static",
"method",
"that",
"constructs",
"a",
"translation",
"based",
"on",
"its",
"contents",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L313-L347 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation.save | def save(self, *args, **kwargs):
"""
Save object in database, updating the datetimes accordingly.
"""
# Now in UTC
now_datetime = timezone.now()
# If we are in a creation, assigns creation_datetime
if not self.id:
self.creation_datetime = now_datetime
# Las update datetime is always updated
self.last_update_datetime = now_datetime
# Current user is creator
# (get current user with django-cuser middleware)
self.creator_user = None
current_user = CuserMiddleware.get_user()
if not current_user is None and not current_user.is_anonymous():
self.creator_user_id = current_user.id
# Parent constructor call
super(FieldTranslation, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Save object in database, updating the datetimes accordingly.
"""
# Now in UTC
now_datetime = timezone.now()
# If we are in a creation, assigns creation_datetime
if not self.id:
self.creation_datetime = now_datetime
# Las update datetime is always updated
self.last_update_datetime = now_datetime
# Current user is creator
# (get current user with django-cuser middleware)
self.creator_user = None
current_user = CuserMiddleware.get_user()
if not current_user is None and not current_user.is_anonymous():
self.creator_user_id = current_user.id
# Parent constructor call
super(FieldTranslation, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Now in UTC",
"now_datetime",
"=",
"timezone",
".",
"now",
"(",
")",
"# If we are in a creation, assigns creation_datetime",
"if",
"not",
"self",
".",
"id",
":",
"self",
".",
"creation_datetime",
"=",
"now_datetime",
"# Las update datetime is always updated",
"self",
".",
"last_update_datetime",
"=",
"now_datetime",
"# Current user is creator",
"# (get current user with django-cuser middleware)",
"self",
".",
"creator_user",
"=",
"None",
"current_user",
"=",
"CuserMiddleware",
".",
"get_user",
"(",
")",
"if",
"not",
"current_user",
"is",
"None",
"and",
"not",
"current_user",
".",
"is_anonymous",
"(",
")",
":",
"self",
".",
"creator_user_id",
"=",
"current_user",
".",
"id",
"# Parent constructor call",
"super",
"(",
"FieldTranslation",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Save object in database, updating the datetimes accordingly. | [
"Save",
"object",
"in",
"database",
"updating",
"the",
"datetimes",
"accordingly",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L413-L436 |
softwarefactory-project/distroinfo | distroinfo/parse.py | parse_info | def parse_info(raw_info, apply_tag=None):
"""
Parse raw rdoinfo metadata inplace.
:param raw_info: raw info to parse
:param apply_tag: tag to apply
:returns: dictionary containing all packages in rdoinfo
"""
parse_releases(raw_info)
parse_packages(raw_info, apply_tag=apply_tag)
return raw_info | python | def parse_info(raw_info, apply_tag=None):
"""
Parse raw rdoinfo metadata inplace.
:param raw_info: raw info to parse
:param apply_tag: tag to apply
:returns: dictionary containing all packages in rdoinfo
"""
parse_releases(raw_info)
parse_packages(raw_info, apply_tag=apply_tag)
return raw_info | [
"def",
"parse_info",
"(",
"raw_info",
",",
"apply_tag",
"=",
"None",
")",
":",
"parse_releases",
"(",
"raw_info",
")",
"parse_packages",
"(",
"raw_info",
",",
"apply_tag",
"=",
"apply_tag",
")",
"return",
"raw_info"
] | Parse raw rdoinfo metadata inplace.
:param raw_info: raw info to parse
:param apply_tag: tag to apply
:returns: dictionary containing all packages in rdoinfo | [
"Parse",
"raw",
"rdoinfo",
"metadata",
"inplace",
"."
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/parse.py#L8-L18 |
softwarefactory-project/distroinfo | distroinfo/parse.py | info2dicts | def info2dicts(info, in_place=False):
"""
Return info with:
1) `packages` list replaced by a 'packages' dict indexed by 'project'
2) `releases` list replaced by a 'releases' dict indexed by 'name'
"""
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
info_dicts = info
else:
info_dicts = info.copy()
packages = info.get('packages')
if packages:
info_dicts['packages'] = list2dict(packages, 'project')
releases = info.get('releases')
if releases:
info_dicts['releases'] = list2dict(releases, 'name')
return info_dicts | python | def info2dicts(info, in_place=False):
"""
Return info with:
1) `packages` list replaced by a 'packages' dict indexed by 'project'
2) `releases` list replaced by a 'releases' dict indexed by 'name'
"""
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
info_dicts = info
else:
info_dicts = info.copy()
packages = info.get('packages')
if packages:
info_dicts['packages'] = list2dict(packages, 'project')
releases = info.get('releases')
if releases:
info_dicts['releases'] = list2dict(releases, 'name')
return info_dicts | [
"def",
"info2dicts",
"(",
"info",
",",
"in_place",
"=",
"False",
")",
":",
"if",
"'packages'",
"not",
"in",
"info",
"and",
"'releases'",
"not",
"in",
"info",
":",
"return",
"info",
"if",
"in_place",
":",
"info_dicts",
"=",
"info",
"else",
":",
"info_dicts",
"=",
"info",
".",
"copy",
"(",
")",
"packages",
"=",
"info",
".",
"get",
"(",
"'packages'",
")",
"if",
"packages",
":",
"info_dicts",
"[",
"'packages'",
"]",
"=",
"list2dict",
"(",
"packages",
",",
"'project'",
")",
"releases",
"=",
"info",
".",
"get",
"(",
"'releases'",
")",
"if",
"releases",
":",
"info_dicts",
"[",
"'releases'",
"]",
"=",
"list2dict",
"(",
"releases",
",",
"'name'",
")",
"return",
"info_dicts"
] | Return info with:
1) `packages` list replaced by a 'packages' dict indexed by 'project'
2) `releases` list replaced by a 'releases' dict indexed by 'name' | [
"Return",
"info",
"with",
":"
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/parse.py#L189-L208 |
softwarefactory-project/distroinfo | distroinfo/parse.py | info2lists | def info2lists(info, in_place=False):
"""
Return info with:
1) `packages` dict replaced by a 'packages' list with indexes removed
2) `releases` dict replaced by a 'releases' list with indexes removed
info2list(info2dicts(info)) == info
"""
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
info_lists = info
else:
info_lists = info.copy()
packages = info.get('packages')
if packages:
info_lists['packages'] = list(packages.values())
releases = info.get('releases')
if releases:
info_lists['releases'] = list(releases.values())
return info_lists | python | def info2lists(info, in_place=False):
"""
Return info with:
1) `packages` dict replaced by a 'packages' list with indexes removed
2) `releases` dict replaced by a 'releases' list with indexes removed
info2list(info2dicts(info)) == info
"""
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
info_lists = info
else:
info_lists = info.copy()
packages = info.get('packages')
if packages:
info_lists['packages'] = list(packages.values())
releases = info.get('releases')
if releases:
info_lists['releases'] = list(releases.values())
return info_lists | [
"def",
"info2lists",
"(",
"info",
",",
"in_place",
"=",
"False",
")",
":",
"if",
"'packages'",
"not",
"in",
"info",
"and",
"'releases'",
"not",
"in",
"info",
":",
"return",
"info",
"if",
"in_place",
":",
"info_lists",
"=",
"info",
"else",
":",
"info_lists",
"=",
"info",
".",
"copy",
"(",
")",
"packages",
"=",
"info",
".",
"get",
"(",
"'packages'",
")",
"if",
"packages",
":",
"info_lists",
"[",
"'packages'",
"]",
"=",
"list",
"(",
"packages",
".",
"values",
"(",
")",
")",
"releases",
"=",
"info",
".",
"get",
"(",
"'releases'",
")",
"if",
"releases",
":",
"info_lists",
"[",
"'releases'",
"]",
"=",
"list",
"(",
"releases",
".",
"values",
"(",
")",
")",
"return",
"info_lists"
] | Return info with:
1) `packages` dict replaced by a 'packages' list with indexes removed
2) `releases` dict replaced by a 'releases' list with indexes removed
info2list(info2dicts(info)) == info | [
"Return",
"info",
"with",
":"
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/parse.py#L211-L233 |
xapple/plumbing | plumbing/common.py | alphanumeric | def alphanumeric(text):
"""Make an ultra-safe, ASCII version a string.
For instance for use as a filename.
\w matches any alphanumeric character and the underscore."""
return "".join([c for c in text if re.match(r'\w', c)]) | python | def alphanumeric(text):
"""Make an ultra-safe, ASCII version a string.
For instance for use as a filename.
\w matches any alphanumeric character and the underscore."""
return "".join([c for c in text if re.match(r'\w', c)]) | [
"def",
"alphanumeric",
"(",
"text",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"text",
"if",
"re",
".",
"match",
"(",
"r'\\w'",
",",
"c",
")",
"]",
")"
] | Make an ultra-safe, ASCII version a string.
For instance for use as a filename.
\w matches any alphanumeric character and the underscore. | [
"Make",
"an",
"ultra",
"-",
"safe",
"ASCII",
"version",
"a",
"string",
".",
"For",
"instance",
"for",
"use",
"as",
"a",
"filename",
".",
"\\",
"w",
"matches",
"any",
"alphanumeric",
"character",
"and",
"the",
"underscore",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L23-L27 |
xapple/plumbing | plumbing/common.py | sanitize_text | def sanitize_text(text):
"""Make a safe representation of a string.
Note: the `\s` special character matches any whitespace character.
This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace)."""
# First replace characters that have specific effects with their repr #
text = re.sub("(\s)", lambda m: repr(m.group(0)).strip("'"), text)
# Make it a unicode string (the try supports python 2 and 3) #
try: text = text.decode('utf-8')
except AttributeError: pass
# Normalize it “
text = unicodedata.normalize('NFC', text)
return text | python | def sanitize_text(text):
"""Make a safe representation of a string.
Note: the `\s` special character matches any whitespace character.
This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace)."""
# First replace characters that have specific effects with their repr #
text = re.sub("(\s)", lambda m: repr(m.group(0)).strip("'"), text)
# Make it a unicode string (the try supports python 2 and 3) #
try: text = text.decode('utf-8')
except AttributeError: pass
# Normalize it “
text = unicodedata.normalize('NFC', text)
return text | [
"def",
"sanitize_text",
"(",
"text",
")",
":",
"# First replace characters that have specific effects with their repr #",
"text",
"=",
"re",
".",
"sub",
"(",
"\"(\\s)\"",
",",
"lambda",
"m",
":",
"repr",
"(",
"m",
".",
"group",
"(",
"0",
")",
")",
".",
"strip",
"(",
"\"'\"",
")",
",",
"text",
")",
"# Make it a unicode string (the try supports python 2 and 3) #",
"try",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"AttributeError",
":",
"pass",
"# Normalize it “",
"text",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"text",
")",
"return",
"text"
] | Make a safe representation of a string.
Note: the `\s` special character matches any whitespace character.
This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace). | [
"Make",
"a",
"safe",
"representation",
"of",
"a",
"string",
".",
"Note",
":",
"the",
"\\",
"s",
"special",
"character",
"matches",
"any",
"whitespace",
"character",
".",
"This",
"is",
"equivalent",
"to",
"the",
"set",
"[",
"\\",
"t",
"\\",
"n",
"\\",
"r",
"\\",
"f",
"\\",
"v",
"]",
"as",
"well",
"as",
"(",
"whitespace",
")",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L30-L41 |
xapple/plumbing | plumbing/common.py | camel_to_snake | def camel_to_snake(text):
"""
Will convert CamelCaseStrings to snake_case_strings.
>>> camel_to_snake('CamelCase')
'camel_case'
>>> camel_to_snake('CamelCamelCase')
'camel_camel_case'
>>> camel_to_snake('Camel2Camel2Case')
'camel2_camel2_case'
>>> camel_to_snake('getHTTPResponseCode')
'get_http_response_code'
>>> camel_to_snake('get2HTTPResponseCode')
'get2_http_response_code'
>>> camel_to_snake('HTTPResponseCode')
'http_response_code'
>>> camel_to_snake('HTTPResponseCodeXYZ')
'http_response_code_xyz'
"""
step_one = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
step_two = re.sub('([a-z0-9])([A-Z])', r'\1_\2', step_one)
return step_two.lower() | python | def camel_to_snake(text):
"""
Will convert CamelCaseStrings to snake_case_strings.
>>> camel_to_snake('CamelCase')
'camel_case'
>>> camel_to_snake('CamelCamelCase')
'camel_camel_case'
>>> camel_to_snake('Camel2Camel2Case')
'camel2_camel2_case'
>>> camel_to_snake('getHTTPResponseCode')
'get_http_response_code'
>>> camel_to_snake('get2HTTPResponseCode')
'get2_http_response_code'
>>> camel_to_snake('HTTPResponseCode')
'http_response_code'
>>> camel_to_snake('HTTPResponseCodeXYZ')
'http_response_code_xyz'
"""
step_one = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
step_two = re.sub('([a-z0-9])([A-Z])', r'\1_\2', step_one)
return step_two.lower() | [
"def",
"camel_to_snake",
"(",
"text",
")",
":",
"step_one",
"=",
"re",
".",
"sub",
"(",
"'(.)([A-Z][a-z]+)'",
",",
"r'\\1_\\2'",
",",
"text",
")",
"step_two",
"=",
"re",
".",
"sub",
"(",
"'([a-z0-9])([A-Z])'",
",",
"r'\\1_\\2'",
",",
"step_one",
")",
"return",
"step_two",
".",
"lower",
"(",
")"
] | Will convert CamelCaseStrings to snake_case_strings.
>>> camel_to_snake('CamelCase')
'camel_case'
>>> camel_to_snake('CamelCamelCase')
'camel_camel_case'
>>> camel_to_snake('Camel2Camel2Case')
'camel2_camel2_case'
>>> camel_to_snake('getHTTPResponseCode')
'get_http_response_code'
>>> camel_to_snake('get2HTTPResponseCode')
'get2_http_response_code'
>>> camel_to_snake('HTTPResponseCode')
'http_response_code'
>>> camel_to_snake('HTTPResponseCodeXYZ')
'http_response_code_xyz' | [
"Will",
"convert",
"CamelCaseStrings",
"to",
"snake_case_strings",
".",
">>>",
"camel_to_snake",
"(",
"CamelCase",
")",
"camel_case",
">>>",
"camel_to_snake",
"(",
"CamelCamelCase",
")",
"camel_camel_case",
">>>",
"camel_to_snake",
"(",
"Camel2Camel2Case",
")",
"camel2_camel2_case",
">>>",
"camel_to_snake",
"(",
"getHTTPResponseCode",
")",
"get_http_response_code",
">>>",
"camel_to_snake",
"(",
"get2HTTPResponseCode",
")",
"get2_http_response_code",
">>>",
"camel_to_snake",
"(",
"HTTPResponseCode",
")",
"http_response_code",
">>>",
"camel_to_snake",
"(",
"HTTPResponseCodeXYZ",
")",
"http_response_code_xyz"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L44-L64 |
xapple/plumbing | plumbing/common.py | bool_to_unicode | def bool_to_unicode(b):
"""Different possibilities for True: ☑️✔︎✓✅👍✔️
Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴"""
b = bool(b)
if b is True: return u"✅"
if b is False: return u"❎" | python | def bool_to_unicode(b):
"""Different possibilities for True: ☑️✔︎✓✅👍✔️
Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴"""
b = bool(b)
if b is True: return u"✅"
if b is False: return u"❎" | [
"def",
"bool_to_unicode",
"(",
"b",
")",
":",
"b",
"=",
"bool",
"(",
"b",
")",
"if",
"b",
"is",
"True",
":",
"return",
"u\"✅\"",
"if",
"b",
"is",
"False",
":",
"return",
"u\"❎\""
] | Different possibilities for True: ☑️✔︎✓✅👍✔️
Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴 | [
"Different",
"possibilities",
"for",
"True",
":",
"☑️✔︎✓✅👍✔️",
"Different",
"possibilities",
"for",
"False",
":",
"✕✖︎✗✘✖️❌⛔️❎👎🛑🔴"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L67-L72 |
xapple/plumbing | plumbing/common.py | access_dict_like_obj | def access_dict_like_obj(obj, prop, new_value=None):
"""
Access a dictionary like if it was an object with properties.
If no "new_value", then it's a getter, otherwise it's a setter.
>>> {'characters': {'cast': 'Jean-Luc Picard', 'featuring': 'Deanna Troi'}}
>>> access_dict_like_obj(startrek, 'characters.cast', 'Pierce Brosnan')
"""
props = prop.split('.')
if new_value:
if props[0] not in obj: obj[props[0]] = {}
if len(props)==1: obj[prop] = new_value
else: return access_dict_like_obj(obj[props[0]], '.'.join(props[1:]), new_value)
else:
if len(props)==1: return obj[prop]
else: return access_dict_like_obj(obj[props[0]], '.'.join(props[1:])) | python | def access_dict_like_obj(obj, prop, new_value=None):
"""
Access a dictionary like if it was an object with properties.
If no "new_value", then it's a getter, otherwise it's a setter.
>>> {'characters': {'cast': 'Jean-Luc Picard', 'featuring': 'Deanna Troi'}}
>>> access_dict_like_obj(startrek, 'characters.cast', 'Pierce Brosnan')
"""
props = prop.split('.')
if new_value:
if props[0] not in obj: obj[props[0]] = {}
if len(props)==1: obj[prop] = new_value
else: return access_dict_like_obj(obj[props[0]], '.'.join(props[1:]), new_value)
else:
if len(props)==1: return obj[prop]
else: return access_dict_like_obj(obj[props[0]], '.'.join(props[1:])) | [
"def",
"access_dict_like_obj",
"(",
"obj",
",",
"prop",
",",
"new_value",
"=",
"None",
")",
":",
"props",
"=",
"prop",
".",
"split",
"(",
"'.'",
")",
"if",
"new_value",
":",
"if",
"props",
"[",
"0",
"]",
"not",
"in",
"obj",
":",
"obj",
"[",
"props",
"[",
"0",
"]",
"]",
"=",
"{",
"}",
"if",
"len",
"(",
"props",
")",
"==",
"1",
":",
"obj",
"[",
"prop",
"]",
"=",
"new_value",
"else",
":",
"return",
"access_dict_like_obj",
"(",
"obj",
"[",
"props",
"[",
"0",
"]",
"]",
",",
"'.'",
".",
"join",
"(",
"props",
"[",
"1",
":",
"]",
")",
",",
"new_value",
")",
"else",
":",
"if",
"len",
"(",
"props",
")",
"==",
"1",
":",
"return",
"obj",
"[",
"prop",
"]",
"else",
":",
"return",
"access_dict_like_obj",
"(",
"obj",
"[",
"props",
"[",
"0",
"]",
"]",
",",
"'.'",
".",
"join",
"(",
"props",
"[",
"1",
":",
"]",
")",
")"
] | Access a dictionary like if it was an object with properties.
If no "new_value", then it's a getter, otherwise it's a setter.
>>> {'characters': {'cast': 'Jean-Luc Picard', 'featuring': 'Deanna Troi'}}
>>> access_dict_like_obj(startrek, 'characters.cast', 'Pierce Brosnan') | [
"Access",
"a",
"dictionary",
"like",
"if",
"it",
"was",
"an",
"object",
"with",
"properties",
".",
"If",
"no",
"new_value",
"then",
"it",
"s",
"a",
"getter",
"otherwise",
"it",
"s",
"a",
"setter",
".",
">>>",
"{",
"characters",
":",
"{",
"cast",
":",
"Jean",
"-",
"Luc",
"Picard",
"featuring",
":",
"Deanna",
"Troi",
"}}",
">>>",
"access_dict_like_obj",
"(",
"startrek",
"characters",
".",
"cast",
"Pierce",
"Brosnan",
")"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L75-L89 |
xapple/plumbing | plumbing/common.py | all_combinations | def all_combinations(items):
"""Generate all combinations of a given list of items."""
return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items))) | python | def all_combinations(items):
"""Generate all combinations of a given list of items."""
return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items))) | [
"def",
"all_combinations",
"(",
"items",
")",
":",
"return",
"(",
"set",
"(",
"compress",
"(",
"items",
",",
"mask",
")",
")",
"for",
"mask",
"in",
"product",
"(",
"*",
"[",
"[",
"0",
",",
"1",
"]",
"]",
"*",
"len",
"(",
"items",
")",
")",
")"
] | Generate all combinations of a given list of items. | [
"Generate",
"all",
"combinations",
"of",
"a",
"given",
"list",
"of",
"items",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L92-L94 |
xapple/plumbing | plumbing/common.py | pad_equal_whitespace | def pad_equal_whitespace(string, pad=None):
"""Given a multiline string, add whitespaces to every line
so that every line has the same length."""
if pad is None: pad = max(map(len, string.split('\n'))) + 1
return '\n'.join(('{0: <%i}' % pad).format(line) for line in string.split('\n')) | python | def pad_equal_whitespace(string, pad=None):
"""Given a multiline string, add whitespaces to every line
so that every line has the same length."""
if pad is None: pad = max(map(len, string.split('\n'))) + 1
return '\n'.join(('{0: <%i}' % pad).format(line) for line in string.split('\n')) | [
"def",
"pad_equal_whitespace",
"(",
"string",
",",
"pad",
"=",
"None",
")",
":",
"if",
"pad",
"is",
"None",
":",
"pad",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"string",
".",
"split",
"(",
"'\\n'",
")",
")",
")",
"+",
"1",
"return",
"'\\n'",
".",
"join",
"(",
"(",
"'{0: <%i}'",
"%",
"pad",
")",
".",
"format",
"(",
"line",
")",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
")"
] | Given a multiline string, add whitespaces to every line
so that every line has the same length. | [
"Given",
"a",
"multiline",
"string",
"add",
"whitespaces",
"to",
"every",
"line",
"so",
"that",
"every",
"line",
"has",
"the",
"same",
"length",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L97-L101 |
xapple/plumbing | plumbing/common.py | concatenate_by_line | def concatenate_by_line(first, second):
"""Zip two strings together, line wise"""
return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n'))) | python | def concatenate_by_line(first, second):
"""Zip two strings together, line wise"""
return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n'))) | [
"def",
"concatenate_by_line",
"(",
"first",
",",
"second",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"x",
"+",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"first",
".",
"split",
"(",
"'\\n'",
")",
",",
"second",
".",
"split",
"(",
"'\\n'",
")",
")",
")"
] | Zip two strings together, line wise | [
"Zip",
"two",
"strings",
"together",
"line",
"wise"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L115-L117 |
xapple/plumbing | plumbing/common.py | sort_string_by_pairs | def sort_string_by_pairs(strings):
"""Group a list of strings by pairs, by matching those with only
one character difference between each other together."""
assert len(strings) % 2 == 0
pairs = []
strings = list(strings) # This shallow copies the list
while strings:
template = strings.pop()
for i, candidate in enumerate(strings):
if count_string_diff(template, candidate) == 1:
pair = [template, strings.pop(i)]
pair.sort()
pairs.append(pair)
break
return pairs | python | def sort_string_by_pairs(strings):
"""Group a list of strings by pairs, by matching those with only
one character difference between each other together."""
assert len(strings) % 2 == 0
pairs = []
strings = list(strings) # This shallow copies the list
while strings:
template = strings.pop()
for i, candidate in enumerate(strings):
if count_string_diff(template, candidate) == 1:
pair = [template, strings.pop(i)]
pair.sort()
pairs.append(pair)
break
return pairs | [
"def",
"sort_string_by_pairs",
"(",
"strings",
")",
":",
"assert",
"len",
"(",
"strings",
")",
"%",
"2",
"==",
"0",
"pairs",
"=",
"[",
"]",
"strings",
"=",
"list",
"(",
"strings",
")",
"# This shallow copies the list",
"while",
"strings",
":",
"template",
"=",
"strings",
".",
"pop",
"(",
")",
"for",
"i",
",",
"candidate",
"in",
"enumerate",
"(",
"strings",
")",
":",
"if",
"count_string_diff",
"(",
"template",
",",
"candidate",
")",
"==",
"1",
":",
"pair",
"=",
"[",
"template",
",",
"strings",
".",
"pop",
"(",
"i",
")",
"]",
"pair",
".",
"sort",
"(",
")",
"pairs",
".",
"append",
"(",
"pair",
")",
"break",
"return",
"pairs"
] | Group a list of strings by pairs, by matching those with only
one character difference between each other together. | [
"Group",
"a",
"list",
"of",
"strings",
"by",
"pairs",
"by",
"matching",
"those",
"with",
"only",
"one",
"character",
"difference",
"between",
"each",
"other",
"together",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L120-L134 |
xapple/plumbing | plumbing/common.py | count_string_diff | def count_string_diff(a,b):
"""Return the number of characters in two strings that don't exactly match"""
shortest = min(len(a), len(b))
return sum(a[i] != b[i] for i in range(shortest)) | python | def count_string_diff(a,b):
"""Return the number of characters in two strings that don't exactly match"""
shortest = min(len(a), len(b))
return sum(a[i] != b[i] for i in range(shortest)) | [
"def",
"count_string_diff",
"(",
"a",
",",
"b",
")",
":",
"shortest",
"=",
"min",
"(",
"len",
"(",
"a",
")",
",",
"len",
"(",
"b",
")",
")",
"return",
"sum",
"(",
"a",
"[",
"i",
"]",
"!=",
"b",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"shortest",
")",
")"
] | Return the number of characters in two strings that don't exactly match | [
"Return",
"the",
"number",
"of",
"characters",
"in",
"two",
"strings",
"that",
"don",
"t",
"exactly",
"match"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L137-L140 |
xapple/plumbing | plumbing/common.py | iflatten | def iflatten(L):
"""Iterative flatten."""
for sublist in L:
if hasattr(sublist, '__iter__'):
for item in iflatten(sublist): yield item
else: yield sublist | python | def iflatten(L):
"""Iterative flatten."""
for sublist in L:
if hasattr(sublist, '__iter__'):
for item in iflatten(sublist): yield item
else: yield sublist | [
"def",
"iflatten",
"(",
"L",
")",
":",
"for",
"sublist",
"in",
"L",
":",
"if",
"hasattr",
"(",
"sublist",
",",
"'__iter__'",
")",
":",
"for",
"item",
"in",
"iflatten",
"(",
"sublist",
")",
":",
"yield",
"item",
"else",
":",
"yield",
"sublist"
] | Iterative flatten. | [
"Iterative",
"flatten",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L143-L148 |
xapple/plumbing | plumbing/common.py | uniquify_list | def uniquify_list(L):
"""Same order unique list using only a list compression."""
return [e for i, e in enumerate(L) if L.index(e) == i] | python | def uniquify_list(L):
"""Same order unique list using only a list compression."""
return [e for i, e in enumerate(L) if L.index(e) == i] | [
"def",
"uniquify_list",
"(",
"L",
")",
":",
"return",
"[",
"e",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"L",
")",
"if",
"L",
".",
"index",
"(",
"e",
")",
"==",
"i",
"]"
] | Same order unique list using only a list compression. | [
"Same",
"order",
"unique",
"list",
"using",
"only",
"a",
"list",
"compression",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L151-L153 |
xapple/plumbing | plumbing/common.py | average | def average(iterator):
"""Iterative mean."""
count = 0
total = 0
for num in iterator:
count += 1
total += num
return float(total)/count | python | def average(iterator):
"""Iterative mean."""
count = 0
total = 0
for num in iterator:
count += 1
total += num
return float(total)/count | [
"def",
"average",
"(",
"iterator",
")",
":",
"count",
"=",
"0",
"total",
"=",
"0",
"for",
"num",
"in",
"iterator",
":",
"count",
"+=",
"1",
"total",
"+=",
"num",
"return",
"float",
"(",
"total",
")",
"/",
"count"
] | Iterative mean. | [
"Iterative",
"mean",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L156-L163 |
xapple/plumbing | plumbing/common.py | get_next_item | def get_next_item(iterable):
"""Gets the next item of an iterable.
If the iterable is exhausted, returns None."""
try: x = iterable.next()
except StopIteration: x = None
except AttributeError: x = None
return x | python | def get_next_item(iterable):
"""Gets the next item of an iterable.
If the iterable is exhausted, returns None."""
try: x = iterable.next()
except StopIteration: x = None
except AttributeError: x = None
return x | [
"def",
"get_next_item",
"(",
"iterable",
")",
":",
"try",
":",
"x",
"=",
"iterable",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"x",
"=",
"None",
"except",
"AttributeError",
":",
"x",
"=",
"None",
"return",
"x"
] | Gets the next item of an iterable.
If the iterable is exhausted, returns None. | [
"Gets",
"the",
"next",
"item",
"of",
"an",
"iterable",
".",
"If",
"the",
"iterable",
"is",
"exhausted",
"returns",
"None",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L166-L172 |
xapple/plumbing | plumbing/common.py | pretty_now | def pretty_now():
"""Returns some thing like '2019-02-15 15:58:22 CET+0100'"""
import datetime, tzlocal
time_zone = tzlocal.get_localzone()
now = datetime.datetime.now(time_zone)
return now.strftime("%Y-%m-%d %H:%M:%S %Z%z") | python | def pretty_now():
"""Returns some thing like '2019-02-15 15:58:22 CET+0100'"""
import datetime, tzlocal
time_zone = tzlocal.get_localzone()
now = datetime.datetime.now(time_zone)
return now.strftime("%Y-%m-%d %H:%M:%S %Z%z") | [
"def",
"pretty_now",
"(",
")",
":",
"import",
"datetime",
",",
"tzlocal",
"time_zone",
"=",
"tzlocal",
".",
"get_localzone",
"(",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"time_zone",
")",
"return",
"now",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S %Z%z\"",
")"
] | Returns some thing like '2019-02-15 15:58:22 CET+0100 | [
"Returns",
"some",
"thing",
"like",
"2019",
"-",
"02",
"-",
"15",
"15",
":",
"58",
":",
"22",
"CET",
"+",
"0100"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L175-L180 |
xapple/plumbing | plumbing/common.py | andify | def andify(list_of_strings):
"""
Given a list of strings will join them with commas
and a final "and" word.
>>> andify(['Apples', 'Oranges', 'Mangos'])
'Apples, Oranges and Mangos'
"""
result = ', '.join(list_of_strings)
comma_index = result.rfind(',')
if comma_index > -1: result = result[:comma_index] + ' and' + result[comma_index+1:]
return result | python | def andify(list_of_strings):
"""
Given a list of strings will join them with commas
and a final "and" word.
>>> andify(['Apples', 'Oranges', 'Mangos'])
'Apples, Oranges and Mangos'
"""
result = ', '.join(list_of_strings)
comma_index = result.rfind(',')
if comma_index > -1: result = result[:comma_index] + ' and' + result[comma_index+1:]
return result | [
"def",
"andify",
"(",
"list_of_strings",
")",
":",
"result",
"=",
"', '",
".",
"join",
"(",
"list_of_strings",
")",
"comma_index",
"=",
"result",
".",
"rfind",
"(",
"','",
")",
"if",
"comma_index",
">",
"-",
"1",
":",
"result",
"=",
"result",
"[",
":",
"comma_index",
"]",
"+",
"' and'",
"+",
"result",
"[",
"comma_index",
"+",
"1",
":",
"]",
"return",
"result"
] | Given a list of strings will join them with commas
and a final "and" word.
>>> andify(['Apples', 'Oranges', 'Mangos'])
'Apples, Oranges and Mangos' | [
"Given",
"a",
"list",
"of",
"strings",
"will",
"join",
"them",
"with",
"commas",
"and",
"a",
"final",
"and",
"word",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L183-L194 |
xapple/plumbing | plumbing/common.py | num_to_ith | def num_to_ith(num):
"""1 becomes 1st, 2 becomes 2nd, etc."""
value = str(num)
before_last_digit = value[-2]
last_digit = value[-1]
if len(value) > 1 and before_last_digit == '1': return value +'th'
if last_digit == '1': return value + 'st'
if last_digit == '2': return value + 'nd'
if last_digit == '3': return value + 'rd'
return value + 'th' | python | def num_to_ith(num):
"""1 becomes 1st, 2 becomes 2nd, etc."""
value = str(num)
before_last_digit = value[-2]
last_digit = value[-1]
if len(value) > 1 and before_last_digit == '1': return value +'th'
if last_digit == '1': return value + 'st'
if last_digit == '2': return value + 'nd'
if last_digit == '3': return value + 'rd'
return value + 'th' | [
"def",
"num_to_ith",
"(",
"num",
")",
":",
"value",
"=",
"str",
"(",
"num",
")",
"before_last_digit",
"=",
"value",
"[",
"-",
"2",
"]",
"last_digit",
"=",
"value",
"[",
"-",
"1",
"]",
"if",
"len",
"(",
"value",
")",
">",
"1",
"and",
"before_last_digit",
"==",
"'1'",
":",
"return",
"value",
"+",
"'th'",
"if",
"last_digit",
"==",
"'1'",
":",
"return",
"value",
"+",
"'st'",
"if",
"last_digit",
"==",
"'2'",
":",
"return",
"value",
"+",
"'nd'",
"if",
"last_digit",
"==",
"'3'",
":",
"return",
"value",
"+",
"'rd'",
"return",
"value",
"+",
"'th'"
] | 1 becomes 1st, 2 becomes 2nd, etc. | [
"1",
"becomes",
"1st",
"2",
"becomes",
"2nd",
"etc",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L197-L206 |
xapple/plumbing | plumbing/common.py | isubsample | def isubsample(full_sample, k, full_sample_len=None):
"""Down-sample an enumerable list of things"""
# Determine length #
if not full_sample_len: full_sample_len = len(full_sample)
# Check size coherence #
if not 0 <= k <= full_sample_len:
raise ValueError('Required that 0 <= k <= full_sample_length')
# Do it #
picked = 0
for i, element in enumerate(full_sample):
prob = (k-picked) / (full_sample_len-i)
if random.random() < prob:
yield element
picked += 1
# Did we pick the right amount #
assert picked == k | python | def isubsample(full_sample, k, full_sample_len=None):
"""Down-sample an enumerable list of things"""
# Determine length #
if not full_sample_len: full_sample_len = len(full_sample)
# Check size coherence #
if not 0 <= k <= full_sample_len:
raise ValueError('Required that 0 <= k <= full_sample_length')
# Do it #
picked = 0
for i, element in enumerate(full_sample):
prob = (k-picked) / (full_sample_len-i)
if random.random() < prob:
yield element
picked += 1
# Did we pick the right amount #
assert picked == k | [
"def",
"isubsample",
"(",
"full_sample",
",",
"k",
",",
"full_sample_len",
"=",
"None",
")",
":",
"# Determine length #",
"if",
"not",
"full_sample_len",
":",
"full_sample_len",
"=",
"len",
"(",
"full_sample",
")",
"# Check size coherence #",
"if",
"not",
"0",
"<=",
"k",
"<=",
"full_sample_len",
":",
"raise",
"ValueError",
"(",
"'Required that 0 <= k <= full_sample_length'",
")",
"# Do it #",
"picked",
"=",
"0",
"for",
"i",
",",
"element",
"in",
"enumerate",
"(",
"full_sample",
")",
":",
"prob",
"=",
"(",
"k",
"-",
"picked",
")",
"/",
"(",
"full_sample_len",
"-",
"i",
")",
"if",
"random",
".",
"random",
"(",
")",
"<",
"prob",
":",
"yield",
"element",
"picked",
"+=",
"1",
"# Did we pick the right amount #",
"assert",
"picked",
"==",
"k"
] | Down-sample an enumerable list of things | [
"Down",
"-",
"sample",
"an",
"enumerable",
"list",
"of",
"things"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L209-L224 |
xapple/plumbing | plumbing/common.py | moving_average | def moving_average(interval, windowsize, borders=None):
"""This is essentially a convolving operation. Several option exist for dealing with the border cases.
* None: Here the returned signal will be smaller than the inputted interval.
* zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original interval before operating the convolution.
* zero_padding_and_cut: Same as above only the result is truncated to be the same size as the original input.
* copy_padding: Here the returned signal will be larger than the inputted interval and we will use the right and leftmost values for padding before operating the convolution.
* copy_padding_and_cut: Same as above only the result is truncated to be the same size as the original input.
* zero_stretching: Here we will compute the convolution only in the valid domain, then add zeros to the result so that the output is the same size as the input.
* copy_stretching: Here we will compute the convolution only in the valid domain, then copy the right and leftmost values so that the output is the same size as the input.
"""
# The window size in half #
half = int(math.floor(windowsize/2.0))
# The normalized rectangular signal #
window = numpy.ones(int(windowsize))/float(windowsize)
# How do we deal with borders #
if borders == None:
return numpy.convolve(interval, window, 'valid')
if borders == 'zero_padding':
return numpy.convolve(interval, window, 'full')
if borders == 'zero_padding_and_cut':
return numpy.convolve(interval, window, 'same')
if borders == 'copy_padding':
new_interval = [interval[0]]*(windowsize-1) + interval + [interval[-1]]*(windowsize-1)
return numpy.convolve(new_interval, window, 'valid')
if borders == 'copy_padding_and_cut':
new_interval = [interval[0]]*(windowsize-1) + interval + [interval[-1]]*(windowsize-1)
return numpy.convolve(new_interval, window, 'valid')[half:-half]
if borders == 'zero_stretching':
result = numpy.convolve(interval, window, 'valid')
pad = numpy.zeros(half)
return numpy.concatenate((pad, result, pad))
if borders == 'copy_stretching':
result = numpy.convolve(interval, window, 'valid')
left = numpy.ones(half)*result[0]
right = numpy.ones(half)*result[-1]
return numpy.concatenate((left, result, right)) | python | def moving_average(interval, windowsize, borders=None):
"""This is essentially a convolving operation. Several option exist for dealing with the border cases.
* None: Here the returned signal will be smaller than the inputted interval.
* zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original interval before operating the convolution.
* zero_padding_and_cut: Same as above only the result is truncated to be the same size as the original input.
* copy_padding: Here the returned signal will be larger than the inputted interval and we will use the right and leftmost values for padding before operating the convolution.
* copy_padding_and_cut: Same as above only the result is truncated to be the same size as the original input.
* zero_stretching: Here we will compute the convolution only in the valid domain, then add zeros to the result so that the output is the same size as the input.
* copy_stretching: Here we will compute the convolution only in the valid domain, then copy the right and leftmost values so that the output is the same size as the input.
"""
# The window size in half #
half = int(math.floor(windowsize/2.0))
# The normalized rectangular signal #
window = numpy.ones(int(windowsize))/float(windowsize)
# How do we deal with borders #
if borders == None:
return numpy.convolve(interval, window, 'valid')
if borders == 'zero_padding':
return numpy.convolve(interval, window, 'full')
if borders == 'zero_padding_and_cut':
return numpy.convolve(interval, window, 'same')
if borders == 'copy_padding':
new_interval = [interval[0]]*(windowsize-1) + interval + [interval[-1]]*(windowsize-1)
return numpy.convolve(new_interval, window, 'valid')
if borders == 'copy_padding_and_cut':
new_interval = [interval[0]]*(windowsize-1) + interval + [interval[-1]]*(windowsize-1)
return numpy.convolve(new_interval, window, 'valid')[half:-half]
if borders == 'zero_stretching':
result = numpy.convolve(interval, window, 'valid')
pad = numpy.zeros(half)
return numpy.concatenate((pad, result, pad))
if borders == 'copy_stretching':
result = numpy.convolve(interval, window, 'valid')
left = numpy.ones(half)*result[0]
right = numpy.ones(half)*result[-1]
return numpy.concatenate((left, result, right)) | [
"def",
"moving_average",
"(",
"interval",
",",
"windowsize",
",",
"borders",
"=",
"None",
")",
":",
"# The window size in half #",
"half",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"windowsize",
"/",
"2.0",
")",
")",
"# The normalized rectangular signal #",
"window",
"=",
"numpy",
".",
"ones",
"(",
"int",
"(",
"windowsize",
")",
")",
"/",
"float",
"(",
"windowsize",
")",
"# How do we deal with borders #",
"if",
"borders",
"==",
"None",
":",
"return",
"numpy",
".",
"convolve",
"(",
"interval",
",",
"window",
",",
"'valid'",
")",
"if",
"borders",
"==",
"'zero_padding'",
":",
"return",
"numpy",
".",
"convolve",
"(",
"interval",
",",
"window",
",",
"'full'",
")",
"if",
"borders",
"==",
"'zero_padding_and_cut'",
":",
"return",
"numpy",
".",
"convolve",
"(",
"interval",
",",
"window",
",",
"'same'",
")",
"if",
"borders",
"==",
"'copy_padding'",
":",
"new_interval",
"=",
"[",
"interval",
"[",
"0",
"]",
"]",
"*",
"(",
"windowsize",
"-",
"1",
")",
"+",
"interval",
"+",
"[",
"interval",
"[",
"-",
"1",
"]",
"]",
"*",
"(",
"windowsize",
"-",
"1",
")",
"return",
"numpy",
".",
"convolve",
"(",
"new_interval",
",",
"window",
",",
"'valid'",
")",
"if",
"borders",
"==",
"'copy_padding_and_cut'",
":",
"new_interval",
"=",
"[",
"interval",
"[",
"0",
"]",
"]",
"*",
"(",
"windowsize",
"-",
"1",
")",
"+",
"interval",
"+",
"[",
"interval",
"[",
"-",
"1",
"]",
"]",
"*",
"(",
"windowsize",
"-",
"1",
")",
"return",
"numpy",
".",
"convolve",
"(",
"new_interval",
",",
"window",
",",
"'valid'",
")",
"[",
"half",
":",
"-",
"half",
"]",
"if",
"borders",
"==",
"'zero_stretching'",
":",
"result",
"=",
"numpy",
".",
"convolve",
"(",
"interval",
",",
"window",
",",
"'valid'",
")",
"pad",
"=",
"numpy",
".",
"zeros",
"(",
"half",
")",
"return",
"numpy",
".",
"concatenate",
"(",
"(",
"pad",
",",
"result",
",",
"pad",
")",
")",
"if",
"borders",
"==",
"'copy_stretching'",
":",
"result",
"=",
"numpy",
".",
"convolve",
"(",
"interval",
",",
"window",
",",
"'valid'",
")",
"left",
"=",
"numpy",
".",
"ones",
"(",
"half",
")",
"*",
"result",
"[",
"0",
"]",
"right",
"=",
"numpy",
".",
"ones",
"(",
"half",
")",
"*",
"result",
"[",
"-",
"1",
"]",
"return",
"numpy",
".",
"concatenate",
"(",
"(",
"left",
",",
"result",
",",
"right",
")",
")"
] | This is essentially a convolving operation. Several option exist for dealing with the border cases.
* None: Here the returned signal will be smaller than the inputted interval.
* zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original interval before operating the convolution.
* zero_padding_and_cut: Same as above only the result is truncated to be the same size as the original input.
* copy_padding: Here the returned signal will be larger than the inputted interval and we will use the right and leftmost values for padding before operating the convolution.
* copy_padding_and_cut: Same as above only the result is truncated to be the same size as the original input.
* zero_stretching: Here we will compute the convolution only in the valid domain, then add zeros to the result so that the output is the same size as the input.
* copy_stretching: Here we will compute the convolution only in the valid domain, then copy the right and leftmost values so that the output is the same size as the input. | [
"This",
"is",
"essentially",
"a",
"convolving",
"operation",
".",
"Several",
"option",
"exist",
"for",
"dealing",
"with",
"the",
"border",
"cases",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L227-L269 |
xapple/plumbing | plumbing/common.py | wait | def wait(predicate, interval=1, message=lambda: "Waiting..."):
"""Wait until the predicate turns true and display a turning ball."""
ball, next_ball = u"|/-\\", "|"
sys.stdout.write(" \033[K")
sys.stdout.flush()
while not predicate():
time.sleep(1)
next_ball = ball[(ball.index(next_ball) + 1) % len(ball)]
sys.stdout.write("\r " + str(message()) + " " + next_ball + " \033[K")
sys.stdout.flush()
print("\r Done. \033[K")
sys.stdout.flush() | python | def wait(predicate, interval=1, message=lambda: "Waiting..."):
"""Wait until the predicate turns true and display a turning ball."""
ball, next_ball = u"|/-\\", "|"
sys.stdout.write(" \033[K")
sys.stdout.flush()
while not predicate():
time.sleep(1)
next_ball = ball[(ball.index(next_ball) + 1) % len(ball)]
sys.stdout.write("\r " + str(message()) + " " + next_ball + " \033[K")
sys.stdout.flush()
print("\r Done. \033[K")
sys.stdout.flush() | [
"def",
"wait",
"(",
"predicate",
",",
"interval",
"=",
"1",
",",
"message",
"=",
"lambda",
":",
"\"Waiting...\"",
")",
":",
"ball",
",",
"next_ball",
"=",
"u\"|/-\\\\\"",
",",
"\"|\"",
"sys",
".",
"stdout",
".",
"write",
"(",
"\" \\033[K\"",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"while",
"not",
"predicate",
"(",
")",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"next_ball",
"=",
"ball",
"[",
"(",
"ball",
".",
"index",
"(",
"next_ball",
")",
"+",
"1",
")",
"%",
"len",
"(",
"ball",
")",
"]",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"\\r \"",
"+",
"str",
"(",
"message",
"(",
")",
")",
"+",
"\" \"",
"+",
"next_ball",
"+",
"\" \\033[K\"",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"print",
"(",
"\"\\r Done. \\033[K\"",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | Wait until the predicate turns true and display a turning ball. | [
"Wait",
"until",
"the",
"predicate",
"turns",
"true",
"and",
"display",
"a",
"turning",
"ball",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L272-L283 |
xapple/plumbing | plumbing/common.py | natural_sort | def natural_sort(item):
"""
Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
dre = re.compile(r'(\d+)')
return [int(s) if s.isdigit() else s.lower() for s in re.split(dre, item)] | python | def natural_sort(item):
"""
Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
dre = re.compile(r'(\d+)')
return [int(s) if s.isdigit() else s.lower() for s in re.split(dre, item)] | [
"def",
"natural_sort",
"(",
"item",
")",
":",
"dre",
"=",
"re",
".",
"compile",
"(",
"r'(\\d+)'",
")",
"return",
"[",
"int",
"(",
"s",
")",
"if",
"s",
".",
"isdigit",
"(",
")",
"else",
"s",
".",
"lower",
"(",
")",
"for",
"s",
"in",
"re",
".",
"split",
"(",
"dre",
",",
"item",
")",
"]"
] | Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" | [
"Sort",
"strings",
"that",
"contain",
"numbers",
"correctly",
".",
"Works",
"in",
"Python",
"2",
"and",
"3",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L286-L296 |
xapple/plumbing | plumbing/common.py | split_thousands | def split_thousands(s):
"""
Splits a number on thousands.
>>> split_thousands(1000012)
"1'000'012"
"""
# Check input #
if s is None: return "0"
# If it's a string #
if isinstance(s, basestring): s = float(s)
# If it's a float that should be an int #
if isinstance(s, float) and s.is_integer(): s = int(s)
# Use python built-in #
result = "{:,}".format(s)
# But we want single quotes #
result = result.replace(',', "'")
# Return #
return result | python | def split_thousands(s):
"""
Splits a number on thousands.
>>> split_thousands(1000012)
"1'000'012"
"""
# Check input #
if s is None: return "0"
# If it's a string #
if isinstance(s, basestring): s = float(s)
# If it's a float that should be an int #
if isinstance(s, float) and s.is_integer(): s = int(s)
# Use python built-in #
result = "{:,}".format(s)
# But we want single quotes #
result = result.replace(',', "'")
# Return #
return result | [
"def",
"split_thousands",
"(",
"s",
")",
":",
"# Check input #",
"if",
"s",
"is",
"None",
":",
"return",
"\"0\"",
"# If it's a string #",
"if",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"s",
"=",
"float",
"(",
"s",
")",
"# If it's a float that should be an int #",
"if",
"isinstance",
"(",
"s",
",",
"float",
")",
"and",
"s",
".",
"is_integer",
"(",
")",
":",
"s",
"=",
"int",
"(",
"s",
")",
"# Use python built-in #",
"result",
"=",
"\"{:,}\"",
".",
"format",
"(",
"s",
")",
"# But we want single quotes #",
"result",
"=",
"result",
".",
"replace",
"(",
"','",
",",
"\"'\"",
")",
"# Return #",
"return",
"result"
] | Splits a number on thousands.
>>> split_thousands(1000012)
"1'000'012" | [
"Splits",
"a",
"number",
"on",
"thousands",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L299-L317 |
xapple/plumbing | plumbing/common.py | reverse_compl_with_name | def reverse_compl_with_name(old_seq):
"""Reverse a SeqIO sequence, but keep its name intact."""
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | python | def reverse_compl_with_name(old_seq):
"""Reverse a SeqIO sequence, but keep its name intact."""
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | [
"def",
"reverse_compl_with_name",
"(",
"old_seq",
")",
":",
"new_seq",
"=",
"old_seq",
".",
"reverse_complement",
"(",
")",
"new_seq",
".",
"id",
"=",
"old_seq",
".",
"id",
"new_seq",
".",
"description",
"=",
"old_seq",
".",
"description",
"return",
"new_seq"
] | Reverse a SeqIO sequence, but keep its name intact. | [
"Reverse",
"a",
"SeqIO",
"sequence",
"but",
"keep",
"its",
"name",
"intact",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L333-L338 |
xapple/plumbing | plumbing/common.py | load_json_path | def load_json_path(path):
"""Load a file with the json module, but report errors better if it
fails. And have it ordered too !"""
with open(path) as handle:
try: return json.load(handle, object_pairs_hook=collections.OrderedDict)
except ValueError as error:
message = "Could not decode JSON file '%s'." % path
message = "-"*20 + "\n" + message + "\n" + str(error) + "\n" + "-"*20 + "\n"
sys.stderr.write(message)
raise error | python | def load_json_path(path):
"""Load a file with the json module, but report errors better if it
fails. And have it ordered too !"""
with open(path) as handle:
try: return json.load(handle, object_pairs_hook=collections.OrderedDict)
except ValueError as error:
message = "Could not decode JSON file '%s'." % path
message = "-"*20 + "\n" + message + "\n" + str(error) + "\n" + "-"*20 + "\n"
sys.stderr.write(message)
raise error | [
"def",
"load_json_path",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"handle",
":",
"try",
":",
"return",
"json",
".",
"load",
"(",
"handle",
",",
"object_pairs_hook",
"=",
"collections",
".",
"OrderedDict",
")",
"except",
"ValueError",
"as",
"error",
":",
"message",
"=",
"\"Could not decode JSON file '%s'.\"",
"%",
"path",
"message",
"=",
"\"-\"",
"*",
"20",
"+",
"\"\\n\"",
"+",
"message",
"+",
"\"\\n\"",
"+",
"str",
"(",
"error",
")",
"+",
"\"\\n\"",
"+",
"\"-\"",
"*",
"20",
"+",
"\"\\n\"",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
")",
"raise",
"error"
] | Load a file with the json module, but report errors better if it
fails. And have it ordered too ! | [
"Load",
"a",
"file",
"with",
"the",
"json",
"module",
"but",
"report",
"errors",
"better",
"if",
"it",
"fails",
".",
"And",
"have",
"it",
"ordered",
"too",
"!"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L390-L399 |
xapple/plumbing | plumbing/common.py | md5sum | def md5sum(file_path, blocksize=65536):
"""Compute the md5 of a file. Pretty fast."""
md5 = hashlib.md5()
with open(file_path, "rb") as f:
for block in iter(lambda: f.read(blocksize), ""):
md5.update(block)
return md5.hexdigest() | python | def md5sum(file_path, blocksize=65536):
"""Compute the md5 of a file. Pretty fast."""
md5 = hashlib.md5()
with open(file_path, "rb") as f:
for block in iter(lambda: f.read(blocksize), ""):
md5.update(block)
return md5.hexdigest() | [
"def",
"md5sum",
"(",
"file_path",
",",
"blocksize",
"=",
"65536",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"file_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"block",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"blocksize",
")",
",",
"\"\"",
")",
":",
"md5",
".",
"update",
"(",
"block",
")",
"return",
"md5",
".",
"hexdigest",
"(",
")"
] | Compute the md5 of a file. Pretty fast. | [
"Compute",
"the",
"md5",
"of",
"a",
"file",
".",
"Pretty",
"fast",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L408-L414 |
xapple/plumbing | plumbing/common.py | download_from_url | def download_from_url(source, destination, progress=False, uncompress=False):
"""Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory"""
# Modules #
from tqdm import tqdm
import requests
from autopaths.file_path import FilePath
# Check destination exists #
destination = FilePath(destination)
destination.directory.create_if_not_exists()
# Over HTTP #
response = requests.get(source, stream=True)
total_size = int(response.headers.get('content-length'))
block_size = int(total_size/1024)
# Do it #
with open(destination, "wb") as handle:
if progress:
for data in tqdm(response.iter_content(chunk_size=block_size), total=1024): handle.write(data)
else:
for data in response.iter_content(chunk_size=block_size): handle.write(data)
# Uncompress #
if uncompress:
with open(destination) as f: header = f.read(4)
if header == "PK\x03\x04": unzip(destination, inplace=True)
# Add other compression formats here
# Return #
return destination | python | def download_from_url(source, destination, progress=False, uncompress=False):
"""Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory"""
# Modules #
from tqdm import tqdm
import requests
from autopaths.file_path import FilePath
# Check destination exists #
destination = FilePath(destination)
destination.directory.create_if_not_exists()
# Over HTTP #
response = requests.get(source, stream=True)
total_size = int(response.headers.get('content-length'))
block_size = int(total_size/1024)
# Do it #
with open(destination, "wb") as handle:
if progress:
for data in tqdm(response.iter_content(chunk_size=block_size), total=1024): handle.write(data)
else:
for data in response.iter_content(chunk_size=block_size): handle.write(data)
# Uncompress #
if uncompress:
with open(destination) as f: header = f.read(4)
if header == "PK\x03\x04": unzip(destination, inplace=True)
# Add other compression formats here
# Return #
return destination | [
"def",
"download_from_url",
"(",
"source",
",",
"destination",
",",
"progress",
"=",
"False",
",",
"uncompress",
"=",
"False",
")",
":",
"# Modules #",
"from",
"tqdm",
"import",
"tqdm",
"import",
"requests",
"from",
"autopaths",
".",
"file_path",
"import",
"FilePath",
"# Check destination exists #",
"destination",
"=",
"FilePath",
"(",
"destination",
")",
"destination",
".",
"directory",
".",
"create_if_not_exists",
"(",
")",
"# Over HTTP #",
"response",
"=",
"requests",
".",
"get",
"(",
"source",
",",
"stream",
"=",
"True",
")",
"total_size",
"=",
"int",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'content-length'",
")",
")",
"block_size",
"=",
"int",
"(",
"total_size",
"/",
"1024",
")",
"# Do it #",
"with",
"open",
"(",
"destination",
",",
"\"wb\"",
")",
"as",
"handle",
":",
"if",
"progress",
":",
"for",
"data",
"in",
"tqdm",
"(",
"response",
".",
"iter_content",
"(",
"chunk_size",
"=",
"block_size",
")",
",",
"total",
"=",
"1024",
")",
":",
"handle",
".",
"write",
"(",
"data",
")",
"else",
":",
"for",
"data",
"in",
"response",
".",
"iter_content",
"(",
"chunk_size",
"=",
"block_size",
")",
":",
"handle",
".",
"write",
"(",
"data",
")",
"# Uncompress #",
"if",
"uncompress",
":",
"with",
"open",
"(",
"destination",
")",
"as",
"f",
":",
"header",
"=",
"f",
".",
"read",
"(",
"4",
")",
"if",
"header",
"==",
"\"PK\\x03\\x04\"",
":",
"unzip",
"(",
"destination",
",",
"inplace",
"=",
"True",
")",
"# Add other compression formats here",
"# Return #",
"return",
"destination"
] | Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory | [
"Download",
"a",
"file",
"from",
"an",
"URL",
"and",
"place",
"it",
"somewhere",
".",
"Like",
"wget",
".",
"Uses",
"requests",
"and",
"tqdm",
"to",
"display",
"progress",
"if",
"you",
"want",
".",
"By",
"default",
"it",
"will",
"uncompress",
"files",
".",
"#TODO",
":",
"handle",
"case",
"where",
"destination",
"is",
"a",
"directory"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L417-L445 |
xapple/plumbing | plumbing/common.py | reversed_lines | def reversed_lines(path):
"""Generate the lines of file in reverse order."""
with open(path, 'r') as handle:
part = ''
for block in reversed_blocks(handle):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ''
part += c
if part: yield part[::-1] | python | def reversed_lines(path):
"""Generate the lines of file in reverse order."""
with open(path, 'r') as handle:
part = ''
for block in reversed_blocks(handle):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ''
part += c
if part: yield part[::-1] | [
"def",
"reversed_lines",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"handle",
":",
"part",
"=",
"''",
"for",
"block",
"in",
"reversed_blocks",
"(",
"handle",
")",
":",
"for",
"c",
"in",
"reversed",
"(",
"block",
")",
":",
"if",
"c",
"==",
"'\\n'",
"and",
"part",
":",
"yield",
"part",
"[",
":",
":",
"-",
"1",
"]",
"part",
"=",
"''",
"part",
"+=",
"c",
"if",
"part",
":",
"yield",
"part",
"[",
":",
":",
"-",
"1",
"]"
] | Generate the lines of file in reverse order. | [
"Generate",
"the",
"lines",
"of",
"file",
"in",
"reverse",
"order",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L448-L458 |
xapple/plumbing | plumbing/common.py | reversed_blocks | def reversed_blocks(handle, blocksize=4096):
"""Generate blocks of file's contents in reverse order."""
handle.seek(0, os.SEEK_END)
here = handle.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
handle.seek(here, os.SEEK_SET)
yield handle.read(delta) | python | def reversed_blocks(handle, blocksize=4096):
"""Generate blocks of file's contents in reverse order."""
handle.seek(0, os.SEEK_END)
here = handle.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
handle.seek(here, os.SEEK_SET)
yield handle.read(delta) | [
"def",
"reversed_blocks",
"(",
"handle",
",",
"blocksize",
"=",
"4096",
")",
":",
"handle",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_END",
")",
"here",
"=",
"handle",
".",
"tell",
"(",
")",
"while",
"0",
"<",
"here",
":",
"delta",
"=",
"min",
"(",
"blocksize",
",",
"here",
")",
"here",
"-=",
"delta",
"handle",
".",
"seek",
"(",
"here",
",",
"os",
".",
"SEEK_SET",
")",
"yield",
"handle",
".",
"read",
"(",
"delta",
")"
] | Generate blocks of file's contents in reverse order. | [
"Generate",
"blocks",
"of",
"file",
"s",
"contents",
"in",
"reverse",
"order",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L461-L469 |
xapple/plumbing | plumbing/common.py | prepend_to_file | def prepend_to_file(path, data, bufsize=1<<15):
"""TODO:
* Add a random string to the backup file.
* Restore permissions after copy.
"""
# Backup the file #
backupname = path + os.extsep + 'bak'
# Remove previous backup if it exists #
try: os.unlink(backupname)
except OSError: pass
os.rename(path, backupname)
# Open input/output files, note: outputfile's permissions lost #
with open(backupname) as inputfile:
with open(path, 'w') as outputfile:
outputfile.write(data)
buf = inputfile.read(bufsize)
while buf:
outputfile.write(buf)
buf = inputfile.read(bufsize)
# Remove backup on success #
os.remove(backupname) | python | def prepend_to_file(path, data, bufsize=1<<15):
"""TODO:
* Add a random string to the backup file.
* Restore permissions after copy.
"""
# Backup the file #
backupname = path + os.extsep + 'bak'
# Remove previous backup if it exists #
try: os.unlink(backupname)
except OSError: pass
os.rename(path, backupname)
# Open input/output files, note: outputfile's permissions lost #
with open(backupname) as inputfile:
with open(path, 'w') as outputfile:
outputfile.write(data)
buf = inputfile.read(bufsize)
while buf:
outputfile.write(buf)
buf = inputfile.read(bufsize)
# Remove backup on success #
os.remove(backupname) | [
"def",
"prepend_to_file",
"(",
"path",
",",
"data",
",",
"bufsize",
"=",
"1",
"<<",
"15",
")",
":",
"# Backup the file #",
"backupname",
"=",
"path",
"+",
"os",
".",
"extsep",
"+",
"'bak'",
"# Remove previous backup if it exists #",
"try",
":",
"os",
".",
"unlink",
"(",
"backupname",
")",
"except",
"OSError",
":",
"pass",
"os",
".",
"rename",
"(",
"path",
",",
"backupname",
")",
"# Open input/output files, note: outputfile's permissions lost #",
"with",
"open",
"(",
"backupname",
")",
"as",
"inputfile",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"outputfile",
":",
"outputfile",
".",
"write",
"(",
"data",
")",
"buf",
"=",
"inputfile",
".",
"read",
"(",
"bufsize",
")",
"while",
"buf",
":",
"outputfile",
".",
"write",
"(",
"buf",
")",
"buf",
"=",
"inputfile",
".",
"read",
"(",
"bufsize",
")",
"# Remove backup on success #",
"os",
".",
"remove",
"(",
"backupname",
")"
] | TODO:
* Add a random string to the backup file.
* Restore permissions after copy. | [
"TODO",
":",
"*",
"Add",
"a",
"random",
"string",
"to",
"the",
"backup",
"file",
".",
"*",
"Restore",
"permissions",
"after",
"copy",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L472-L492 |
xapple/plumbing | plumbing/common.py | which | def which(cmd, safe=False):
"""https://github.com/jc0n/python-which"""
from autopaths.file_path import FilePath
def is_executable(path):
return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
path, name = os.path.split(cmd)
if path:
if is_executable(cmd): return FilePath(cmd)
else:
for path in os.environ['PATH'].split(os.pathsep):
candidate = os.path.join(path, cmd)
if is_executable(candidate): return FilePath(candidate)
if not safe: raise Exception('which failed to locate a proper command path "%s"' % cmd) | python | def which(cmd, safe=False):
"""https://github.com/jc0n/python-which"""
from autopaths.file_path import FilePath
def is_executable(path):
return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
path, name = os.path.split(cmd)
if path:
if is_executable(cmd): return FilePath(cmd)
else:
for path in os.environ['PATH'].split(os.pathsep):
candidate = os.path.join(path, cmd)
if is_executable(candidate): return FilePath(candidate)
if not safe: raise Exception('which failed to locate a proper command path "%s"' % cmd) | [
"def",
"which",
"(",
"cmd",
",",
"safe",
"=",
"False",
")",
":",
"from",
"autopaths",
".",
"file_path",
"import",
"FilePath",
"def",
"is_executable",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"X_OK",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"path",
",",
"name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"cmd",
")",
"if",
"path",
":",
"if",
"is_executable",
"(",
"cmd",
")",
":",
"return",
"FilePath",
"(",
"cmd",
")",
"else",
":",
"for",
"path",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"candidate",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"cmd",
")",
"if",
"is_executable",
"(",
"candidate",
")",
":",
"return",
"FilePath",
"(",
"candidate",
")",
"if",
"not",
"safe",
":",
"raise",
"Exception",
"(",
"'which failed to locate a proper command path \"%s\"'",
"%",
"cmd",
")"
] | https://github.com/jc0n/python-which | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"jc0n",
"/",
"python",
"-",
"which"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L529-L541 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | css_tag | def css_tag(parser, token):
"""
Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
{% css "myfile.css" "screen, projection"%}
"""
path = get_path_from_tokens(token)
tokens = token.split_contents()
if len(tokens) > 2:
# Get the media types from the tag call provided by the user.
media_type = tokens[2][1:-1]
else:
# Default values.
media_type = "screen, projection"
return CssTagNode(path, media_type=media_type) | python | def css_tag(parser, token):
"""
Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
{% css "myfile.css" "screen, projection"%}
"""
path = get_path_from_tokens(token)
tokens = token.split_contents()
if len(tokens) > 2:
# Get the media types from the tag call provided by the user.
media_type = tokens[2][1:-1]
else:
# Default values.
media_type = "screen, projection"
return CssTagNode(path, media_type=media_type) | [
"def",
"css_tag",
"(",
"parser",
",",
"token",
")",
":",
"path",
"=",
"get_path_from_tokens",
"(",
"token",
")",
"tokens",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"2",
":",
"# Get the media types from the tag call provided by the user.",
"media_type",
"=",
"tokens",
"[",
"2",
"]",
"[",
"1",
":",
"-",
"1",
"]",
"else",
":",
"# Default values.",
"media_type",
"=",
"\"screen, projection\"",
"return",
"CssTagNode",
"(",
"path",
",",
"media_type",
"=",
"media_type",
")"
] | Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
{% css "myfile.css" "screen, projection"%} | [
"Renders",
"a",
"tag",
"to",
"include",
"the",
"stylesheet",
".",
"It",
"takes",
"an",
"optional",
"second",
"parameter",
"for",
"the",
"media",
"attribute",
";",
"the",
"default",
"media",
"is",
"screen",
"projector",
".",
"Usage",
"::"
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L154-L178 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | css_print_tag | def css_print_tag(parser, token):
"""
Shortcut to render CSS as a print stylesheet.
Usage::
{% css_print "myfile.css" %}
Which is equivalent to
{% css "myfile.css" "print" %}
"""
path = get_path_from_tokens(token)
# Hard wired media type, since this is for media type of 'print'.
media_type = "print"
return CssTagNode(path, media_type=media_type) | python | def css_print_tag(parser, token):
"""
Shortcut to render CSS as a print stylesheet.
Usage::
{% css_print "myfile.css" %}
Which is equivalent to
{% css "myfile.css" "print" %}
"""
path = get_path_from_tokens(token)
# Hard wired media type, since this is for media type of 'print'.
media_type = "print"
return CssTagNode(path, media_type=media_type) | [
"def",
"css_print_tag",
"(",
"parser",
",",
"token",
")",
":",
"path",
"=",
"get_path_from_tokens",
"(",
"token",
")",
"# Hard wired media type, since this is for media type of 'print'.",
"media_type",
"=",
"\"print\"",
"return",
"CssTagNode",
"(",
"path",
",",
"media_type",
"=",
"media_type",
")"
] | Shortcut to render CSS as a print stylesheet.
Usage::
{% css_print "myfile.css" %}
Which is equivalent to
{% css "myfile.css" "print" %} | [
"Shortcut",
"to",
"render",
"CSS",
"as",
"a",
"print",
"stylesheet",
".",
"Usage",
"::",
"{",
"%",
"css_print",
"myfile",
".",
"css",
"%",
"}",
"Which",
"is",
"equivalent",
"to",
"{",
"%",
"css",
"myfile",
".",
"css",
"print",
"%",
"}"
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L181-L197 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | BaseTagNode.supports_gzip | def supports_gzip(self, context):
"""
Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be served the original media.
"""
if 'request' in context and client.supports_gzip():
enc = context['request'].META.get('HTTP_ACCEPT_ENCODING', '')
return 'gzip' in enc and msettings['SERVE_REMOTE']
return False | python | def supports_gzip(self, context):
"""
Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be served the original media.
"""
if 'request' in context and client.supports_gzip():
enc = context['request'].META.get('HTTP_ACCEPT_ENCODING', '')
return 'gzip' in enc and msettings['SERVE_REMOTE']
return False | [
"def",
"supports_gzip",
"(",
"self",
",",
"context",
")",
":",
"if",
"'request'",
"in",
"context",
"and",
"client",
".",
"supports_gzip",
"(",
")",
":",
"enc",
"=",
"context",
"[",
"'request'",
"]",
".",
"META",
".",
"get",
"(",
"'HTTP_ACCEPT_ENCODING'",
",",
"''",
")",
"return",
"'gzip'",
"in",
"enc",
"and",
"msettings",
"[",
"'SERVE_REMOTE'",
"]",
"return",
"False"
] | Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be served the original media. | [
"Looks",
"at",
"the",
"RequestContext",
"object",
"and",
"determines",
"if",
"the",
"client",
"supports",
"gzip",
"encoded",
"content",
".",
"If",
"the",
"client",
"does",
"we",
"will",
"send",
"them",
"to",
"the",
"gzipped",
"version",
"of",
"files",
"that",
"are",
"allowed",
"to",
"be",
"compressed",
".",
"Clients",
"without",
"gzip",
"support",
"will",
"be",
"served",
"the",
"original",
"media",
"."
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L32-L42 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | BaseTagNode.get_media_url | def get_media_url(self, context):
"""
Checks to see whether to use the normal or the secure media source,
depending on whether the current page view is being sent over SSL.
The USE_SSL setting can be used to force HTTPS (True) or HTTP (False).
NOTE: Not all backends implement SSL media. In this case, they'll just
return an unencrypted URL.
"""
use_ssl = msettings['USE_SSL']
is_secure = use_ssl if use_ssl is not None else self.is_secure(context)
return client.media_url(with_ssl=True) if is_secure else client.media_url() | python | def get_media_url(self, context):
"""
Checks to see whether to use the normal or the secure media source,
depending on whether the current page view is being sent over SSL.
The USE_SSL setting can be used to force HTTPS (True) or HTTP (False).
NOTE: Not all backends implement SSL media. In this case, they'll just
return an unencrypted URL.
"""
use_ssl = msettings['USE_SSL']
is_secure = use_ssl if use_ssl is not None else self.is_secure(context)
return client.media_url(with_ssl=True) if is_secure else client.media_url() | [
"def",
"get_media_url",
"(",
"self",
",",
"context",
")",
":",
"use_ssl",
"=",
"msettings",
"[",
"'USE_SSL'",
"]",
"is_secure",
"=",
"use_ssl",
"if",
"use_ssl",
"is",
"not",
"None",
"else",
"self",
".",
"is_secure",
"(",
"context",
")",
"return",
"client",
".",
"media_url",
"(",
"with_ssl",
"=",
"True",
")",
"if",
"is_secure",
"else",
"client",
".",
"media_url",
"(",
")"
] | Checks to see whether to use the normal or the secure media source,
depending on whether the current page view is being sent over SSL.
The USE_SSL setting can be used to force HTTPS (True) or HTTP (False).
NOTE: Not all backends implement SSL media. In this case, they'll just
return an unencrypted URL. | [
"Checks",
"to",
"see",
"whether",
"to",
"use",
"the",
"normal",
"or",
"the",
"secure",
"media",
"source",
"depending",
"on",
"whether",
"the",
"current",
"page",
"view",
"is",
"being",
"sent",
"over",
"SSL",
".",
"The",
"USE_SSL",
"setting",
"can",
"be",
"used",
"to",
"force",
"HTTPS",
"(",
"True",
")",
"or",
"HTTP",
"(",
"False",
")",
".",
"NOTE",
":",
"Not",
"all",
"backends",
"implement",
"SSL",
"media",
".",
"In",
"this",
"case",
"they",
"ll",
"just",
"return",
"an",
"unencrypted",
"URL",
"."
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L44-L55 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | BaseTagNode.mkpath | def mkpath(self, url, path, filename=None, gzip=False):
"""
Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
filename: (str) The file name to serve.
gzip: (bool) True if client should receive *.gzt version of file.
"""
if path:
url = "%s/%s" % (url.rstrip('/'), path.strip('/'))
if filename:
url = "%s/%s" % (url, filename.lstrip('/'))
content_type = mimetypes.guess_type(url)[0]
if gzip and content_type in mediasync.TYPES_TO_COMPRESS:
url = "%s.gzt" % url
cb = msettings['CACHE_BUSTER']
if cb:
# Cache busters help tell the client to re-download the file after
# a change. This can either be a callable or a constant defined
# in settings.py.
cb_val = cb(url) if callable(cb) else cb
url = "%s?%s" % (url, cb_val)
return msettings['URL_PROCESSOR'](url) | python | def mkpath(self, url, path, filename=None, gzip=False):
"""
Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
filename: (str) The file name to serve.
gzip: (bool) True if client should receive *.gzt version of file.
"""
if path:
url = "%s/%s" % (url.rstrip('/'), path.strip('/'))
if filename:
url = "%s/%s" % (url, filename.lstrip('/'))
content_type = mimetypes.guess_type(url)[0]
if gzip and content_type in mediasync.TYPES_TO_COMPRESS:
url = "%s.gzt" % url
cb = msettings['CACHE_BUSTER']
if cb:
# Cache busters help tell the client to re-download the file after
# a change. This can either be a callable or a constant defined
# in settings.py.
cb_val = cb(url) if callable(cb) else cb
url = "%s?%s" % (url, cb_val)
return msettings['URL_PROCESSOR'](url) | [
"def",
"mkpath",
"(",
"self",
",",
"url",
",",
"path",
",",
"filename",
"=",
"None",
",",
"gzip",
"=",
"False",
")",
":",
"if",
"path",
":",
"url",
"=",
"\"%s/%s\"",
"%",
"(",
"url",
".",
"rstrip",
"(",
"'/'",
")",
",",
"path",
".",
"strip",
"(",
"'/'",
")",
")",
"if",
"filename",
":",
"url",
"=",
"\"%s/%s\"",
"%",
"(",
"url",
",",
"filename",
".",
"lstrip",
"(",
"'/'",
")",
")",
"content_type",
"=",
"mimetypes",
".",
"guess_type",
"(",
"url",
")",
"[",
"0",
"]",
"if",
"gzip",
"and",
"content_type",
"in",
"mediasync",
".",
"TYPES_TO_COMPRESS",
":",
"url",
"=",
"\"%s.gzt\"",
"%",
"url",
"cb",
"=",
"msettings",
"[",
"'CACHE_BUSTER'",
"]",
"if",
"cb",
":",
"# Cache busters help tell the client to re-download the file after",
"# a change. This can either be a callable or a constant defined",
"# in settings.py.",
"cb_val",
"=",
"cb",
"(",
"url",
")",
"if",
"callable",
"(",
"cb",
")",
"else",
"cb",
"url",
"=",
"\"%s?%s\"",
"%",
"(",
"url",
",",
"cb_val",
")",
"return",
"msettings",
"[",
"'URL_PROCESSOR'",
"]",
"(",
"url",
")"
] | Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
filename: (str) The file name to serve.
gzip: (bool) True if client should receive *.gzt version of file. | [
"Assembles",
"various",
"components",
"to",
"form",
"a",
"complete",
"resource",
"URL",
".",
"args",
":",
"url",
":",
"(",
"str",
")",
"A",
"base",
"media",
"URL",
".",
"path",
":",
"(",
"str",
")",
"The",
"path",
"on",
"the",
"host",
"(",
"specified",
"in",
"url",
")",
"leading",
"up",
"to",
"the",
"file",
".",
"filename",
":",
"(",
"str",
")",
"The",
"file",
"name",
"to",
"serve",
".",
"gzip",
":",
"(",
"bool",
")",
"True",
"if",
"client",
"should",
"receive",
"*",
".",
"gzt",
"version",
"of",
"file",
"."
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L57-L86 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | CssTagNode.linktag | def linktag(self, url, path, filename, media, context):
"""
Renders a <link> tag for the stylesheet(s).
"""
if msettings['DOCTYPE'] == 'xhtml':
markup = """<link rel="stylesheet" href="%s" type="text/css" media="%s" />"""
elif msettings['DOCTYPE'] == 'html5':
markup = """<link rel="stylesheet" href="%s" media="%s">"""
else:
markup = """<link rel="stylesheet" href="%s" type="text/css" media="%s">"""
return markup % (self.mkpath(url, path, filename, gzip=self.supports_gzip(context)), media) | python | def linktag(self, url, path, filename, media, context):
"""
Renders a <link> tag for the stylesheet(s).
"""
if msettings['DOCTYPE'] == 'xhtml':
markup = """<link rel="stylesheet" href="%s" type="text/css" media="%s" />"""
elif msettings['DOCTYPE'] == 'html5':
markup = """<link rel="stylesheet" href="%s" media="%s">"""
else:
markup = """<link rel="stylesheet" href="%s" type="text/css" media="%s">"""
return markup % (self.mkpath(url, path, filename, gzip=self.supports_gzip(context)), media) | [
"def",
"linktag",
"(",
"self",
",",
"url",
",",
"path",
",",
"filename",
",",
"media",
",",
"context",
")",
":",
"if",
"msettings",
"[",
"'DOCTYPE'",
"]",
"==",
"'xhtml'",
":",
"markup",
"=",
"\"\"\"<link rel=\"stylesheet\" href=\"%s\" type=\"text/css\" media=\"%s\" />\"\"\"",
"elif",
"msettings",
"[",
"'DOCTYPE'",
"]",
"==",
"'html5'",
":",
"markup",
"=",
"\"\"\"<link rel=\"stylesheet\" href=\"%s\" media=\"%s\">\"\"\"",
"else",
":",
"markup",
"=",
"\"\"\"<link rel=\"stylesheet\" href=\"%s\" type=\"text/css\" media=\"%s\">\"\"\"",
"return",
"markup",
"%",
"(",
"self",
".",
"mkpath",
"(",
"url",
",",
"path",
",",
"filename",
",",
"gzip",
"=",
"self",
".",
"supports_gzip",
"(",
"context",
")",
")",
",",
"media",
")"
] | Renders a <link> tag for the stylesheet(s). | [
"Renders",
"a",
"<link",
">",
"tag",
"for",
"the",
"stylesheet",
"(",
"s",
")",
"."
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L230-L240 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | JsTagNode.scripttag | def scripttag(self, url, path, filename, context):
"""
Renders a <script> tag for the JS file(s).
"""
if msettings['DOCTYPE'] == 'html5':
markup = """<script src="%s"></script>"""
else:
markup = """<script type="text/javascript" charset="utf-8" src="%s"></script>"""
return markup % self.mkpath(url, path, filename, gzip=self.supports_gzip(context)) | python | def scripttag(self, url, path, filename, context):
"""
Renders a <script> tag for the JS file(s).
"""
if msettings['DOCTYPE'] == 'html5':
markup = """<script src="%s"></script>"""
else:
markup = """<script type="text/javascript" charset="utf-8" src="%s"></script>"""
return markup % self.mkpath(url, path, filename, gzip=self.supports_gzip(context)) | [
"def",
"scripttag",
"(",
"self",
",",
"url",
",",
"path",
",",
"filename",
",",
"context",
")",
":",
"if",
"msettings",
"[",
"'DOCTYPE'",
"]",
"==",
"'html5'",
":",
"markup",
"=",
"\"\"\"<script src=\"%s\"></script>\"\"\"",
"else",
":",
"markup",
"=",
"\"\"\"<script type=\"text/javascript\" charset=\"utf-8\" src=\"%s\"></script>\"\"\"",
"return",
"markup",
"%",
"self",
".",
"mkpath",
"(",
"url",
",",
"path",
",",
"filename",
",",
"gzip",
"=",
"self",
".",
"supports_gzip",
"(",
"context",
")",
")"
] | Renders a <script> tag for the JS file(s). | [
"Renders",
"a",
"<script",
">",
"tag",
"for",
"the",
"JS",
"file",
"(",
"s",
")",
"."
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L284-L292 |
sprockets/sprockets.http | sprockets/http/app.py | wrap_application | def wrap_application(application, before_run, on_start, shutdown):
"""
Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
:param list|NoneType on_start: optional list of callbacks to
register with :meth:`~tornado.IOLoop.spawn_callback`.
:param list|NoneType shutdown: optional list of callbacks to
invoke before stopping the IOLoop
:return: a wrapped application object
:rtype: sprockets.http.app.Application
"""
before_run = [] if before_run is None else before_run
on_start = [] if on_start is None else on_start
shutdown = [] if shutdown is None else shutdown
if not isinstance(application, Application):
application = _ApplicationAdapter(application)
application.before_run_callbacks.extend(before_run)
application.on_start_callbacks.extend(on_start)
application.on_shutdown_callbacks.extend(shutdown)
return application | python | def wrap_application(application, before_run, on_start, shutdown):
"""
Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
:param list|NoneType on_start: optional list of callbacks to
register with :meth:`~tornado.IOLoop.spawn_callback`.
:param list|NoneType shutdown: optional list of callbacks to
invoke before stopping the IOLoop
:return: a wrapped application object
:rtype: sprockets.http.app.Application
"""
before_run = [] if before_run is None else before_run
on_start = [] if on_start is None else on_start
shutdown = [] if shutdown is None else shutdown
if not isinstance(application, Application):
application = _ApplicationAdapter(application)
application.before_run_callbacks.extend(before_run)
application.on_start_callbacks.extend(on_start)
application.on_shutdown_callbacks.extend(shutdown)
return application | [
"def",
"wrap_application",
"(",
"application",
",",
"before_run",
",",
"on_start",
",",
"shutdown",
")",
":",
"before_run",
"=",
"[",
"]",
"if",
"before_run",
"is",
"None",
"else",
"before_run",
"on_start",
"=",
"[",
"]",
"if",
"on_start",
"is",
"None",
"else",
"on_start",
"shutdown",
"=",
"[",
"]",
"if",
"shutdown",
"is",
"None",
"else",
"shutdown",
"if",
"not",
"isinstance",
"(",
"application",
",",
"Application",
")",
":",
"application",
"=",
"_ApplicationAdapter",
"(",
"application",
")",
"application",
".",
"before_run_callbacks",
".",
"extend",
"(",
"before_run",
")",
"application",
".",
"on_start_callbacks",
".",
"extend",
"(",
"on_start",
")",
"application",
".",
"on_shutdown_callbacks",
".",
"extend",
"(",
"shutdown",
")",
"return",
"application"
] | Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
:param list|NoneType on_start: optional list of callbacks to
register with :meth:`~tornado.IOLoop.spawn_callback`.
:param list|NoneType shutdown: optional list of callbacks to
invoke before stopping the IOLoop
:return: a wrapped application object
:rtype: sprockets.http.app.Application | [
"Wrap",
"a",
"tornado",
"application",
"in",
"a",
"callback",
"-",
"aware",
"wrapper",
"."
] | train | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/app.py#L229-L257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.