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
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
pearu/pyvtk
pyvtk/common.py
Common.get_3_tuple_list
def get_3_tuple_list(self,obj,default=None): """Return list of 3-tuples from sequence of a sequence, sequence - it is mapped to sequence of 3-sequences if possible number """ if is_sequence2(obj): return [self.get_3_tuple(o,default) for o in obj] elif ...
python
def get_3_tuple_list(self,obj,default=None): """Return list of 3-tuples from sequence of a sequence, sequence - it is mapped to sequence of 3-sequences if possible number """ if is_sequence2(obj): return [self.get_3_tuple(o,default) for o in obj] elif ...
[ "def", "get_3_tuple_list", "(", "self", ",", "obj", ",", "default", "=", "None", ")", ":", "if", "is_sequence2", "(", "obj", ")", ":", "return", "[", "self", ".", "get_3_tuple", "(", "o", ",", "default", ")", "for", "o", "in", "obj", "]", "elif", "...
Return list of 3-tuples from sequence of a sequence, sequence - it is mapped to sequence of 3-sequences if possible number
[ "Return", "list", "of", "3", "-", "tuples", "from", "sequence", "of", "a", "sequence", "sequence", "-", "it", "is", "mapped", "to", "sequence", "of", "3", "-", "sequences", "if", "possible", "number" ]
train
https://github.com/pearu/pyvtk/blob/b004ec3c03299a2d75338a4be93dd29f076b70ab/pyvtk/common.py#L196-L207
pearu/pyvtk
pyvtk/common.py
Common.get_3_3_tuple
def get_3_3_tuple(self,obj,default=None): """Return tuple of 3-tuples """ if is_sequence2(obj): ret = [] for i in range(3): if i<len(obj): ret.append(self.get_3_tuple(obj[i],default)) else: ret.append...
python
def get_3_3_tuple(self,obj,default=None): """Return tuple of 3-tuples """ if is_sequence2(obj): ret = [] for i in range(3): if i<len(obj): ret.append(self.get_3_tuple(obj[i],default)) else: ret.append...
[ "def", "get_3_3_tuple", "(", "self", ",", "obj", ",", "default", "=", "None", ")", ":", "if", "is_sequence2", "(", "obj", ")", ":", "ret", "=", "[", "]", "for", "i", "in", "range", "(", "3", ")", ":", "if", "i", "<", "len", "(", "obj", ")", "...
Return tuple of 3-tuples
[ "Return", "tuple", "of", "3", "-", "tuples" ]
train
https://github.com/pearu/pyvtk/blob/b004ec3c03299a2d75338a4be93dd29f076b70ab/pyvtk/common.py#L208-L233
pearu/pyvtk
pyvtk/common.py
Common.get_3_3_tuple_list
def get_3_3_tuple_list(self,obj,default=None): """Return list of 3x3-tuples. """ if is_sequence3(obj): return [self.get_3_3_tuple(o,default) for o in obj] return [self.get_3_3_tuple(obj,default)]
python
def get_3_3_tuple_list(self,obj,default=None): """Return list of 3x3-tuples. """ if is_sequence3(obj): return [self.get_3_3_tuple(o,default) for o in obj] return [self.get_3_3_tuple(obj,default)]
[ "def", "get_3_3_tuple_list", "(", "self", ",", "obj", ",", "default", "=", "None", ")", ":", "if", "is_sequence3", "(", "obj", ")", ":", "return", "[", "self", ".", "get_3_3_tuple", "(", "o", ",", "default", ")", "for", "o", "in", "obj", "]", "return...
Return list of 3x3-tuples.
[ "Return", "list", "of", "3x3", "-", "tuples", "." ]
train
https://github.com/pearu/pyvtk/blob/b004ec3c03299a2d75338a4be93dd29f076b70ab/pyvtk/common.py#L234-L239
Ketouem/flask-boto3
flask_boto3/__init__.py
Boto3.connect
def connect(self): """Iterate through the application configuration and instantiate the services. """ requested_services = set( svc.lower() for svc in current_app.config.get('BOTO3_SERVICES', []) ) region = current_app.config.get('BOTO3_REGION') sess_...
python
def connect(self): """Iterate through the application configuration and instantiate the services. """ requested_services = set( svc.lower() for svc in current_app.config.get('BOTO3_SERVICES', []) ) region = current_app.config.get('BOTO3_REGION') sess_...
[ "def", "connect", "(", "self", ")", ":", "requested_services", "=", "set", "(", "svc", ".", "lower", "(", ")", "for", "svc", "in", "current_app", ".", "config", ".", "get", "(", "'BOTO3_SERVICES'", ",", "[", "]", ")", ")", "region", "=", "current_app",...
Iterate through the application configuration and instantiate the services.
[ "Iterate", "through", "the", "application", "configuration", "and", "instantiate", "the", "services", "." ]
train
https://github.com/Ketouem/flask-boto3/blob/3958edc9539421c0fd4923115a1d53ab0db91ac9/flask_boto3/__init__.py#L23-L69
Ketouem/flask-boto3
flask_boto3/__init__.py
Boto3.clients
def clients(self): """ Get all clients (with and without associated resources) """ clients = {} for k, v in self.connections.items(): if hasattr(v.meta, 'client'): # has boto3 resource clients[k] = v.meta.client else: ...
python
def clients(self): """ Get all clients (with and without associated resources) """ clients = {} for k, v in self.connections.items(): if hasattr(v.meta, 'client'): # has boto3 resource clients[k] = v.meta.client else: ...
[ "def", "clients", "(", "self", ")", ":", "clients", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "connections", ".", "items", "(", ")", ":", "if", "hasattr", "(", "v", ".", "meta", ",", "'client'", ")", ":", "# has boto3 resource", "clie...
Get all clients (with and without associated resources)
[ "Get", "all", "clients", "(", "with", "and", "without", "associated", "resources", ")" ]
train
https://github.com/Ketouem/flask-boto3/blob/3958edc9539421c0fd4923115a1d53ab0db91ac9/flask_boto3/__init__.py#L85-L95
mkomitee/flask-kerberos
flask_kerberos.py
init_kerberos
def init_kerberos(app, service='HTTP', hostname=gethostname()): ''' Configure the GSSAPI service name, and validate the presence of the appropriate principal in the kerberos keytab. :param app: a flask application :type app: flask.Flask :param service: GSSAPI service name :type service: str...
python
def init_kerberos(app, service='HTTP', hostname=gethostname()): ''' Configure the GSSAPI service name, and validate the presence of the appropriate principal in the kerberos keytab. :param app: a flask application :type app: flask.Flask :param service: GSSAPI service name :type service: str...
[ "def", "init_kerberos", "(", "app", ",", "service", "=", "'HTTP'", ",", "hostname", "=", "gethostname", "(", ")", ")", ":", "global", "_SERVICE_NAME", "_SERVICE_NAME", "=", "\"%s@%s\"", "%", "(", "service", ",", "hostname", ")", "if", "'KRB5_KTNAME'", "not",...
Configure the GSSAPI service name, and validate the presence of the appropriate principal in the kerberos keytab. :param app: a flask application :type app: flask.Flask :param service: GSSAPI service name :type service: str :param hostname: hostname the service runs under :type hostname: st...
[ "Configure", "the", "GSSAPI", "service", "name", "and", "validate", "the", "presence", "of", "the", "appropriate", "principal", "in", "the", "kerberos", "keytab", "." ]
train
https://github.com/mkomitee/flask-kerberos/blob/f8f811d1fa3c44cb71b6ca1bef9b7b2b72dd22b0/flask_kerberos.py#L14-L37
telminov/sw-django-utils
djutils/date_utils.py
date_to_timestamp
def date_to_timestamp(date): """ date to unix timestamp in milliseconds """ date_tuple = date.timetuple() timestamp = calendar.timegm(date_tuple) * 1000 return timestamp
python
def date_to_timestamp(date): """ date to unix timestamp in milliseconds """ date_tuple = date.timetuple() timestamp = calendar.timegm(date_tuple) * 1000 return timestamp
[ "def", "date_to_timestamp", "(", "date", ")", ":", "date_tuple", "=", "date", ".", "timetuple", "(", ")", "timestamp", "=", "calendar", ".", "timegm", "(", "date_tuple", ")", "*", "1000", "return", "timestamp" ]
date to unix timestamp in milliseconds
[ "date", "to", "unix", "timestamp", "in", "milliseconds" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/date_utils.py#L39-L45
telminov/sw-django-utils
djutils/date_utils.py
random_date
def random_date(dt_from, dt_to): """ This function will return a random datetime between two datetime objects. :param start: :param end: """ delta = dt_to - dt_from int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = randrange(int_delta) return dt_from + datetime....
python
def random_date(dt_from, dt_to): """ This function will return a random datetime between two datetime objects. :param start: :param end: """ delta = dt_to - dt_from int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = randrange(int_delta) return dt_from + datetime....
[ "def", "random_date", "(", "dt_from", ",", "dt_to", ")", ":", "delta", "=", "dt_to", "-", "dt_from", "int_delta", "=", "(", "delta", ".", "days", "*", "24", "*", "60", "*", "60", ")", "+", "delta", ".", "seconds", "random_second", "=", "randrange", "...
This function will return a random datetime between two datetime objects. :param start: :param end:
[ "This", "function", "will", "return", "a", "random", "datetime", "between", "two", "datetime", "objects", ".", ":", "param", "start", ":", ":", "param", "end", ":" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/date_utils.py#L48-L57
telminov/sw-django-utils
djutils/json_utils.py
object_to_json
def object_to_json(obj, indent=2): """ transform object to json """ instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder) return instance_json
python
def object_to_json(obj, indent=2): """ transform object to json """ instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder) return instance_json
[ "def", "object_to_json", "(", "obj", ",", "indent", "=", "2", ")", ":", "instance_json", "=", "json", ".", "dumps", "(", "obj", ",", "indent", "=", "indent", ",", "ensure_ascii", "=", "False", ",", "cls", "=", "DjangoJSONEncoder", ")", "return", "instanc...
transform object to json
[ "transform", "object", "to", "json" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/json_utils.py#L9-L14
telminov/sw-django-utils
djutils/json_utils.py
qs_to_json
def qs_to_json(qs, fields=None): """ transform QuerySet to json """ if not fields : fields = [f.name for f in qs.model._meta.fields] # сформируем список для сериализации objects = [] for value_dict in qs.values(*fields): # сохраним порядок полей, как определено в моделе ...
python
def qs_to_json(qs, fields=None): """ transform QuerySet to json """ if not fields : fields = [f.name for f in qs.model._meta.fields] # сформируем список для сериализации objects = [] for value_dict in qs.values(*fields): # сохраним порядок полей, как определено в моделе ...
[ "def", "qs_to_json", "(", "qs", ",", "fields", "=", "None", ")", ":", "if", "not", "fields", ":", "fields", "=", "[", "f", ".", "name", "for", "f", "in", "qs", ".", "model", ".", "_meta", ".", "fields", "]", "# сформируем список для сериализации", "obj...
transform QuerySet to json
[ "transform", "QuerySet", "to", "json" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/json_utils.py#L25-L44
telminov/sw-django-utils
djutils/json_utils.py
mongoqs_to_json
def mongoqs_to_json(qs, fields=None): """ transform mongoengine.QuerySet to json """ l = list(qs.as_pymongo()) for element in l: element.pop('_cls') # use DjangoJSONEncoder for transform date data type to datetime json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSO...
python
def mongoqs_to_json(qs, fields=None): """ transform mongoengine.QuerySet to json """ l = list(qs.as_pymongo()) for element in l: element.pop('_cls') # use DjangoJSONEncoder for transform date data type to datetime json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSO...
[ "def", "mongoqs_to_json", "(", "qs", ",", "fields", "=", "None", ")", ":", "l", "=", "list", "(", "qs", ".", "as_pymongo", "(", ")", ")", "for", "element", "in", "l", ":", "element", ".", "pop", "(", "'_cls'", ")", "# use DjangoJSONEncoder for transform ...
transform mongoengine.QuerySet to json
[ "transform", "mongoengine", ".", "QuerySet", "to", "json" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/json_utils.py#L47-L59
telminov/sw-django-utils
djutils/views/helpers.py
url_path
def url_path(request, base_url=None, is_full=False, *args, **kwargs): """ join base_url and some GET-parameters to one; it could be absolute url optionally usage example: c['current_url'] = url_path(request, use_urllib=True, is_full=False) ... <a href="{{ current_url }}">Лабораторн...
python
def url_path(request, base_url=None, is_full=False, *args, **kwargs): """ join base_url and some GET-parameters to one; it could be absolute url optionally usage example: c['current_url'] = url_path(request, use_urllib=True, is_full=False) ... <a href="{{ current_url }}">Лабораторн...
[ "def", "url_path", "(", "request", ",", "base_url", "=", "None", ",", "is_full", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "base_url", ":", "base_url", "=", "request", ".", "path", "if", "is_full", ":", "protocol...
join base_url and some GET-parameters to one; it could be absolute url optionally usage example: c['current_url'] = url_path(request, use_urllib=True, is_full=False) ... <a href="{{ current_url }}">Лабораторный номер</a>
[ "join", "base_url", "and", "some", "GET", "-", "parameters", "to", "one", ";", "it", "could", "be", "absolute", "url", "optionally" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/views/helpers.py#L7-L26
telminov/sw-django-utils
djutils/views/helpers.py
url_params
def url_params(request, except_params=None, as_is=False): """ create string with GET-params of request usage example: c['sort_url'] = url_params(request, except_params=('sort',)) ... <a href="{{ sort_url }}&sort=lab_number">Лабораторный номер</a> """ if not request.GET: ...
python
def url_params(request, except_params=None, as_is=False): """ create string with GET-params of request usage example: c['sort_url'] = url_params(request, except_params=('sort',)) ... <a href="{{ sort_url }}&sort=lab_number">Лабораторный номер</a> """ if not request.GET: ...
[ "def", "url_params", "(", "request", ",", "except_params", "=", "None", ",", "as_is", "=", "False", ")", ":", "if", "not", "request", ".", "GET", ":", "return", "''", "params", "=", "[", "]", "for", "key", ",", "value", "in", "request", ".", "GET", ...
create string with GET-params of request usage example: c['sort_url'] = url_params(request, except_params=('sort',)) ... <a href="{{ sort_url }}&sort=lab_number">Лабораторный номер</a>
[ "create", "string", "with", "GET", "-", "params", "of", "request" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/views/helpers.py#L28-L50
telminov/sw-django-utils
djutils/views/helpers.py
prepare_sort_params
def prepare_sort_params(params, request, sort_key='sort', revers_sort=None, except_params=None): """ Prepare sort params. Add revers '-' if need. Params: params - list of sort parameters request sort_key revers_sort - list or set with keys that need re...
python
def prepare_sort_params(params, request, sort_key='sort', revers_sort=None, except_params=None): """ Prepare sort params. Add revers '-' if need. Params: params - list of sort parameters request sort_key revers_sort - list or set with keys that need re...
[ "def", "prepare_sort_params", "(", "params", ",", "request", ",", "sort_key", "=", "'sort'", ",", "revers_sort", "=", "None", ",", "except_params", "=", "None", ")", ":", "current_param", ",", "current_reversed", "=", "sort_key_process", "(", "request", ",", "...
Prepare sort params. Add revers '-' if need. Params: params - list of sort parameters request sort_key revers_sort - list or set with keys that need reverse default sort direction except_params - GET-params that will be ignored Example: ...
[ "Prepare", "sort", "params", ".", "Add", "revers", "-", "if", "need", ".", "Params", ":", "params", "-", "list", "of", "sort", "parameters", "request", "sort_key", "revers_sort", "-", "list", "or", "set", "with", "keys", "that", "need", "reverse", "default...
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/views/helpers.py#L53-L100
telminov/sw-django-utils
djutils/views/helpers.py
sort_key_process
def sort_key_process(request, sort_key='sort'): """ process sort-parameter value (for example, "-name") return: current_param - field for sorting ("name) current_reversed - revers flag (True) """ current = request.GET.get(sort_key) current_reversed = False cur...
python
def sort_key_process(request, sort_key='sort'): """ process sort-parameter value (for example, "-name") return: current_param - field for sorting ("name) current_reversed - revers flag (True) """ current = request.GET.get(sort_key) current_reversed = False cur...
[ "def", "sort_key_process", "(", "request", ",", "sort_key", "=", "'sort'", ")", ":", "current", "=", "request", ".", "GET", ".", "get", "(", "sort_key", ")", "current_reversed", "=", "False", "current_param", "=", "None", "if", "current", ":", "mo", "=", ...
process sort-parameter value (for example, "-name") return: current_param - field for sorting ("name) current_reversed - revers flag (True)
[ "process", "sort", "-", "parameter", "value", "(", "for", "example", "-", "name", ")", "return", ":", "current_param", "-", "field", "for", "sorting", "(", "name", ")", "current_reversed", "-", "revers", "flag", "(", "True", ")" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/views/helpers.py#L103-L119
telminov/sw-django-utils
djutils/forms.py
transform_form_error
def transform_form_error(form, verbose=True): """ transform form errors to list like ["field1: error1", "field2: error2"] """ errors = [] for field, err_msg in form.errors.items(): if field == '__all__': # general errors errors.append(', '.join(err_msg)) else...
python
def transform_form_error(form, verbose=True): """ transform form errors to list like ["field1: error1", "field2: error2"] """ errors = [] for field, err_msg in form.errors.items(): if field == '__all__': # general errors errors.append(', '.join(err_msg)) else...
[ "def", "transform_form_error", "(", "form", ",", "verbose", "=", "True", ")", ":", "errors", "=", "[", "]", "for", "field", ",", "err_msg", "in", "form", ".", "errors", ".", "items", "(", ")", ":", "if", "field", "==", "'__all__'", ":", "# general erro...
transform form errors to list like ["field1: error1", "field2: error2"]
[ "transform", "form", "errors", "to", "list", "like", "[", "field1", ":", "error1", "field2", ":", "error2", "]" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/forms.py#L3-L17
telminov/sw-django-utils
djutils/management/commands/__init__.py
process_date_from_to_options
def process_date_from_to_options(options, to_datetime=False, default_dt_to=False): """ to_datetime - приводить ли date к datetime default_dt_to - устанавливать заведомо будущее дефолтное значение для dt_to """ start_time = datetime.datetime.now() if options.get('last_week'): dt_...
python
def process_date_from_to_options(options, to_datetime=False, default_dt_to=False): """ to_datetime - приводить ли date к datetime default_dt_to - устанавливать заведомо будущее дефолтное значение для dt_to """ start_time = datetime.datetime.now() if options.get('last_week'): dt_...
[ "def", "process_date_from_to_options", "(", "options", ",", "to_datetime", "=", "False", ",", "default_dt_to", "=", "False", ")", ":", "start_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "options", ".", "get", "(", "'last_week'", ")",...
to_datetime - приводить ли date к datetime default_dt_to - устанавливать заведомо будущее дефолтное значение для dt_to
[ "to_datetime", "-", "приводить", "ли", "date", "к", "datetime", "default_dt_to", "-", "устанавливать", "заведомо", "будущее", "дефолтное", "значение", "для", "dt_to" ]
train
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/management/commands/__init__.py#L30-L77
SteelPangolin/genderize
genderize/__init__.py
_chunked
def _chunked(iterable, n): """ Collect data into chunks of up to length n. :type iterable: Iterable[T] :type n: int :rtype: Iterator[list[T]] """ it = iter(iterable) while True: chunk = list(islice(it, n)) if chunk: yield chunk else: return
python
def _chunked(iterable, n): """ Collect data into chunks of up to length n. :type iterable: Iterable[T] :type n: int :rtype: Iterator[list[T]] """ it = iter(iterable) while True: chunk = list(islice(it, n)) if chunk: yield chunk else: return
[ "def", "_chunked", "(", "iterable", ",", "n", ")", ":", "it", "=", "iter", "(", "iterable", ")", "while", "True", ":", "chunk", "=", "list", "(", "islice", "(", "it", ",", "n", ")", ")", "if", "chunk", ":", "yield", "chunk", "else", ":", "return"...
Collect data into chunks of up to length n. :type iterable: Iterable[T] :type n: int :rtype: Iterator[list[T]]
[ "Collect", "data", "into", "chunks", "of", "up", "to", "length", "n", ".", ":", "type", "iterable", ":", "Iterable", "[", "T", "]", ":", "type", "n", ":", "int", ":", "rtype", ":", "Iterator", "[", "list", "[", "T", "]]" ]
train
https://github.com/SteelPangolin/genderize/blob/53ca94012702f3589ab528b628b28df52397232f/genderize/__init__.py#L166-L179
SteelPangolin/genderize
genderize/__init__.py
Genderize.get
def get(self, names, country_id=None, language_id=None, retheader=False): """ Look up gender for a list of names. Can optionally refine search with locale info. May make multiple requests if there are more names than can be retrieved in one call. :param names: List of na...
python
def get(self, names, country_id=None, language_id=None, retheader=False): """ Look up gender for a list of names. Can optionally refine search with locale info. May make multiple requests if there are more names than can be retrieved in one call. :param names: List of na...
[ "def", "get", "(", "self", ",", "names", ",", "country_id", "=", "None", ",", "language_id", "=", "None", ",", "retheader", "=", "False", ")", ":", "responses", "=", "[", "self", ".", "_get_chunk", "(", "name_chunk", ",", "country_id", ",", "language_id"...
Look up gender for a list of names. Can optionally refine search with locale info. May make multiple requests if there are more names than can be retrieved in one call. :param names: List of names. :type names: Iterable[str] :param country_id: Optional ISO 3166-1 alpha-2...
[ "Look", "up", "gender", "for", "a", "list", "of", "names", ".", "Can", "optionally", "refine", "search", "with", "locale", "info", ".", "May", "make", "multiple", "requests", "if", "there", "are", "more", "names", "than", "can", "be", "retrieved", "in", ...
train
https://github.com/SteelPangolin/genderize/blob/53ca94012702f3589ab528b628b28df52397232f/genderize/__init__.py#L66-L110
SteelPangolin/genderize
genderize/__init__.py
Genderize.get1
def get1(self, name, **kwargs): """ Look up gender for a single name. See :py:meth:`get`. Doesn't support retheader option. """ if 'retheader' in kwargs: raise GenderizeException( "get1() doesn't support the retheader option.") return s...
python
def get1(self, name, **kwargs): """ Look up gender for a single name. See :py:meth:`get`. Doesn't support retheader option. """ if 'retheader' in kwargs: raise GenderizeException( "get1() doesn't support the retheader option.") return s...
[ "def", "get1", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "if", "'retheader'", "in", "kwargs", ":", "raise", "GenderizeException", "(", "\"get1() doesn't support the retheader option.\"", ")", "return", "self", ".", "get", "(", "[", "name", ...
Look up gender for a single name. See :py:meth:`get`. Doesn't support retheader option.
[ "Look", "up", "gender", "for", "a", "single", "name", ".", "See", ":", "py", ":", "meth", ":", "get", ".", "Doesn", "t", "support", "retheader", "option", "." ]
train
https://github.com/SteelPangolin/genderize/blob/53ca94012702f3589ab528b628b28df52397232f/genderize/__init__.py#L154-L163
ewiger/mlab
src/mlab/mlabwrap.py
saveVarsInMat
def saveVarsInMat(filename, varNamesStr, outOf=None, **opts): """Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`. """ from mlabwrap import mlab filename, varnames, outOf = __saveVarsHelper( filename, varNamesStr, outOf, '.mat', **op...
python
def saveVarsInMat(filename, varNamesStr, outOf=None, **opts): """Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`. """ from mlabwrap import mlab filename, varnames, outOf = __saveVarsHelper( filename, varNamesStr, outOf, '.mat', **op...
[ "def", "saveVarsInMat", "(", "filename", ",", "varNamesStr", ",", "outOf", "=", "None", ",", "*", "*", "opts", ")", ":", "from", "mlabwrap", "import", "mlab", "filename", ",", "varnames", ",", "outOf", "=", "__saveVarsHelper", "(", "filename", ",", "varNam...
Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`.
[ "Hacky", "convinience", "function", "to", "dump", "a", "couple", "of", "python", "variables", "in", "a", ".", "mat", "file", ".", "See", "awmstools", ".", "saveVars", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabwrap.py#L651-L664
ewiger/mlab
src/mlab/mlabwrap.py
MlabWrap._make_proxy
def _make_proxy(self, varname, parent=None, constructor=MlabObjectProxy): """Creates a proxy for a variable. XXX create and cache nested proxies also here. """ # FIXME why not just use gensym here? proxy_val_name = "PROXY_VAL%d__" % self._proxy_count self._proxy_count +=...
python
def _make_proxy(self, varname, parent=None, constructor=MlabObjectProxy): """Creates a proxy for a variable. XXX create and cache nested proxies also here. """ # FIXME why not just use gensym here? proxy_val_name = "PROXY_VAL%d__" % self._proxy_count self._proxy_count +=...
[ "def", "_make_proxy", "(", "self", ",", "varname", ",", "parent", "=", "None", ",", "constructor", "=", "MlabObjectProxy", ")", ":", "# FIXME why not just use gensym here?", "proxy_val_name", "=", "\"PROXY_VAL%d__\"", "%", "self", ".", "_proxy_count", "self", ".", ...
Creates a proxy for a variable. XXX create and cache nested proxies also here.
[ "Creates", "a", "proxy", "for", "a", "variable", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabwrap.py#L440-L451
ewiger/mlab
src/mlab/mlabwrap.py
MlabWrap._do
def _do(self, cmd, *args, **kwargs): """Semi-raw execution of a matlab command. Smartly handle calls to matlab, figure out what to do with `args`, and when to use function call syntax and not. If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is used in Matlab...
python
def _do(self, cmd, *args, **kwargs): """Semi-raw execution of a matlab command. Smartly handle calls to matlab, figure out what to do with `args`, and when to use function call syntax and not. If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is used in Matlab...
[ "def", "_do", "(", "self", ",", "cmd", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "handle_out", "=", "kwargs", ".", "get", "(", "'handle_out'", ",", "_flush_write_stdout", ")", "#self._session = self._session or mlabraw.open()", "# HACK", "if", "self...
Semi-raw execution of a matlab command. Smartly handle calls to matlab, figure out what to do with `args`, and when to use function call syntax and not. If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is used in Matlab -- this also makes literal Matlab commands lega...
[ "Semi", "-", "raw", "execution", "of", "a", "matlab", "command", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabwrap.py#L487-L559
ewiger/mlab
src/mlab/mlabwrap.py
MlabWrap._get
def _get(self, name, remove=False): r"""Directly access a variable in matlab space. This should normally not be used by user code.""" # FIXME should this really be needed in normal operation? if name in self._proxies: return self._proxies[name] varname = name vartype = s...
python
def _get(self, name, remove=False): r"""Directly access a variable in matlab space. This should normally not be used by user code.""" # FIXME should this really be needed in normal operation? if name in self._proxies: return self._proxies[name] varname = name vartype = s...
[ "def", "_get", "(", "self", ",", "name", ",", "remove", "=", "False", ")", ":", "# FIXME should this really be needed in normal operation?", "if", "name", "in", "self", ".", "_proxies", ":", "return", "self", ".", "_proxies", "[", "name", "]", "varname", "=", ...
r"""Directly access a variable in matlab space. This should normally not be used by user code.
[ "r", "Directly", "access", "a", "variable", "in", "matlab", "space", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabwrap.py#L561-L593
ewiger/mlab
src/mlab/mlabwrap.py
MlabWrap._set
def _set(self, name, value): r"""Directly set a variable `name` in matlab space to `value`. This should normally not be used in user code.""" if isinstance(value, MlabObjectProxy): mlabraw.eval(self._session, "%s = %s;" % (name, value._name)) else: ## mlabraw.put...
python
def _set(self, name, value): r"""Directly set a variable `name` in matlab space to `value`. This should normally not be used in user code.""" if isinstance(value, MlabObjectProxy): mlabraw.eval(self._session, "%s = %s;" % (name, value._name)) else: ## mlabraw.put...
[ "def", "_set", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "MlabObjectProxy", ")", ":", "mlabraw", ".", "eval", "(", "self", ".", "_session", ",", "\"%s = %s;\"", "%", "(", "name", ",", "value", ".", "_nam...
r"""Directly set a variable `name` in matlab space to `value`. This should normally not be used in user code.
[ "r", "Directly", "set", "a", "variable", "name", "in", "matlab", "space", "to", "value", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabwrap.py#L595-L603
ewiger/mlab
src/mlab/matlabcom.py
MatlabCom.open
def open(self, visible=False): """ Dispatches the matlab COM client. Note: If this method fails, try running matlab with the -regserver flag. """ if self.client: raise MatlabConnectionError('Matlab(TM) COM client is still active. Use close to ' 'close it') self.client = ...
python
def open(self, visible=False): """ Dispatches the matlab COM client. Note: If this method fails, try running matlab with the -regserver flag. """ if self.client: raise MatlabConnectionError('Matlab(TM) COM client is still active. Use close to ' 'close it') self.client = ...
[ "def", "open", "(", "self", ",", "visible", "=", "False", ")", ":", "if", "self", ".", "client", ":", "raise", "MatlabConnectionError", "(", "'Matlab(TM) COM client is still active. Use close to '", "'close it'", ")", "self", ".", "client", "=", "win32com", ".", ...
Dispatches the matlab COM client. Note: If this method fails, try running matlab with the -regserver flag.
[ "Dispatches", "the", "matlab", "COM", "client", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabcom.py#L54-L63
ewiger/mlab
src/mlab/matlabcom.py
MatlabCom.eval
def eval(self, expression, identify_erros=True): """ Evaluates a matlab expression synchronously. If identify_erros is true, and the last output line after evaluating the expressions begins with '???' an excpetion is thrown with the matlab error following the '???'. The return value of the function...
python
def eval(self, expression, identify_erros=True): """ Evaluates a matlab expression synchronously. If identify_erros is true, and the last output line after evaluating the expressions begins with '???' an excpetion is thrown with the matlab error following the '???'. The return value of the function...
[ "def", "eval", "(", "self", ",", "expression", ",", "identify_erros", "=", "True", ")", ":", "#print expression", "self", ".", "_check_open", "(", ")", "ret", "=", "self", ".", "client", ".", "Execute", "(", "expression", ")", "#print ret", "if", "identify...
Evaluates a matlab expression synchronously. If identify_erros is true, and the last output line after evaluating the expressions begins with '???' an excpetion is thrown with the matlab error following the '???'. The return value of the function is the matlab output following the call.
[ "Evaluates", "a", "matlab", "expression", "synchronously", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabcom.py#L75-L90
ewiger/mlab
src/mlab/matlabcom.py
MatlabCom.get
def get(self, names_to_get, convert_to_numpy=True): """ Loads the requested variables from the matlab com client. names_to_get can be either a variable name or a list of variable names. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned...
python
def get(self, names_to_get, convert_to_numpy=True): """ Loads the requested variables from the matlab com client. names_to_get can be either a variable name or a list of variable names. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned...
[ "def", "get", "(", "self", ",", "names_to_get", ",", "convert_to_numpy", "=", "True", ")", ":", "self", ".", "_check_open", "(", ")", "single_itme", "=", "isinstance", "(", "names_to_get", ",", "(", "unicode", ",", "str", ")", ")", "if", "single_itme", "...
Loads the requested variables from the matlab com client. names_to_get can be either a variable name or a list of variable names. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned. If convert_to_numpy is true, the method will all arra...
[ "Loads", "the", "requested", "variables", "from", "the", "matlab", "com", "client", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabcom.py#L92-L117
ewiger/mlab
src/mlab/matlabcom.py
MatlabCom.put
def put(self, name_to_val): """ Loads a dictionary of variable names into the matlab com client. """ self._check_open() for name, val in name_to_val.iteritems(): # First try to put data as a matrix: try: self.client.PutFullMatrix(name, 'base', val, None) except: self.cl...
python
def put(self, name_to_val): """ Loads a dictionary of variable names into the matlab com client. """ self._check_open() for name, val in name_to_val.iteritems(): # First try to put data as a matrix: try: self.client.PutFullMatrix(name, 'base', val, None) except: self.cl...
[ "def", "put", "(", "self", ",", "name_to_val", ")", ":", "self", ".", "_check_open", "(", ")", "for", "name", ",", "val", "in", "name_to_val", ".", "iteritems", "(", ")", ":", "# First try to put data as a matrix:", "try", ":", "self", ".", "client", ".", ...
Loads a dictionary of variable names into the matlab com client.
[ "Loads", "a", "dictionary", "of", "variable", "names", "into", "the", "matlab", "com", "client", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabcom.py#L119-L128
ewiger/mlab
src/mlab/mlabraw.py
open
def open(): global _MATLAB_RELEASE '''Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location ''' if is_win: ret = MatlabConnection() ret.open() return ret else: if settings.MATLAB_PATH != 'guess': matlab_path = settings.MA...
python
def open(): global _MATLAB_RELEASE '''Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location ''' if is_win: ret = MatlabConnection() ret.open() return ret else: if settings.MATLAB_PATH != 'guess': matlab_path = settings.MA...
[ "def", "open", "(", ")", ":", "global", "_MATLAB_RELEASE", "if", "is_win", ":", "ret", "=", "MatlabConnection", "(", ")", "ret", ".", "open", "(", ")", "return", "ret", "else", ":", "if", "settings", ".", "MATLAB_PATH", "!=", "'guess'", ":", "matlab_path...
Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location
[ "Opens", "MATLAB", "using", "specified", "connection", "(", "or", "DCOM", "+", "protocol", "on", "Windows", ")", "where", "matlab_location" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/mlabraw.py#L39-L60
ewiger/mlab
src/mlab/matlabpipe.py
_list_releases
def _list_releases(): ''' Tries to guess matlab process release version and location path on osx machines. The paths we will search are in the format: /Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab We will try the latest version first. If no path is found, None is reutrned. ''' if...
python
def _list_releases(): ''' Tries to guess matlab process release version and location path on osx machines. The paths we will search are in the format: /Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab We will try the latest version first. If no path is found, None is reutrned. ''' if...
[ "def", "_list_releases", "(", ")", ":", "if", "is_linux", "(", ")", ":", "base_path", "=", "'/usr/local/MATLAB/R%d%s/bin/matlab'", "else", ":", "# assume mac", "base_path", "=", "'/Applications/MATLAB_R%d%s.app/bin/matlab'", "years", "=", "range", "(", "2050", ",", ...
Tries to guess matlab process release version and location path on osx machines. The paths we will search are in the format: /Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab We will try the latest version first. If no path is found, None is reutrned.
[ "Tries", "to", "guess", "matlab", "process", "release", "version", "and", "location", "path", "on", "osx", "machines", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L41-L62
ewiger/mlab
src/mlab/matlabpipe.py
is_valid_release_version
def is_valid_release_version(version): '''Checks that the given version code is valid.''' return version is not None and len(version) == 6 and version[0] == 'R' \ and int(version[1:5]) in range(1990, 2050) \ and version[5] in ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')
python
def is_valid_release_version(version): '''Checks that the given version code is valid.''' return version is not None and len(version) == 6 and version[0] == 'R' \ and int(version[1:5]) in range(1990, 2050) \ and version[5] in ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')
[ "def", "is_valid_release_version", "(", "version", ")", ":", "return", "version", "is", "not", "None", "and", "len", "(", "version", ")", "==", "6", "and", "version", "[", "0", "]", "==", "'R'", "and", "int", "(", "version", "[", "1", ":", "5", "]", ...
Checks that the given version code is valid.
[ "Checks", "that", "the", "given", "version", "code", "is", "valid", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L72-L76
ewiger/mlab
src/mlab/matlabpipe.py
find_matlab_version
def find_matlab_version(process_path): """ Tries to guess matlab's version according to its process path. If we couldn't gues the version, None is returned. """ bin_path = os.path.dirname(process_path) matlab_path = os.path.dirname(bin_path) matlab_dir_name = os.path.basename(matlab_path) v...
python
def find_matlab_version(process_path): """ Tries to guess matlab's version according to its process path. If we couldn't gues the version, None is returned. """ bin_path = os.path.dirname(process_path) matlab_path = os.path.dirname(bin_path) matlab_dir_name = os.path.basename(matlab_path) v...
[ "def", "find_matlab_version", "(", "process_path", ")", ":", "bin_path", "=", "os", ".", "path", ".", "dirname", "(", "process_path", ")", "matlab_path", "=", "os", ".", "path", ".", "dirname", "(", "bin_path", ")", "matlab_dir_name", "=", "os", ".", "path...
Tries to guess matlab's version according to its process path. If we couldn't gues the version, None is returned.
[ "Tries", "to", "guess", "matlab", "s", "version", "according", "to", "its", "process", "path", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L91-L104
ewiger/mlab
src/mlab/matlabpipe.py
MatlabPipe.open
def open(self, print_matlab_welcome=False): '''Opens the matlab process.''' if self.process and not self.process.returncode: raise MatlabConnectionError('Matlab(TM) process is still active. Use close to ' 'close it') self.process = subproce...
python
def open(self, print_matlab_welcome=False): '''Opens the matlab process.''' if self.process and not self.process.returncode: raise MatlabConnectionError('Matlab(TM) process is still active. Use close to ' 'close it') self.process = subproce...
[ "def", "open", "(", "self", ",", "print_matlab_welcome", "=", "False", ")", ":", "if", "self", ".", "process", "and", "not", "self", ".", "process", ".", "returncode", ":", "raise", "MatlabConnectionError", "(", "'Matlab(TM) process is still active. Use close to '",...
Opens the matlab process.
[ "Opens", "the", "matlab", "process", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L148-L162
ewiger/mlab
src/mlab/matlabpipe.py
MatlabPipe.eval
def eval(self, expression, identify_errors=True, print_expression=True, on_new_output=sys.stdout.write): """ Evaluates a matlab expression synchronously. If identify_erros is true, and the last output line after evaluat...
python
def eval(self, expression, identify_errors=True, print_expression=True, on_new_output=sys.stdout.write): """ Evaluates a matlab expression synchronously. If identify_erros is true, and the last output line after evaluat...
[ "def", "eval", "(", "self", ",", "expression", ",", "identify_errors", "=", "True", ",", "print_expression", "=", "True", ",", "on_new_output", "=", "sys", ".", "stdout", ".", "write", ")", ":", "self", ".", "_check_open", "(", ")", "if", "print_expression...
Evaluates a matlab expression synchronously. If identify_erros is true, and the last output line after evaluating the expressions begins with '???' and excpetion is thrown with the matlab error following the '???'. If on_new_output is not None, it will be called whenever a new output is...
[ "Evaluates", "a", "matlab", "expression", "synchronously", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L170-L195
ewiger/mlab
src/mlab/matlabpipe.py
MatlabPipe.put
def put(self, name_to_val, oned_as='row', on_new_output=None): """ Loads a dictionary of variable names into the matlab shell. oned_as is the same as in scipy.io.matlab.savemat function: oned_as : {'column', 'row'}, optional If 'column', write 1-D numpy arrays as column vectors. ...
python
def put(self, name_to_val, oned_as='row', on_new_output=None): """ Loads a dictionary of variable names into the matlab shell. oned_as is the same as in scipy.io.matlab.savemat function: oned_as : {'column', 'row'}, optional If 'column', write 1-D numpy arrays as column vectors. ...
[ "def", "put", "(", "self", ",", "name_to_val", ",", "oned_as", "=", "'row'", ",", "on_new_output", "=", "None", ")", ":", "self", ".", "_check_open", "(", ")", "# We can't give stdin to mlabio.savemat because it needs random access :(", "temp", "=", "StringIO", "(",...
Loads a dictionary of variable names into the matlab shell. oned_as is the same as in scipy.io.matlab.savemat function: oned_as : {'column', 'row'}, optional If 'column', write 1-D numpy arrays as column vectors. If 'row', write 1D numpy arrays as row vectors.
[ "Loads", "a", "dictionary", "of", "variable", "names", "into", "the", "matlab", "shell", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L198-L218
ewiger/mlab
src/mlab/matlabpipe.py
MatlabPipe.get
def get(self, names_to_get, extract_numpy_scalars=True, on_new_output=None): """ Loads the requested variables from the matlab shell. names_to_get can be either a variable name, a list of variable names, or None. If it is a var...
python
def get(self, names_to_get, extract_numpy_scalars=True, on_new_output=None): """ Loads the requested variables from the matlab shell. names_to_get can be either a variable name, a list of variable names, or None. If it is a var...
[ "def", "get", "(", "self", ",", "names_to_get", ",", "extract_numpy_scalars", "=", "True", ",", "on_new_output", "=", "None", ")", ":", "self", ".", "_check_open", "(", ")", "single_item", "=", "isinstance", "(", "names_to_get", ",", "(", "unicode", ",", "...
Loads the requested variables from the matlab shell. names_to_get can be either a variable name, a list of variable names, or None. If it is a variable name, the values is returned. If it is a list, a dictionary of variable_name -> value is returned. If it is None, a dictionary ...
[ "Loads", "the", "requested", "variables", "from", "the", "matlab", "shell", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L220-L279
ewiger/mlab
src/mlab/awmstools.py
rexGroups
def rexGroups(rex): """Return the named groups in a regular expression (compiled or as string) in occuring order. >>> rexGroups(r'(?P<name>\w+) +(?P<surname>\w+)') ('name', 'surname') """ if isinstance(rex,basestring): rex = re.compile(rex) return zip(*sorted([(n,g) for (g,n) in rex.groupi...
python
def rexGroups(rex): """Return the named groups in a regular expression (compiled or as string) in occuring order. >>> rexGroups(r'(?P<name>\w+) +(?P<surname>\w+)') ('name', 'surname') """ if isinstance(rex,basestring): rex = re.compile(rex) return zip(*sorted([(n,g) for (g,n) in rex.groupi...
[ "def", "rexGroups", "(", "rex", ")", ":", "if", "isinstance", "(", "rex", ",", "basestring", ")", ":", "rex", "=", "re", ".", "compile", "(", "rex", ")", "return", "zip", "(", "*", "sorted", "(", "[", "(", "n", ",", "g", ")", "for", "(", "g", ...
Return the named groups in a regular expression (compiled or as string) in occuring order. >>> rexGroups(r'(?P<name>\w+) +(?P<surname>\w+)') ('name', 'surname')
[ "Return", "the", "named", "groups", "in", "a", "regular", "expression", "(", "compiled", "or", "as", "string", ")", "in", "occuring", "order", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L140-L149
ewiger/mlab
src/mlab/awmstools.py
div
def div(a,b): """``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise an `ValueError` is raised. >>> div(10,2) 5 >>> div(10,3) Traceback (most recent call last): ... ValueError: 3 does not divide 10 """ res, fail = divmod(a,b) if fail: raise ValueError("...
python
def div(a,b): """``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise an `ValueError` is raised. >>> div(10,2) 5 >>> div(10,3) Traceback (most recent call last): ... ValueError: 3 does not divide 10 """ res, fail = divmod(a,b) if fail: raise ValueError("...
[ "def", "div", "(", "a", ",", "b", ")", ":", "res", ",", "fail", "=", "divmod", "(", "a", ",", "b", ")", "if", "fail", ":", "raise", "ValueError", "(", "\"%r does not divide %r\"", "%", "(", "b", ",", "a", ")", ")", "else", ":", "return", "res" ]
``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise an `ValueError` is raised. >>> div(10,2) 5 >>> div(10,3) Traceback (most recent call last): ... ValueError: 3 does not divide 10
[ "div", "(", "a", "b", ")", "is", "like", "a", "//", "b", "if", "b", "devides", "a", "otherwise", "an", "ValueError", "is", "raised", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L243-L258
ewiger/mlab
src/mlab/awmstools.py
ipshuffle
def ipshuffle(l, random=None): r"""Shuffle list `l` inplace and return it.""" import random as _random _random.shuffle(l, random) return l
python
def ipshuffle(l, random=None): r"""Shuffle list `l` inplace and return it.""" import random as _random _random.shuffle(l, random) return l
[ "def", "ipshuffle", "(", "l", ",", "random", "=", "None", ")", ":", "import", "random", "as", "_random", "_random", ".", "shuffle", "(", "l", ",", "random", ")", "return", "l" ]
r"""Shuffle list `l` inplace and return it.
[ "r", "Shuffle", "list", "l", "inplace", "and", "return", "it", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L261-L265
ewiger/mlab
src/mlab/awmstools.py
shuffle
def shuffle(seq, random=None): r"""Return shuffled *copy* of `seq`.""" if isinstance(seq, list): return ipshuffle(seq[:], random) elif isString(seq): # seq[0:0] == "" or u"" return seq[0:0].join(ipshuffle(list(seq)),random) else: return type(seq)(ipshuffle(list(seq),rand...
python
def shuffle(seq, random=None): r"""Return shuffled *copy* of `seq`.""" if isinstance(seq, list): return ipshuffle(seq[:], random) elif isString(seq): # seq[0:0] == "" or u"" return seq[0:0].join(ipshuffle(list(seq)),random) else: return type(seq)(ipshuffle(list(seq),rand...
[ "def", "shuffle", "(", "seq", ",", "random", "=", "None", ")", ":", "if", "isinstance", "(", "seq", ",", "list", ")", ":", "return", "ipshuffle", "(", "seq", "[", ":", "]", ",", "random", ")", "elif", "isString", "(", "seq", ")", ":", "# seq[0:0] =...
r"""Return shuffled *copy* of `seq`.
[ "r", "Return", "shuffled", "*", "copy", "*", "of", "seq", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L281-L289
ewiger/mlab
src/mlab/awmstools.py
slurp
def slurp(file, binary=False, expand=False): r"""Read in a complete file `file` as a string Parameters: - `file`: a file handle or a string (`str` or `unicode`). - `binary`: whether to read in the file in binary mode (default: False). """ mode = "r" + ["b",""][not binary] file = _normaliz...
python
def slurp(file, binary=False, expand=False): r"""Read in a complete file `file` as a string Parameters: - `file`: a file handle or a string (`str` or `unicode`). - `binary`: whether to read in the file in binary mode (default: False). """ mode = "r" + ["b",""][not binary] file = _normaliz...
[ "def", "slurp", "(", "file", ",", "binary", "=", "False", ",", "expand", "=", "False", ")", ":", "mode", "=", "\"r\"", "+", "[", "\"b\"", ",", "\"\"", "]", "[", "not", "binary", "]", "file", "=", "_normalizeToFile", "(", "file", ",", "mode", "=", ...
r"""Read in a complete file `file` as a string Parameters: - `file`: a file handle or a string (`str` or `unicode`). - `binary`: whether to read in the file in binary mode (default: False).
[ "r", "Read", "in", "a", "complete", "file", "file", "as", "a", "string", "Parameters", ":" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L322-L332
ewiger/mlab
src/mlab/awmstools.py
withFile
def withFile(file, func, mode='r', expand=False): """Pass `file` to `func` and ensure the file is closed afterwards. If `file` is a string, open according to `mode`; if `expand` is true also expand user and vars. """ file = _normalizeToFile(file, mode=mode, expand=expand) try: return ...
python
def withFile(file, func, mode='r', expand=False): """Pass `file` to `func` and ensure the file is closed afterwards. If `file` is a string, open according to `mode`; if `expand` is true also expand user and vars. """ file = _normalizeToFile(file, mode=mode, expand=expand) try: return ...
[ "def", "withFile", "(", "file", ",", "func", ",", "mode", "=", "'r'", ",", "expand", "=", "False", ")", ":", "file", "=", "_normalizeToFile", "(", "file", ",", "mode", "=", "mode", ",", "expand", "=", "expand", ")", "try", ":", "return", "func", "(...
Pass `file` to `func` and ensure the file is closed afterwards. If `file` is a string, open according to `mode`; if `expand` is true also expand user and vars.
[ "Pass", "file", "to", "func", "and", "ensure", "the", "file", "is", "closed", "afterwards", ".", "If", "file", "is", "a", "string", "open", "according", "to", "mode", ";", "if", "expand", "is", "true", "also", "expand", "user", "and", "vars", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L335-L342
ewiger/mlab
src/mlab/awmstools.py
slurpLines
def slurpLines(file, expand=False): r"""Read in a complete file (specified by a file handler or a filename string/unicode string) as list of lines""" file = _normalizeToFile(file, "r", expand) try: return file.readlines() finally: file.close()
python
def slurpLines(file, expand=False): r"""Read in a complete file (specified by a file handler or a filename string/unicode string) as list of lines""" file = _normalizeToFile(file, "r", expand) try: return file.readlines() finally: file.close()
[ "def", "slurpLines", "(", "file", ",", "expand", "=", "False", ")", ":", "file", "=", "_normalizeToFile", "(", "file", ",", "\"r\"", ",", "expand", ")", "try", ":", "return", "file", ".", "readlines", "(", ")", "finally", ":", "file", ".", "close", "...
r"""Read in a complete file (specified by a file handler or a filename string/unicode string) as list of lines
[ "r", "Read", "in", "a", "complete", "file", "(", "specified", "by", "a", "file", "handler", "or", "a", "filename", "string", "/", "unicode", "string", ")", "as", "list", "of", "lines" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L345-L350
ewiger/mlab
src/mlab/awmstools.py
slurpChompedLines
def slurpChompedLines(file, expand=False): r"""Return ``file`` a list of chomped lines. See `slurpLines`.""" f=_normalizeToFile(file, "r", expand) try: return list(chompLines(f)) finally: f.close()
python
def slurpChompedLines(file, expand=False): r"""Return ``file`` a list of chomped lines. See `slurpLines`.""" f=_normalizeToFile(file, "r", expand) try: return list(chompLines(f)) finally: f.close()
[ "def", "slurpChompedLines", "(", "file", ",", "expand", "=", "False", ")", ":", "f", "=", "_normalizeToFile", "(", "file", ",", "\"r\"", ",", "expand", ")", "try", ":", "return", "list", "(", "chompLines", "(", "f", ")", ")", "finally", ":", "f", "."...
r"""Return ``file`` a list of chomped lines. See `slurpLines`.
[ "r", "Return", "file", "a", "list", "of", "chomped", "lines", ".", "See", "slurpLines", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L352-L356
ewiger/mlab
src/mlab/awmstools.py
strToTempfile
def strToTempfile(s, suffix=None, prefix=None, dir=None, binary=False): """Create a new tempfile, write ``s`` to it and return the filename. `suffix`, `prefix` and `dir` are like in `tempfile.mkstemp`. """ fd, filename = tempfile.mkstemp(**dict((k,v) for (k,v) in ...
python
def strToTempfile(s, suffix=None, prefix=None, dir=None, binary=False): """Create a new tempfile, write ``s`` to it and return the filename. `suffix`, `prefix` and `dir` are like in `tempfile.mkstemp`. """ fd, filename = tempfile.mkstemp(**dict((k,v) for (k,v) in ...
[ "def", "strToTempfile", "(", "s", ",", "suffix", "=", "None", ",", "prefix", "=", "None", ",", "dir", "=", "None", ",", "binary", "=", "False", ")", ":", "fd", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", "*", "*", "dict", "(", "(", "k"...
Create a new tempfile, write ``s`` to it and return the filename. `suffix`, `prefix` and `dir` are like in `tempfile.mkstemp`.
[ "Create", "a", "new", "tempfile", "write", "s", "to", "it", "and", "return", "the", "filename", ".", "suffix", "prefix", "and", "dir", "are", "like", "in", "tempfile", ".", "mkstemp", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L358-L366
ewiger/mlab
src/mlab/awmstools.py
spitOut
def spitOut(s, file, binary=False, expand=False): r"""Write string `s` into `file` (which can be a string (`str` or `unicode`) or a `file` instance).""" mode = "w" + ["b",""][not binary] file = _normalizeToFile(file, mode=mode, expand=expand) try: file.write(s) finally: file.close()
python
def spitOut(s, file, binary=False, expand=False): r"""Write string `s` into `file` (which can be a string (`str` or `unicode`) or a `file` instance).""" mode = "w" + ["b",""][not binary] file = _normalizeToFile(file, mode=mode, expand=expand) try: file.write(s) finally: file.close()
[ "def", "spitOut", "(", "s", ",", "file", ",", "binary", "=", "False", ",", "expand", "=", "False", ")", ":", "mode", "=", "\"w\"", "+", "[", "\"b\"", ",", "\"\"", "]", "[", "not", "binary", "]", "file", "=", "_normalizeToFile", "(", "file", ",", ...
r"""Write string `s` into `file` (which can be a string (`str` or `unicode`) or a `file` instance).
[ "r", "Write", "string", "s", "into", "file", "(", "which", "can", "be", "a", "string", "(", "str", "or", "unicode", ")", "or", "a", "file", "instance", ")", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L369-L375
ewiger/mlab
src/mlab/awmstools.py
spitOutLines
def spitOutLines(lines, file, expand=False): r"""Write all the `lines` to `file` (which can be a string/unicode or a file handler).""" file = _normalizeToFile(file, mode="w", expand=expand) try: file.writelines(lines) finally: file.close()
python
def spitOutLines(lines, file, expand=False): r"""Write all the `lines` to `file` (which can be a string/unicode or a file handler).""" file = _normalizeToFile(file, mode="w", expand=expand) try: file.writelines(lines) finally: file.close()
[ "def", "spitOutLines", "(", "lines", ",", "file", ",", "expand", "=", "False", ")", ":", "file", "=", "_normalizeToFile", "(", "file", ",", "mode", "=", "\"w\"", ",", "expand", "=", "expand", ")", "try", ":", "file", ".", "writelines", "(", "lines", ...
r"""Write all the `lines` to `file` (which can be a string/unicode or a file handler).
[ "r", "Write", "all", "the", "lines", "to", "file", "(", "which", "can", "be", "a", "string", "/", "unicode", "or", "a", "file", "handler", ")", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L377-L382
ewiger/mlab
src/mlab/awmstools.py
readProcess
def readProcess(cmd, *args): r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the exit code (unlike popen2, exit is 0 if no problems occured (for some bizarre reason popen2 returns None... <sigh>). FIXME: only works for UNIX; handling of signalled processes. """ import pope...
python
def readProcess(cmd, *args): r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the exit code (unlike popen2, exit is 0 if no problems occured (for some bizarre reason popen2 returns None... <sigh>). FIXME: only works for UNIX; handling of signalled processes. """ import pope...
[ "def", "readProcess", "(", "cmd", ",", "*", "args", ")", ":", "import", "popen2", "BUFSIZE", "=", "1024", "import", "select", "popen", "=", "popen2", ".", "Popen3", "(", "(", "cmd", ",", ")", "+", "args", ",", "capturestderr", "=", "True", ")", "whic...
r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the exit code (unlike popen2, exit is 0 if no problems occured (for some bizarre reason popen2 returns None... <sigh>). FIXME: only works for UNIX; handling of signalled processes.
[ "r", "Similar", "to", "os", ".", "popen3", "but", "returns", "2", "strings", "(", "stdin", "stdout", ")", "and", "the", "exit", "code", "(", "unlike", "popen2", "exit", "is", "0", "if", "no", "problems", "occured", "(", "for", "some", "bizarre", "reaso...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L386-L424
ewiger/mlab
src/mlab/awmstools.py
runProcess
def runProcess(cmd, *args): """Run `cmd` (which is searched for in the executable path) with `args` and return the exit status. In general (unless you know what you're doing) use:: runProcess('program', filename) rather than:: os.system('program %s' % filename) because the latter will...
python
def runProcess(cmd, *args): """Run `cmd` (which is searched for in the executable path) with `args` and return the exit status. In general (unless you know what you're doing) use:: runProcess('program', filename) rather than:: os.system('program %s' % filename) because the latter will...
[ "def", "runProcess", "(", "cmd", ",", "*", "args", ")", ":", "from", "os", "import", "spawnvp", ",", "P_WAIT", "return", "spawnvp", "(", "P_WAIT", ",", "cmd", ",", "(", "cmd", ",", ")", "+", "args", ")" ]
Run `cmd` (which is searched for in the executable path) with `args` and return the exit status. In general (unless you know what you're doing) use:: runProcess('program', filename) rather than:: os.system('program %s' % filename) because the latter will not work as expected if `filename`...
[ "Run", "cmd", "(", "which", "is", "searched", "for", "in", "the", "executable", "path", ")", "with", "args", "and", "return", "the", "exit", "status", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L432-L450
ewiger/mlab
src/mlab/awmstools.py
splitext
def splitext(p): r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles (e.g. .emacs) as extensions. Also uses os.sep instead of '/'.""" root, ext = os.path.splitext(p) # check for dotfiles if (not root or root[-1] == os.sep): # XXX: use '/' or os.sep here??? return (root +...
python
def splitext(p): r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles (e.g. .emacs) as extensions. Also uses os.sep instead of '/'.""" root, ext = os.path.splitext(p) # check for dotfiles if (not root or root[-1] == os.sep): # XXX: use '/' or os.sep here??? return (root +...
[ "def", "splitext", "(", "p", ")", ":", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "p", ")", "# check for dotfiles", "if", "(", "not", "root", "or", "root", "[", "-", "1", "]", "==", "os", ".", "sep", ")", ":", "# XXX: use '...
r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles (e.g. .emacs) as extensions. Also uses os.sep instead of '/'.
[ "r", "Like", "the", "normal", "splitext", "(", "in", "posixpath", ")", "but", "doesn", "t", "treat", "dotfiles", "(", "e", ".", "g", ".", ".", "emacs", ")", "as", "extensions", ".", "Also", "uses", "os", ".", "sep", "instead", "of", "/", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L463-L472
ewiger/mlab
src/mlab/awmstools.py
bipart
def bipart(func, seq): r"""Like a partitioning version of `filter`. Returns ``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``. Example: >>> bipart(bool, [1,None,2,3,0,[],[0]]) [[None, 0, []], [1, 2, 3, [0]]] """ if func is None: func = bool res = [[],[]] for i in...
python
def bipart(func, seq): r"""Like a partitioning version of `filter`. Returns ``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``. Example: >>> bipart(bool, [1,None,2,3,0,[],[0]]) [[None, 0, []], [1, 2, 3, [0]]] """ if func is None: func = bool res = [[],[]] for i in...
[ "def", "bipart", "(", "func", ",", "seq", ")", ":", "if", "func", "is", "None", ":", "func", "=", "bool", "res", "=", "[", "[", "]", ",", "[", "]", "]", "for", "i", "in", "seq", ":", "res", "[", "not", "not", "func", "(", "i", ")", "]", "...
r"""Like a partitioning version of `filter`. Returns ``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``. Example: >>> bipart(bool, [1,None,2,3,0,[],[0]]) [[None, 0, []], [1, 2, 3, [0]]]
[ "r", "Like", "a", "partitioning", "version", "of", "filter", ".", "Returns", "[", "itemsForWhichFuncReturnedFalse", "itemsForWhichFuncReturnedTrue", "]", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L478-L491
ewiger/mlab
src/mlab/awmstools.py
binarySearchPos
def binarySearchPos(seq, item, cmpfunc=cmp): r"""Return the position of `item` in ordered sequence `seq`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found position of `item`, or -1 if `item` is not in `seq`. The returned position is NOT guaranteed to be the first occu...
python
def binarySearchPos(seq, item, cmpfunc=cmp): r"""Return the position of `item` in ordered sequence `seq`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found position of `item`, or -1 if `item` is not in `seq`. The returned position is NOT guaranteed to be the first occu...
[ "def", "binarySearchPos", "(", "seq", ",", "item", ",", "cmpfunc", "=", "cmp", ")", ":", "if", "not", "seq", ":", "return", "-", "1", "left", ",", "right", "=", "0", ",", "len", "(", "seq", ")", "-", "1", "if", "cmpfunc", "(", "seq", "[", "left...
r"""Return the position of `item` in ordered sequence `seq`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found position of `item`, or -1 if `item` is not in `seq`. The returned position is NOT guaranteed to be the first occurence of `item` in `seq`.
[ "r", "Return", "the", "position", "of", "item", "in", "ordered", "sequence", "seq", "using", "comparison", "function", "cmpfunc", "(", "defaults", "to", "cmp", ")", "and", "return", "the", "first", "found", "position", "of", "item", "or", "-", "1", "if", ...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L499-L516
ewiger/mlab
src/mlab/awmstools.py
binarySearchItem
def binarySearchItem(seq, item, cmpfunc=cmp): r""" Search an ordered sequence `seq` for `item`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found instance of `item`, or `None` if item is not in `seq`. The returned item is NOT guaranteed to be the first occurrence of it...
python
def binarySearchItem(seq, item, cmpfunc=cmp): r""" Search an ordered sequence `seq` for `item`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found instance of `item`, or `None` if item is not in `seq`. The returned item is NOT guaranteed to be the first occurrence of it...
[ "def", "binarySearchItem", "(", "seq", ",", "item", ",", "cmpfunc", "=", "cmp", ")", ":", "pos", "=", "binarySearchPos", "(", "seq", ",", "item", ",", "cmpfunc", ")", "if", "pos", "==", "-", "1", ":", "raise", "KeyError", "(", "\"Item not in seq\"", ")...
r""" Search an ordered sequence `seq` for `item`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found instance of `item`, or `None` if item is not in `seq`. The returned item is NOT guaranteed to be the first occurrence of item in `seq`.
[ "r", "Search", "an", "ordered", "sequence", "seq", "for", "item", "using", "comparison", "function", "cmpfunc", "(", "defaults", "to", "cmp", ")", "and", "return", "the", "first", "found", "instance", "of", "item", "or", "None", "if", "item", "is", "not", ...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L536-L543
ewiger/mlab
src/mlab/awmstools.py
rotate
def rotate(l, steps=1): r"""Rotates a list `l` `steps` to the left. Accepts `steps` > `len(l)` or < 0. >>> rotate([1,2,3]) [2, 3, 1] >>> rotate([1,2,3,4],-2) [3, 4, 1, 2] >>> rotate([1,2,3,4],-5) [4, 1, 2, 3] >>> rotate([1,2,3,4],1) [2, 3, 4, 1] >>> l = [1,2,3]; rotate(l) is...
python
def rotate(l, steps=1): r"""Rotates a list `l` `steps` to the left. Accepts `steps` > `len(l)` or < 0. >>> rotate([1,2,3]) [2, 3, 1] >>> rotate([1,2,3,4],-2) [3, 4, 1, 2] >>> rotate([1,2,3,4],-5) [4, 1, 2, 3] >>> rotate([1,2,3,4],1) [2, 3, 4, 1] >>> l = [1,2,3]; rotate(l) is...
[ "def", "rotate", "(", "l", ",", "steps", "=", "1", ")", ":", "if", "len", "(", "l", ")", ":", "steps", "%=", "len", "(", "l", ")", "if", "steps", ":", "res", "=", "l", "[", "steps", ":", "]", "res", ".", "extend", "(", "l", "[", ":", "ste...
r"""Rotates a list `l` `steps` to the left. Accepts `steps` > `len(l)` or < 0. >>> rotate([1,2,3]) [2, 3, 1] >>> rotate([1,2,3,4],-2) [3, 4, 1, 2] >>> rotate([1,2,3,4],-5) [4, 1, 2, 3] >>> rotate([1,2,3,4],1) [2, 3, 4, 1] >>> l = [1,2,3]; rotate(l) is not l True
[ "r", "Rotates", "a", "list", "l", "steps", "to", "the", "left", ".", "Accepts", "steps", ">", "len", "(", "l", ")", "or", "<", "0", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L546-L566
ewiger/mlab
src/mlab/awmstools.py
iprotate
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del ...
python
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del ...
[ "def", "iprotate", "(", "l", ",", "steps", "=", "1", ")", ":", "if", "len", "(", "l", ")", ":", "steps", "%=", "len", "(", "l", ")", "if", "steps", ":", "firstPart", "=", "l", "[", ":", "steps", "]", "del", "l", "[", ":", "steps", "]", "l",...
r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3]
[ "r", "Like", "rotate", "but", "modifies", "l", "in", "-", "place", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L568-L586
ewiger/mlab
src/mlab/awmstools.py
unique
def unique(iterable): r"""Returns all unique items in `iterable` in the *same* order (only works if items in `seq` are hashable). """ d = {} return (d.setdefault(x,x) for x in iterable if x not in d)
python
def unique(iterable): r"""Returns all unique items in `iterable` in the *same* order (only works if items in `seq` are hashable). """ d = {} return (d.setdefault(x,x) for x in iterable if x not in d)
[ "def", "unique", "(", "iterable", ")", ":", "d", "=", "{", "}", "return", "(", "d", ".", "setdefault", "(", "x", ",", "x", ")", "for", "x", "in", "iterable", "if", "x", "not", "in", "d", ")" ]
r"""Returns all unique items in `iterable` in the *same* order (only works if items in `seq` are hashable).
[ "r", "Returns", "all", "unique", "items", "in", "iterable", "in", "the", "*", "same", "*", "order", "(", "only", "works", "if", "items", "in", "seq", "are", "hashable", ")", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L594-L599
ewiger/mlab
src/mlab/awmstools.py
notUnique
def notUnique(iterable, reportMax=INF): """Returns the elements in `iterable` that aren't unique; stops after it found `reportMax` non-unique elements. Examples: >>> list(notUnique([1,1,2,2,3,3])) [1, 2, 3] >>> list(notUnique([1,1,2,2,3,3], 1)) [1] """ hash = {} n=0 if repo...
python
def notUnique(iterable, reportMax=INF): """Returns the elements in `iterable` that aren't unique; stops after it found `reportMax` non-unique elements. Examples: >>> list(notUnique([1,1,2,2,3,3])) [1, 2, 3] >>> list(notUnique([1,1,2,2,3,3], 1)) [1] """ hash = {} n=0 if repo...
[ "def", "notUnique", "(", "iterable", ",", "reportMax", "=", "INF", ")", ":", "hash", "=", "{", "}", "n", "=", "0", "if", "reportMax", "<", "1", ":", "raise", "ValueError", "(", "\"`reportMax` must be >= 1 and is %r\"", "%", "reportMax", ")", "for", "item",...
Returns the elements in `iterable` that aren't unique; stops after it found `reportMax` non-unique elements. Examples: >>> list(notUnique([1,1,2,2,3,3])) [1, 2, 3] >>> list(notUnique([1,1,2,2,3,3], 1)) [1]
[ "Returns", "the", "elements", "in", "iterable", "that", "aren", "t", "unique", ";", "stops", "after", "it", "found", "reportMax", "non", "-", "unique", "elements", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L614-L635
ewiger/mlab
src/mlab/awmstools.py
unweave
def unweave(iterable, n=2): r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to list `n`. Example: >>> unweave((1,2,3,4,5), 3) [[1, 4], [2, 5], [3]] """ res = [[] for i in range(n)] i = 0 for x in iterable: res[i % n].append(x) i += 1 retu...
python
def unweave(iterable, n=2): r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to list `n`. Example: >>> unweave((1,2,3,4,5), 3) [[1, 4], [2, 5], [3]] """ res = [[] for i in range(n)] i = 0 for x in iterable: res[i % n].append(x) i += 1 retu...
[ "def", "unweave", "(", "iterable", ",", "n", "=", "2", ")", ":", "res", "=", "[", "[", "]", "for", "i", "in", "range", "(", "n", ")", "]", "i", "=", "0", "for", "x", "in", "iterable", ":", "res", "[", "i", "%", "n", "]", ".", "append", "(...
r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to list `n`. Example: >>> unweave((1,2,3,4,5), 3) [[1, 4], [2, 5], [3]]
[ "r", "Divide", "iterable", "in", "n", "lists", "so", "that", "every", "n", "th", "element", "belongs", "to", "list", "n", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L655-L669
ewiger/mlab
src/mlab/awmstools.py
weave
def weave(*iterables): r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]). >>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C'])) [1, 4, 6, 2, 5, 7, 3, 6, 8] Any iterable will work. The first exhausted iterable determines when to stop. FIXME rethink stopping semantics. >>> list...
python
def weave(*iterables): r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]). >>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C'])) [1, 4, 6, 2, 5, 7, 3, 6, 8] Any iterable will work. The first exhausted iterable determines when to stop. FIXME rethink stopping semantics. >>> list...
[ "def", "weave", "(", "*", "iterables", ")", ":", "iterables", "=", "map", "(", "iter", ",", "iterables", ")", "while", "True", ":", "for", "it", "in", "iterables", ":", "yield", "it", ".", "next", "(", ")" ]
r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]). >>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C'])) [1, 4, 6, 2, 5, 7, 3, 6, 8] Any iterable will work. The first exhausted iterable determines when to stop. FIXME rethink stopping semantics. >>> list(weave(iter(('is','psu')), ...
[ "r", "weave", "(", "seq1", "[", "seq2", "]", "[", "...", "]", ")", "-", ">", "iter", "(", "[", "seq1", "[", "0", "]", "seq2", "[", "0", "]", "...", "]", ")", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L674-L690
ewiger/mlab
src/mlab/awmstools.py
atIndices
def atIndices(indexable, indices, default=__unique): r"""Return a list of items in `indexable` at positions `indices`. Examples: >>> atIndices([1,2,3], [1,1,0]) [2, 2, 1] >>> atIndices([1,2,3], [1,1,0,4], 'default') [2, 2, 1, 'default'] >>> atIndices({'a':3, 'b':0}, ['a']) [3] """ ...
python
def atIndices(indexable, indices, default=__unique): r"""Return a list of items in `indexable` at positions `indices`. Examples: >>> atIndices([1,2,3], [1,1,0]) [2, 2, 1] >>> atIndices([1,2,3], [1,1,0,4], 'default') [2, 2, 1, 'default'] >>> atIndices({'a':3, 'b':0}, ['a']) [3] """ ...
[ "def", "atIndices", "(", "indexable", ",", "indices", ",", "default", "=", "__unique", ")", ":", "if", "default", "is", "__unique", ":", "return", "[", "indexable", "[", "i", "]", "for", "i", "in", "indices", "]", "else", ":", "res", "=", "[", "]", ...
r"""Return a list of items in `indexable` at positions `indices`. Examples: >>> atIndices([1,2,3], [1,1,0]) [2, 2, 1] >>> atIndices([1,2,3], [1,1,0,4], 'default') [2, 2, 1, 'default'] >>> atIndices({'a':3, 'b':0}, ['a']) [3]
[ "r", "Return", "a", "list", "of", "items", "in", "indexable", "at", "positions", "indices", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L692-L713
ewiger/mlab
src/mlab/awmstools.py
window
def window(iterable, n=2, s=1): r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time over `iterable`. Examples: >>> list(window(range(6),2)) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] >>> list(window(range(6),3)) [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)] >>> list(w...
python
def window(iterable, n=2, s=1): r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time over `iterable`. Examples: >>> list(window(range(6),2)) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] >>> list(window(range(6),3)) [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)] >>> list(w...
[ "def", "window", "(", "iterable", ",", "n", "=", "2", ",", "s", "=", "1", ")", ":", "assert", "n", ">=", "s", "last", "=", "[", "]", "for", "elt", "in", "iterable", ":", "last", ".", "append", "(", "elt", ")", "if", "len", "(", "last", ")", ...
r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time over `iterable`. Examples: >>> list(window(range(6),2)) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] >>> list(window(range(6),3)) [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)] >>> list(window(range(6),3, 2)) [(0, 1, 2)...
[ "r", "Move", "an", "n", "-", "item", "(", "default", "2", ")", "windows", "s", "steps", "(", "default", "1", ")", "at", "a", "time", "over", "iterable", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L733-L752
ewiger/mlab
src/mlab/awmstools.py
group
def group(iterable, n=2, pad=__unique): r"""Iterate `n`-wise (default pairwise) over `iter`. Examples: >>> for (first, last) in group("Akira Kurosawa John Ford".split()): ... print "given name: %s surname: %s" % (first, last) ... given name: Akira surname: Kurosawa given name: John sur...
python
def group(iterable, n=2, pad=__unique): r"""Iterate `n`-wise (default pairwise) over `iter`. Examples: >>> for (first, last) in group("Akira Kurosawa John Ford".split()): ... print "given name: %s surname: %s" % (first, last) ... given name: Akira surname: Kurosawa given name: John sur...
[ "def", "group", "(", "iterable", ",", "n", "=", "2", ",", "pad", "=", "__unique", ")", ":", "assert", "n", ">", "0", "# ensure it doesn't loop forever", "if", "pad", "is", "not", "__unique", ":", "it", "=", "chain", "(", "iterable", ",", "(", "pad", ...
r"""Iterate `n`-wise (default pairwise) over `iter`. Examples: >>> for (first, last) in group("Akira Kurosawa John Ford".split()): ... print "given name: %s surname: %s" % (first, last) ... given name: Akira surname: Kurosawa given name: John surname: Ford >>> >>> # both contain th...
[ "r", "Iterate", "n", "-", "wise", "(", "default", "pairwise", ")", "over", "iter", ".", "Examples", ":" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L756-L780
ewiger/mlab
src/mlab/awmstools.py
iterate
def iterate(f, n=None, last=__unique): """ >>> list(iterate(lambda x:x//2)(128)) [128, 64, 32, 16, 8, 4, 2, 1, 0] >>> list(iterate(lambda x:x//2, n=2)(128)) [128, 64] """ if n is not None: def funciter(start): for i in xrange(n): yield start; start = f(start) else: ...
python
def iterate(f, n=None, last=__unique): """ >>> list(iterate(lambda x:x//2)(128)) [128, 64, 32, 16, 8, 4, 2, 1, 0] >>> list(iterate(lambda x:x//2, n=2)(128)) [128, 64] """ if n is not None: def funciter(start): for i in xrange(n): yield start; start = f(start) else: ...
[ "def", "iterate", "(", "f", ",", "n", "=", "None", ",", "last", "=", "__unique", ")", ":", "if", "n", "is", "not", "None", ":", "def", "funciter", "(", "start", ")", ":", "for", "i", "in", "xrange", "(", "n", ")", ":", "yield", "start", "start"...
>>> list(iterate(lambda x:x//2)(128)) [128, 64, 32, 16, 8, 4, 2, 1, 0] >>> list(iterate(lambda x:x//2, n=2)(128)) [128, 64]
[ ">>>", "list", "(", "iterate", "(", "lambda", "x", ":", "x", "//", "2", ")", "(", "128", "))", "[", "128", "64", "32", "16", "8", "4", "2", "1", "0", "]", ">>>", "list", "(", "iterate", "(", "lambda", "x", ":", "x", "//", "2", "n", "=", "...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L782-L799
ewiger/mlab
src/mlab/awmstools.py
dropwhilenot
def dropwhilenot(func, iterable): """ >>> list(dropwhilenot(lambda x:x==3, range(10))) [3, 4, 5, 6, 7, 8, 9] """ iterable = iter(iterable) for x in iterable: if func(x): break else: return yield x for x in iterable: yield x
python
def dropwhilenot(func, iterable): """ >>> list(dropwhilenot(lambda x:x==3, range(10))) [3, 4, 5, 6, 7, 8, 9] """ iterable = iter(iterable) for x in iterable: if func(x): break else: return yield x for x in iterable: yield x
[ "def", "dropwhilenot", "(", "func", ",", "iterable", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "for", "x", "in", "iterable", ":", "if", "func", "(", "x", ")", ":", "break", "else", ":", "return", "yield", "x", "for", "x", "in", "iter...
>>> list(dropwhilenot(lambda x:x==3, range(10))) [3, 4, 5, 6, 7, 8, 9]
[ ">>>", "list", "(", "dropwhilenot", "(", "lambda", "x", ":", "x", "==", "3", "range", "(", "10", ")))", "[", "3", "4", "5", "6", "7", "8", "9", "]" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L802-L813
ewiger/mlab
src/mlab/awmstools.py
stretch
def stretch(iterable, n=2): r"""Repeat each item in `iterable` `n` times. Example: >>> list(stretch(range(3), 2)) [0, 0, 1, 1, 2, 2] """ times = range(n) for item in iterable: for i in times: yield item
python
def stretch(iterable, n=2): r"""Repeat each item in `iterable` `n` times. Example: >>> list(stretch(range(3), 2)) [0, 0, 1, 1, 2, 2] """ times = range(n) for item in iterable: for i in times: yield item
[ "def", "stretch", "(", "iterable", ",", "n", "=", "2", ")", ":", "times", "=", "range", "(", "n", ")", "for", "item", "in", "iterable", ":", "for", "i", "in", "times", ":", "yield", "item" ]
r"""Repeat each item in `iterable` `n` times. Example: >>> list(stretch(range(3), 2)) [0, 0, 1, 1, 2, 2]
[ "r", "Repeat", "each", "item", "in", "iterable", "n", "times", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L816-L826
ewiger/mlab
src/mlab/awmstools.py
splitAt
def splitAt(iterable, indices): r"""Yield chunks of `iterable`, split at the points in `indices`: >>> [l for l in splitAt(range(10), [2,5])] [[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]] splits past the length of `iterable` are ignored: >>> [l for l in splitAt(range(10), [2,5,10])] [[0, 1], [2, 3, 4],...
python
def splitAt(iterable, indices): r"""Yield chunks of `iterable`, split at the points in `indices`: >>> [l for l in splitAt(range(10), [2,5])] [[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]] splits past the length of `iterable` are ignored: >>> [l for l in splitAt(range(10), [2,5,10])] [[0, 1], [2, 3, 4],...
[ "def", "splitAt", "(", "iterable", ",", "indices", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "now", "=", "0", "for", "to", "in", "indices", ":", "try", ":", "res", "=", "[", "]", "for", "i", "in", "range", "(", "now", ",", "to", ...
r"""Yield chunks of `iterable`, split at the points in `indices`: >>> [l for l in splitAt(range(10), [2,5])] [[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]] splits past the length of `iterable` are ignored: >>> [l for l in splitAt(range(10), [2,5,10])] [[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
[ "r", "Yield", "chunks", "of", "iterable", "split", "at", "the", "points", "in", "indices", ":" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L829-L852
ewiger/mlab
src/mlab/awmstools.py
update
def update(d, e): """Return a copy of dict `d` updated with dict `e`.""" res = copy.copy(d) res.update(e) return res
python
def update(d, e): """Return a copy of dict `d` updated with dict `e`.""" res = copy.copy(d) res.update(e) return res
[ "def", "update", "(", "d", ",", "e", ")", ":", "res", "=", "copy", ".", "copy", "(", "d", ")", "res", ".", "update", "(", "e", ")", "return", "res" ]
Return a copy of dict `d` updated with dict `e`.
[ "Return", "a", "copy", "of", "dict", "d", "updated", "with", "dict", "e", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L875-L879
ewiger/mlab
src/mlab/awmstools.py
invertDict
def invertDict(d, allowManyToOne=False): r"""Return an inverted version of dict `d`, so that values become keys and vice versa. If multiple keys in `d` have the same value an error is raised, unless `allowManyToOne` is true, in which case one of those key-value pairs is chosen at random for the inversio...
python
def invertDict(d, allowManyToOne=False): r"""Return an inverted version of dict `d`, so that values become keys and vice versa. If multiple keys in `d` have the same value an error is raised, unless `allowManyToOne` is true, in which case one of those key-value pairs is chosen at random for the inversio...
[ "def", "invertDict", "(", "d", ",", "allowManyToOne", "=", "False", ")", ":", "res", "=", "dict", "(", "izip", "(", "d", ".", "itervalues", "(", ")", ",", "d", ".", "iterkeys", "(", ")", ")", ")", "if", "not", "allowManyToOne", "and", "len", "(", ...
r"""Return an inverted version of dict `d`, so that values become keys and vice versa. If multiple keys in `d` have the same value an error is raised, unless `allowManyToOne` is true, in which case one of those key-value pairs is chosen at random for the inversion. Examples: >>> invertDict({1: 2, ...
[ "r", "Return", "an", "inverted", "version", "of", "dict", "d", "so", "that", "values", "become", "keys", "and", "vice", "versa", ".", "If", "multiple", "keys", "in", "d", "have", "the", "same", "value", "an", "error", "is", "raised", "unless", "allowMany...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L881-L901
ewiger/mlab
src/mlab/awmstools.py
iflatten
def iflatten(seq, isSeq=isSeq): r"""Like `flatten` but lazy.""" for elt in seq: if isSeq(elt): for x in iflatten(elt, isSeq): yield x else: yield elt
python
def iflatten(seq, isSeq=isSeq): r"""Like `flatten` but lazy.""" for elt in seq: if isSeq(elt): for x in iflatten(elt, isSeq): yield x else: yield elt
[ "def", "iflatten", "(", "seq", ",", "isSeq", "=", "isSeq", ")", ":", "for", "elt", "in", "seq", ":", "if", "isSeq", "(", "elt", ")", ":", "for", "x", "in", "iflatten", "(", "elt", ",", "isSeq", ")", ":", "yield", "x", "else", ":", "yield", "elt...
r"""Like `flatten` but lazy.
[ "r", "Like", "flatten", "but", "lazy", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L907-L914
ewiger/mlab
src/mlab/awmstools.py
flatten
def flatten(seq, isSeq=isSeq): r"""Returns a flattened version of a sequence `seq` as a `list`. Parameters: - `seq`: The sequence to be flattened (any iterable). - `isSeq`: The function called to determine whether something is a sequence (default: `isSeq`). *Beware that this function should ...
python
def flatten(seq, isSeq=isSeq): r"""Returns a flattened version of a sequence `seq` as a `list`. Parameters: - `seq`: The sequence to be flattened (any iterable). - `isSeq`: The function called to determine whether something is a sequence (default: `isSeq`). *Beware that this function should ...
[ "def", "flatten", "(", "seq", ",", "isSeq", "=", "isSeq", ")", ":", "return", "[", "a", "for", "elt", "in", "seq", "for", "a", "in", "(", "isSeq", "(", "elt", ")", "and", "flatten", "(", "elt", ",", "isSeq", ")", "or", "[", "elt", "]", ")", "...
r"""Returns a flattened version of a sequence `seq` as a `list`. Parameters: - `seq`: The sequence to be flattened (any iterable). - `isSeq`: The function called to determine whether something is a sequence (default: `isSeq`). *Beware that this function should **never** test positive for ...
[ "r", "Returns", "a", "flattened", "version", "of", "a", "sequence", "seq", "as", "a", "list", ".", "Parameters", ":" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L929-L955
ewiger/mlab
src/mlab/awmstools.py
positionIf
def positionIf(pred, seq): """ >>> positionIf(lambda x: x > 3, range(10)) 4 """ for i,e in enumerate(seq): if pred(e): return i return -1
python
def positionIf(pred, seq): """ >>> positionIf(lambda x: x > 3, range(10)) 4 """ for i,e in enumerate(seq): if pred(e): return i return -1
[ "def", "positionIf", "(", "pred", ",", "seq", ")", ":", "for", "i", ",", "e", "in", "enumerate", "(", "seq", ")", ":", "if", "pred", "(", "e", ")", ":", "return", "i", "return", "-", "1" ]
>>> positionIf(lambda x: x > 3, range(10)) 4
[ ">>>", "positionIf", "(", "lambda", "x", ":", "x", ">", "3", "range", "(", "10", "))", "4" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L969-L977
ewiger/mlab
src/mlab/awmstools.py
union
def union(seq1=(), *seqs): r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random. Examples: >>> union() [] >>> union([1,2,3]) [1, 2, 3] >>> union([1,2,3], {1:2, 5:1}) [1, 2, 3, 5] >>> union((1,2,3), ['a'], "bcd") ['a', 1, 2, 3, 'd', 'b', 'c'] >>> un...
python
def union(seq1=(), *seqs): r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random. Examples: >>> union() [] >>> union([1,2,3]) [1, 2, 3] >>> union([1,2,3], {1:2, 5:1}) [1, 2, 3, 5] >>> union((1,2,3), ['a'], "bcd") ['a', 1, 2, 3, 'd', 'b', 'c'] >>> un...
[ "def", "union", "(", "seq1", "=", "(", ")", ",", "*", "seqs", ")", ":", "if", "not", "seqs", ":", "return", "list", "(", "seq1", ")", "res", "=", "set", "(", "seq1", ")", "for", "seq", "in", "seqs", ":", "res", ".", "update", "(", "set", "(",...
r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random. Examples: >>> union() [] >>> union([1,2,3]) [1, 2, 3] >>> union([1,2,3], {1:2, 5:1}) [1, 2, 3, 5] >>> union((1,2,3), ['a'], "bcd") ['a', 1, 2, 3, 'd', 'b', 'c'] >>> union([1,2,3], iter([0,1,1,1])) ...
[ "r", "Return", "the", "set", "union", "of", "seq1", "and", "seqs", "duplicates", "removed", "order", "random", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L981-L1001
ewiger/mlab
src/mlab/awmstools.py
without
def without(seq1, seq2): r"""Return a list with all elements in `seq2` removed from `seq1`, order preserved. Examples: >>> without([1,2,3,1,2], [1]) [2, 3, 2] """ if isSet(seq2): d2 = seq2 else: d2 = set(seq2) return [elt for elt in seq1 if elt not in d2]
python
def without(seq1, seq2): r"""Return a list with all elements in `seq2` removed from `seq1`, order preserved. Examples: >>> without([1,2,3,1,2], [1]) [2, 3, 2] """ if isSet(seq2): d2 = seq2 else: d2 = set(seq2) return [elt for elt in seq1 if elt not in d2]
[ "def", "without", "(", "seq1", ",", "seq2", ")", ":", "if", "isSet", "(", "seq2", ")", ":", "d2", "=", "seq2", "else", ":", "d2", "=", "set", "(", "seq2", ")", "return", "[", "elt", "for", "elt", "in", "seq1", "if", "elt", "not", "in", "d2", ...
r"""Return a list with all elements in `seq2` removed from `seq1`, order preserved. Examples: >>> without([1,2,3,1,2], [1]) [2, 3, 2]
[ "r", "Return", "a", "list", "with", "all", "elements", "in", "seq2", "removed", "from", "seq1", "order", "preserved", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1011-L1022
ewiger/mlab
src/mlab/awmstools.py
some
def some(predicate, *seqs): """ >>> some(lambda x: x, [0, False, None]) False >>> some(lambda x: x, [None, 0, 2, 3]) 2 >>> some(operator.eq, [0,1,2], [2,1,0]) True >>> some(operator.eq, [1,2], [2,1]) False """ try: if len(seqs) == 1: return ifilter(bool,imap(predicate...
python
def some(predicate, *seqs): """ >>> some(lambda x: x, [0, False, None]) False >>> some(lambda x: x, [None, 0, 2, 3]) 2 >>> some(operator.eq, [0,1,2], [2,1,0]) True >>> some(operator.eq, [1,2], [2,1]) False """ try: if len(seqs) == 1: return ifilter(bool,imap(predicate...
[ "def", "some", "(", "predicate", ",", "*", "seqs", ")", ":", "try", ":", "if", "len", "(", "seqs", ")", "==", "1", ":", "return", "ifilter", "(", "bool", ",", "imap", "(", "predicate", ",", "seqs", "[", "0", "]", ")", ")", ".", "next", "(", "...
>>> some(lambda x: x, [0, False, None]) False >>> some(lambda x: x, [None, 0, 2, 3]) 2 >>> some(operator.eq, [0,1,2], [2,1,0]) True >>> some(operator.eq, [1,2], [2,1]) False
[ ">>>", "some", "(", "lambda", "x", ":", "x", "[", "0", "False", "None", "]", ")", "False", ">>>", "some", "(", "lambda", "x", ":", "x", "[", "None", "0", "2", "3", "]", ")", "2", ">>>", "some", "(", "operator", ".", "eq", "[", "0", "1", "2"...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1037-L1051
ewiger/mlab
src/mlab/awmstools.py
every
def every(predicate, *iterables): r"""Like `some`, but only returns `True` if all the elements of `iterables` satisfy `predicate`. Examples: >>> every(bool, []) True >>> every(bool, [0]) False >>> every(bool, [1,1]) True >>> every(operator.eq, [1,2,3],[1,2]) True >>> eve...
python
def every(predicate, *iterables): r"""Like `some`, but only returns `True` if all the elements of `iterables` satisfy `predicate`. Examples: >>> every(bool, []) True >>> every(bool, [0]) False >>> every(bool, [1,1]) True >>> every(operator.eq, [1,2,3],[1,2]) True >>> eve...
[ "def", "every", "(", "predicate", ",", "*", "iterables", ")", ":", "try", ":", "if", "len", "(", "iterables", ")", "==", "1", ":", "ifilterfalse", "(", "predicate", ",", "iterables", "[", "0", "]", ")", ".", "next", "(", ")", "else", ":", "ifilterf...
r"""Like `some`, but only returns `True` if all the elements of `iterables` satisfy `predicate`. Examples: >>> every(bool, []) True >>> every(bool, [0]) False >>> every(bool, [1,1]) True >>> every(operator.eq, [1,2,3],[1,2]) True >>> every(operator.eq, [1,2,3],[0,2]) Fal...
[ "r", "Like", "some", "but", "only", "returns", "True", "if", "all", "the", "elements", "of", "iterables", "satisfy", "predicate", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1053-L1073
ewiger/mlab
src/mlab/awmstools.py
nTimes
def nTimes(n, f, *args, **kwargs): r"""Call `f` `n` times with `args` and `kwargs`. Useful e.g. for simplistic timing. Examples: >>> nTimes(3, sys.stdout.write, 'hallo\n') hallo hallo hallo """ for i in xrange(n): f(*args, **kwargs)
python
def nTimes(n, f, *args, **kwargs): r"""Call `f` `n` times with `args` and `kwargs`. Useful e.g. for simplistic timing. Examples: >>> nTimes(3, sys.stdout.write, 'hallo\n') hallo hallo hallo """ for i in xrange(n): f(*args, **kwargs)
[ "def", "nTimes", "(", "n", ",", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "i", "in", "xrange", "(", "n", ")", ":", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
r"""Call `f` `n` times with `args` and `kwargs`. Useful e.g. for simplistic timing. Examples: >>> nTimes(3, sys.stdout.write, 'hallo\n') hallo hallo hallo
[ "r", "Call", "f", "n", "times", "with", "args", "and", "kwargs", ".", "Useful", "e", ".", "g", ".", "for", "simplistic", "timing", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1082-L1094
ewiger/mlab
src/mlab/awmstools.py
timeCall
def timeCall(*funcAndArgs, **kwargs): r"""Return the time (in ms) it takes to call a function (the first argument) with the remaining arguments and `kwargs`. Examples: To find out how long ``func('foo', spam=1)`` takes to execute, do: ``timeCall(func, foo, spam=1)`` """ func, args = func...
python
def timeCall(*funcAndArgs, **kwargs): r"""Return the time (in ms) it takes to call a function (the first argument) with the remaining arguments and `kwargs`. Examples: To find out how long ``func('foo', spam=1)`` takes to execute, do: ``timeCall(func, foo, spam=1)`` """ func, args = func...
[ "def", "timeCall", "(", "*", "funcAndArgs", ",", "*", "*", "kwargs", ")", ":", "func", ",", "args", "=", "funcAndArgs", "[", "0", "]", ",", "funcAndArgs", "[", "1", ":", "]", "start", "=", "time", ".", "time", "(", ")", "func", "(", "*", "args", ...
r"""Return the time (in ms) it takes to call a function (the first argument) with the remaining arguments and `kwargs`. Examples: To find out how long ``func('foo', spam=1)`` takes to execute, do: ``timeCall(func, foo, spam=1)``
[ "r", "Return", "the", "time", "(", "in", "ms", ")", "it", "takes", "to", "call", "a", "function", "(", "the", "first", "argument", ")", "with", "the", "remaining", "arguments", "and", "kwargs", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1097-L1111
ewiger/mlab
src/mlab/awmstools.py
replaceStrs
def replaceStrs(s, *args): r"""Replace all ``(frm, to)`` tuples in `args` in string `s`. >>> replaceStrs("nothing is better than warm beer", ... ('nothing','warm beer'), ('warm beer','nothing')) 'warm beer is better than nothing' """ if args == (): return s mapping = dict((frm,...
python
def replaceStrs(s, *args): r"""Replace all ``(frm, to)`` tuples in `args` in string `s`. >>> replaceStrs("nothing is better than warm beer", ... ('nothing','warm beer'), ('warm beer','nothing')) 'warm beer is better than nothing' """ if args == (): return s mapping = dict((frm,...
[ "def", "replaceStrs", "(", "s", ",", "*", "args", ")", ":", "if", "args", "==", "(", ")", ":", "return", "s", "mapping", "=", "dict", "(", "(", "frm", ",", "to", ")", "for", "frm", ",", "to", "in", "args", ")", "return", "re", ".", "sub", "("...
r"""Replace all ``(frm, to)`` tuples in `args` in string `s`. >>> replaceStrs("nothing is better than warm beer", ... ('nothing','warm beer'), ('warm beer','nothing')) 'warm beer is better than nothing'
[ "r", "Replace", "all", "(", "frm", "to", ")", "tuples", "in", "args", "in", "string", "s", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1148-L1159
ewiger/mlab
src/mlab/awmstools.py
unescape
def unescape(s): r"""Inverse of `escape`. >>> unescape(r'\x41\n\x42\n\x43') 'A\nB\nC' >>> unescape(r'\u86c7') u'\u86c7' >>> unescape(u'ah') u'ah' """ if re.search(r'(?<!\\)\\(\\\\)*[uU]', s) or isinstance(s, unicode): return unescapeUnicode(s) else: return unescap...
python
def unescape(s): r"""Inverse of `escape`. >>> unescape(r'\x41\n\x42\n\x43') 'A\nB\nC' >>> unescape(r'\u86c7') u'\u86c7' >>> unescape(u'ah') u'ah' """ if re.search(r'(?<!\\)\\(\\\\)*[uU]', s) or isinstance(s, unicode): return unescapeUnicode(s) else: return unescap...
[ "def", "unescape", "(", "s", ")", ":", "if", "re", ".", "search", "(", "r'(?<!\\\\)\\\\(\\\\\\\\)*[uU]'", ",", "s", ")", "or", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "unescapeUnicode", "(", "s", ")", "else", ":", "return", "unescapeA...
r"""Inverse of `escape`. >>> unescape(r'\x41\n\x42\n\x43') 'A\nB\nC' >>> unescape(r'\u86c7') u'\u86c7' >>> unescape(u'ah') u'ah'
[ "r", "Inverse", "of", "escape", ".", ">>>", "unescape", "(", "r", "\\", "x41", "\\", "n", "\\", "x42", "\\", "n", "\\", "x43", ")", "A", "\\", "nB", "\\", "nC", ">>>", "unescape", "(", "r", "\\", "u86c7", ")", "u", "\\", "u86c7", ">>>", "unesca...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1178-L1190
ewiger/mlab
src/mlab/awmstools.py
lineAndColumnAt
def lineAndColumnAt(s, pos): r"""Return line and column of `pos` (0-based!) in `s`. Lines start with 1, columns with 0. Examples: >>> lineAndColumnAt("0123\n56", 5) (2, 0) >>> lineAndColumnAt("0123\n56", 6) (2, 1) >>> lineAndColumnAt("0123\n56", 0) (1, 0) """ if pos >= len(...
python
def lineAndColumnAt(s, pos): r"""Return line and column of `pos` (0-based!) in `s`. Lines start with 1, columns with 0. Examples: >>> lineAndColumnAt("0123\n56", 5) (2, 0) >>> lineAndColumnAt("0123\n56", 6) (2, 1) >>> lineAndColumnAt("0123\n56", 0) (1, 0) """ if pos >= len(...
[ "def", "lineAndColumnAt", "(", "s", ",", "pos", ")", ":", "if", "pos", ">=", "len", "(", "s", ")", ":", "raise", "IndexError", "(", "\"`pos` %d not in string\"", "%", "pos", ")", "# *don't* count last '\\n', if it is at pos!", "line", "=", "s", ".", "count", ...
r"""Return line and column of `pos` (0-based!) in `s`. Lines start with 1, columns with 0. Examples: >>> lineAndColumnAt("0123\n56", 5) (2, 0) >>> lineAndColumnAt("0123\n56", 6) (2, 1) >>> lineAndColumnAt("0123\n56", 0) (1, 0)
[ "r", "Return", "line", "and", "column", "of", "pos", "(", "0", "-", "based!", ")", "in", "s", ".", "Lines", "start", "with", "1", "columns", "with", "0", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1198-L1218
ewiger/mlab
src/mlab/awmstools.py
prin
def prin(*args, **kwargs): r"""Like ``print``, but a function. I.e. prints out all arguments as ``print`` would do. Specify output stream like this:: print('ERROR', `out="sys.stderr"``). """ print >> kwargs.get('out',None), " ".join([str(arg) for arg in args])
python
def prin(*args, **kwargs): r"""Like ``print``, but a function. I.e. prints out all arguments as ``print`` would do. Specify output stream like this:: print('ERROR', `out="sys.stderr"``). """ print >> kwargs.get('out',None), " ".join([str(arg) for arg in args])
[ "def", "prin", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", ">>", "kwargs", ".", "get", "(", "'out'", ",", "None", ")", ",", "\" \"", ".", "join", "(", "[", "str", "(", "arg", ")", "for", "arg", "in", "args", "]", ")" ]
r"""Like ``print``, but a function. I.e. prints out all arguments as ``print`` would do. Specify output stream like this:: print('ERROR', `out="sys.stderr"``).
[ "r", "Like", "print", "but", "a", "function", ".", "I", ".", "e", ".", "prints", "out", "all", "arguments", "as", "print", "would", "do", ".", "Specify", "output", "stream", "like", "this", "::" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1222-L1229
ewiger/mlab
src/mlab/awmstools.py
fitString
def fitString(s, maxCol=79, newlineReplacement=None): r"""Truncate `s` if necessary to fit into a line of width `maxCol` (default: 79), also replacing newlines with `newlineReplacement` (default `None`: in which case everything after the first newline is simply discarded). Examples: >>> fitStr...
python
def fitString(s, maxCol=79, newlineReplacement=None): r"""Truncate `s` if necessary to fit into a line of width `maxCol` (default: 79), also replacing newlines with `newlineReplacement` (default `None`: in which case everything after the first newline is simply discarded). Examples: >>> fitStr...
[ "def", "fitString", "(", "s", ",", "maxCol", "=", "79", ",", "newlineReplacement", "=", "None", ")", ":", "assert", "isString", "(", "s", ")", "if", "'\\n'", "in", "s", ":", "if", "newlineReplacement", "is", "None", ":", "s", "=", "s", "[", ":", "s...
r"""Truncate `s` if necessary to fit into a line of width `maxCol` (default: 79), also replacing newlines with `newlineReplacement` (default `None`: in which case everything after the first newline is simply discarded). Examples: >>> fitString('12345', maxCol=5) '12345' >>> fitString('1234...
[ "r", "Truncate", "s", "if", "necessary", "to", "fit", "into", "a", "line", "of", "width", "maxCol", "(", "default", ":", "79", ")", "also", "replacing", "newlines", "with", "newlineReplacement", "(", "default", "None", ":", "in", "which", "case", "everythi...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1249-L1274
ewiger/mlab
src/mlab/awmstools.py
saveVars
def saveVars(filename, varNamesStr, outOf=None, **opts): r"""Pickle name and value of all those variables in `outOf` (default: all global variables (as seen from the caller)) that are named in `varNamesStr` into a file called `filename` (if no extension is given, '.bpickle' is appended). Overwrites file...
python
def saveVars(filename, varNamesStr, outOf=None, **opts): r"""Pickle name and value of all those variables in `outOf` (default: all global variables (as seen from the caller)) that are named in `varNamesStr` into a file called `filename` (if no extension is given, '.bpickle' is appended). Overwrites file...
[ "def", "saveVars", "(", "filename", ",", "varNamesStr", ",", "outOf", "=", "None", ",", "*", "*", "opts", ")", ":", "filename", ",", "varnames", ",", "outOf", "=", "__saveVarsHelper", "(", "filename", ",", "varNamesStr", ",", "outOf", ",", "*", "*", "o...
r"""Pickle name and value of all those variables in `outOf` (default: all global variables (as seen from the caller)) that are named in `varNamesStr` into a file called `filename` (if no extension is given, '.bpickle' is appended). Overwrites file without asking, unless you specify `overwrite=0`. Load a...
[ "r", "Pickle", "name", "and", "value", "of", "all", "those", "variables", "in", "outOf", "(", "default", ":", "all", "global", "variables", "(", "as", "seen", "from", "the", "caller", "))", "that", "are", "named", "in", "varNamesStr", "into", "a", "file"...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1305-L1328
ewiger/mlab
src/mlab/awmstools.py
addVars
def addVars(filename, varNamesStr, outOf=None): r"""Like `saveVars`, but appends additional variables to file.""" filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf) f = None try: f = open(filename, "rb") h = cPickle.load(f) f.close() h.update(dict...
python
def addVars(filename, varNamesStr, outOf=None): r"""Like `saveVars`, but appends additional variables to file.""" filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf) f = None try: f = open(filename, "rb") h = cPickle.load(f) f.close() h.update(dict...
[ "def", "addVars", "(", "filename", ",", "varNamesStr", ",", "outOf", "=", "None", ")", ":", "filename", ",", "varnames", ",", "outOf", "=", "__saveVarsHelper", "(", "filename", ",", "varNamesStr", ",", "outOf", ")", "f", "=", "None", "try", ":", "f", "...
r"""Like `saveVars`, but appends additional variables to file.
[ "r", "Like", "saveVars", "but", "appends", "additional", "variables", "to", "file", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1336-L1349
ewiger/mlab
src/mlab/awmstools.py
loadDict
def loadDict(filename): """Return the variables pickled pickled into `filename` with `saveVars` as a dict.""" filename = os.path.expanduser(filename) if not splitext(filename)[1]: filename += ".bpickle" f = None try: f = open(filename, "rb") varH = cPickle.load(f) finally: ...
python
def loadDict(filename): """Return the variables pickled pickled into `filename` with `saveVars` as a dict.""" filename = os.path.expanduser(filename) if not splitext(filename)[1]: filename += ".bpickle" f = None try: f = open(filename, "rb") varH = cPickle.load(f) finally: ...
[ "def", "loadDict", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "if", "not", "splitext", "(", "filename", ")", "[", "1", "]", ":", "filename", "+=", "\".bpickle\"", "f", "=", "None", "try", "...
Return the variables pickled pickled into `filename` with `saveVars` as a dict.
[ "Return", "the", "variables", "pickled", "pickled", "into", "filename", "with", "saveVars", "as", "a", "dict", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1351-L1362
ewiger/mlab
src/mlab/awmstools.py
loadVars
def loadVars(filename, ask=True, into=None, only=None): r"""Load variables pickled with `saveVars`. Parameters: - `ask`: If `True` then don't overwrite existing variables without asking. - `only`: A list to limit the variables to or `None`. - `into`: The dictionary the ...
python
def loadVars(filename, ask=True, into=None, only=None): r"""Load variables pickled with `saveVars`. Parameters: - `ask`: If `True` then don't overwrite existing variables without asking. - `only`: A list to limit the variables to or `None`. - `into`: The dictionary the ...
[ "def", "loadVars", "(", "filename", ",", "ask", "=", "True", ",", "into", "=", "None", ",", "only", "=", "None", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "if", "into", "is", "None", ":", "into", "=", ...
r"""Load variables pickled with `saveVars`. Parameters: - `ask`: If `True` then don't overwrite existing variables without asking. - `only`: A list to limit the variables to or `None`. - `into`: The dictionary the variables should be loaded into (defaults ...
[ "r", "Load", "variables", "pickled", "with", "saveVars", ".", "Parameters", ":" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1364-L1393
ewiger/mlab
src/mlab/awmstools.py
runInfo
def runInfo(prog=None,vers=None,date=None,user=None,dir=None,args=None): r"""Create a short info string detailing how a program was invoked. This is meant to be added to a history comment field of a data file were it is important to keep track of what programs modified it and how. !!!:`args` should be ...
python
def runInfo(prog=None,vers=None,date=None,user=None,dir=None,args=None): r"""Create a short info string detailing how a program was invoked. This is meant to be added to a history comment field of a data file were it is important to keep track of what programs modified it and how. !!!:`args` should be ...
[ "def", "runInfo", "(", "prog", "=", "None", ",", "vers", "=", "None", ",", "date", "=", "None", ",", "user", "=", "None", ",", "dir", "=", "None", ",", "args", "=", "None", ")", ":", "return", "\"%(prog)s %(vers)s;\"", "\" run %(date)s by %(usr)s in %(dir)...
r"""Create a short info string detailing how a program was invoked. This is meant to be added to a history comment field of a data file were it is important to keep track of what programs modified it and how. !!!:`args` should be a **``list``** not a ``str``.
[ "r", "Create", "a", "short", "info", "string", "detailing", "how", "a", "program", "was", "invoked", ".", "This", "is", "meant", "to", "be", "added", "to", "a", "history", "comment", "field", "of", "a", "data", "file", "were", "it", "is", "important", ...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1401-L1415
ewiger/mlab
src/mlab/awmstools.py
makePrintReturner
def makePrintReturner(pre="", post="" ,out=None): r"""Creates functions that print out their argument, (between optional `pre` and `post` strings) and return it unmodified. This is usefull for debugging e.g. parts of expressions, without having to modify the behavior of the program. Example: >...
python
def makePrintReturner(pre="", post="" ,out=None): r"""Creates functions that print out their argument, (between optional `pre` and `post` strings) and return it unmodified. This is usefull for debugging e.g. parts of expressions, without having to modify the behavior of the program. Example: >...
[ "def", "makePrintReturner", "(", "pre", "=", "\"\"", ",", "post", "=", "\"\"", ",", "out", "=", "None", ")", ":", "def", "printReturner", "(", "arg", ")", ":", "myArgs", "=", "[", "pre", ",", "arg", ",", "post", "]", "prin", "(", "*", "myArgs", "...
r"""Creates functions that print out their argument, (between optional `pre` and `post` strings) and return it unmodified. This is usefull for debugging e.g. parts of expressions, without having to modify the behavior of the program. Example: >>> makePrintReturner(pre="The value is:", post="[retur...
[ "r", "Creates", "functions", "that", "print", "out", "their", "argument", "(", "between", "optional", "pre", "and", "post", "strings", ")", "and", "return", "it", "unmodified", ".", "This", "is", "usefull", "for", "debugging", "e", ".", "g", ".", "parts", ...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1543-L1560
ewiger/mlab
src/mlab/awmstools.py
asVerboseContainer
def asVerboseContainer(cont, onGet=None, onSet=None, onDel=None): """Returns a 'verbose' version of container instance `cont`, that will execute `onGet`, `onSet` and `onDel` (if not `None`) every time __getitem__, __setitem__ and __delitem__ are called, passing `self`, `key` (and `value` in the...
python
def asVerboseContainer(cont, onGet=None, onSet=None, onDel=None): """Returns a 'verbose' version of container instance `cont`, that will execute `onGet`, `onSet` and `onDel` (if not `None`) every time __getitem__, __setitem__ and __delitem__ are called, passing `self`, `key` (and `value` in the...
[ "def", "asVerboseContainer", "(", "cont", ",", "onGet", "=", "None", ",", "onSet", "=", "None", ",", "onDel", "=", "None", ")", ":", "class", "VerboseContainer", "(", "type", "(", "cont", ")", ")", ":", "if", "onGet", ":", "def", "__getitem__", "(", ...
Returns a 'verbose' version of container instance `cont`, that will execute `onGet`, `onSet` and `onDel` (if not `None`) every time __getitem__, __setitem__ and __delitem__ are called, passing `self`, `key` (and `value` in the case of set). E.g: >>> l = [1,2,3] >>> l = asVerboseConta...
[ "Returns", "a", "verbose", "version", "of", "container", "instance", "cont", "that", "will", "execute", "onGet", "onSet", "and", "onDel", "(", "if", "not", "None", ")", "every", "time", "__getitem__", "__setitem__", "and", "__delitem__", "are", "called", "pass...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1599-L1638
ewiger/mlab
src/mlab/awmstools.py
mkRepr
def mkRepr(instance, *argls, **kwargs): r"""Convinience function to implement ``__repr__``. `kwargs` values are ``repr`` ed. Special behavior for ``instance=None``: just the arguments are formatted. Example: >>> class Thing: ... def __init__(self, color, shape, taste=None):...
python
def mkRepr(instance, *argls, **kwargs): r"""Convinience function to implement ``__repr__``. `kwargs` values are ``repr`` ed. Special behavior for ``instance=None``: just the arguments are formatted. Example: >>> class Thing: ... def __init__(self, color, shape, taste=None):...
[ "def", "mkRepr", "(", "instance", ",", "*", "argls", ",", "*", "*", "kwargs", ")", ":", "width", "=", "79", "maxIndent", "=", "15", "minIndent", "=", "2", "args", "=", "(", "map", "(", "repr", ",", "argls", ")", "+", "[", "\"%s=%r\"", "%", "(", ...
r"""Convinience function to implement ``__repr__``. `kwargs` values are ``repr`` ed. Special behavior for ``instance=None``: just the arguments are formatted. Example: >>> class Thing: ... def __init__(self, color, shape, taste=None): ... self.color, self.shape,...
[ "r", "Convinience", "function", "to", "implement", "__repr__", ".", "kwargs", "values", "are", "repr", "ed", ".", "Special", "behavior", "for", "instance", "=", "None", ":", "just", "the", "arguments", "are", "formatted", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1724-L1764
ewiger/mlab
src/mlab/awmstools.py
d2attrs
def d2attrs(*args, **kwargs): """Utility function to remove ``**kwargs`` parsing boiler-plate in ``__init__``: >>> kwargs = dict(name='Bill', age=51, income=1e7) >>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self ezstruct(income=10000000.0, name='Bill') >>> ...
python
def d2attrs(*args, **kwargs): """Utility function to remove ``**kwargs`` parsing boiler-plate in ``__init__``: >>> kwargs = dict(name='Bill', age=51, income=1e7) >>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self ezstruct(income=10000000.0, name='Bill') >>> ...
[ "def", "d2attrs", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "(", "d", ",", "self", ")", ",", "args", "=", "args", "[", ":", "2", "]", ",", "args", "[", "2", ":", "]", "if", "args", "[", "0", "]", "==", "'all!'", ":", "assert", ...
Utility function to remove ``**kwargs`` parsing boiler-plate in ``__init__``: >>> kwargs = dict(name='Bill', age=51, income=1e7) >>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self ezstruct(income=10000000.0, name='Bill') >>> self = ezstruct(); d2attrs(kwargs, se...
[ "Utility", "function", "to", "remove", "**", "kwargs", "parsing", "boiler", "-", "plate", "in", "__init__", ":" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1787-L1814
ewiger/mlab
src/mlab/awmstools.py
pairwise
def pairwise(fun, v): """ >>> pairwise(operator.sub, [4,3,2,1,-10]) [1, 1, 1, 11] >>> import numpy >>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10])) array([ 1, 1, 1, 11]) """ if not hasattr(v, 'shape'): return list(ipairwise(fun,v)) else: return fun(v[:-1],v[...
python
def pairwise(fun, v): """ >>> pairwise(operator.sub, [4,3,2,1,-10]) [1, 1, 1, 11] >>> import numpy >>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10])) array([ 1, 1, 1, 11]) """ if not hasattr(v, 'shape'): return list(ipairwise(fun,v)) else: return fun(v[:-1],v[...
[ "def", "pairwise", "(", "fun", ",", "v", ")", ":", "if", "not", "hasattr", "(", "v", ",", "'shape'", ")", ":", "return", "list", "(", "ipairwise", "(", "fun", ",", "v", ")", ")", "else", ":", "return", "fun", "(", "v", "[", ":", "-", "1", "]"...
>>> pairwise(operator.sub, [4,3,2,1,-10]) [1, 1, 1, 11] >>> import numpy >>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10])) array([ 1, 1, 1, 11])
[ ">>>", "pairwise", "(", "operator", ".", "sub", "[", "4", "3", "2", "1", "-", "10", "]", ")", "[", "1", "1", "1", "11", "]", ">>>", "import", "numpy", ">>>", "pairwise", "(", "numpy", ".", "subtract", "numpy", ".", "array", "(", "[", "4", "3", ...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1819-L1830
ewiger/mlab
src/mlab/awmstools.py
argmax
def argmax(iterable, key=None, both=False): """ >>> argmax([4,2,-5]) 0 >>> argmax([4,2,-5], key=abs) 2 >>> argmax([4,2,-5], key=abs, both=True) (2, 5) """ if key is not None: it = imap(key, iterable) else: it = iter(iterable) score, argmax = reduce(max, izip(i...
python
def argmax(iterable, key=None, both=False): """ >>> argmax([4,2,-5]) 0 >>> argmax([4,2,-5], key=abs) 2 >>> argmax([4,2,-5], key=abs, both=True) (2, 5) """ if key is not None: it = imap(key, iterable) else: it = iter(iterable) score, argmax = reduce(max, izip(i...
[ "def", "argmax", "(", "iterable", ",", "key", "=", "None", ",", "both", "=", "False", ")", ":", "if", "key", "is", "not", "None", ":", "it", "=", "imap", "(", "key", ",", "iterable", ")", "else", ":", "it", "=", "iter", "(", "iterable", ")", "s...
>>> argmax([4,2,-5]) 0 >>> argmax([4,2,-5], key=abs) 2 >>> argmax([4,2,-5], key=abs, both=True) (2, 5)
[ ">>>", "argmax", "(", "[", "4", "2", "-", "5", "]", ")", "0", ">>>", "argmax", "(", "[", "4", "2", "-", "5", "]", "key", "=", "abs", ")", "2", ">>>", "argmax", "(", "[", "4", "2", "-", "5", "]", "key", "=", "abs", "both", "=", "True", "...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1846-L1862
ewiger/mlab
src/mlab/awmstools.py
argmin
def argmin(iterable, key=None, both=False): """See `argmax`. """ if key is not None: it = imap(key, iterable) else: it = iter(iterable) score, argmin = reduce(min, izip(it, count())) if both: return argmin, score return argmin
python
def argmin(iterable, key=None, both=False): """See `argmax`. """ if key is not None: it = imap(key, iterable) else: it = iter(iterable) score, argmin = reduce(min, izip(it, count())) if both: return argmin, score return argmin
[ "def", "argmin", "(", "iterable", ",", "key", "=", "None", ",", "both", "=", "False", ")", ":", "if", "key", "is", "not", "None", ":", "it", "=", "imap", "(", "key", ",", "iterable", ")", "else", ":", "it", "=", "iter", "(", "iterable", ")", "s...
See `argmax`.
[ "See", "argmax", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1864-L1874
ewiger/mlab
src/mlab/awmstools.py
isInt
def isInt(num): """Returns true if `num` is (sort of) an integer. >>> isInt(3) == isInt(3.0) == 1 True >>> isInt(3.2) False >>> import numpy >>> isInt(numpy.array(1)) True >>> isInt(numpy.array([1])) False """ try: len(num) # FIXME fails for Numeric but Numeric is...
python
def isInt(num): """Returns true if `num` is (sort of) an integer. >>> isInt(3) == isInt(3.0) == 1 True >>> isInt(3.2) False >>> import numpy >>> isInt(numpy.array(1)) True >>> isInt(numpy.array([1])) False """ try: len(num) # FIXME fails for Numeric but Numeric is...
[ "def", "isInt", "(", "num", ")", ":", "try", ":", "len", "(", "num", ")", "# FIXME fails for Numeric but Numeric is obsolete", "except", ":", "try", ":", "return", "(", "num", "-", "math", ".", "floor", "(", "num", ")", "==", "0", ")", "==", "True", "e...
Returns true if `num` is (sort of) an integer. >>> isInt(3) == isInt(3.0) == 1 True >>> isInt(3.2) False >>> import numpy >>> isInt(numpy.array(1)) True >>> isInt(numpy.array([1])) False
[ "Returns", "true", "if", "num", "is", "(", "sort", "of", ")", "an", "integer", ".", ">>>", "isInt", "(", "3", ")", "==", "isInt", "(", "3", ".", "0", ")", "==", "1", "True", ">>>", "isInt", "(", "3", ".", "2", ")", "False", ">>>", "import", "...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1881-L1899
ewiger/mlab
src/mlab/awmstools.py
mapConcat
def mapConcat(func, *iterables): """Similar to `map` but the instead of collecting the return values of `func` in a list, the items of each return value are instaed collected (so `func` must return an iterable type). Examples: >>> mapConcat(lambda x:[x], [1,2,3]) [1, 2, 3] >>> mapConcat(la...
python
def mapConcat(func, *iterables): """Similar to `map` but the instead of collecting the return values of `func` in a list, the items of each return value are instaed collected (so `func` must return an iterable type). Examples: >>> mapConcat(lambda x:[x], [1,2,3]) [1, 2, 3] >>> mapConcat(la...
[ "def", "mapConcat", "(", "func", ",", "*", "iterables", ")", ":", "return", "[", "e", "for", "l", "in", "imap", "(", "func", ",", "*", "iterables", ")", "for", "e", "in", "l", "]" ]
Similar to `map` but the instead of collecting the return values of `func` in a list, the items of each return value are instaed collected (so `func` must return an iterable type). Examples: >>> mapConcat(lambda x:[x], [1,2,3]) [1, 2, 3] >>> mapConcat(lambda x: [x,str(x)], [1,2,3]) [1, '1'...
[ "Similar", "to", "map", "but", "the", "instead", "of", "collecting", "the", "return", "values", "of", "func", "in", "a", "list", "the", "items", "of", "each", "return", "value", "are", "instaed", "collected", "(", "so", "func", "must", "return", "an", "i...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1917-L1929
ewiger/mlab
src/mlab/awmstools.py
unfold
def unfold(seed, by, last = __unique): """ >>> list(unfold(1234, lambda x: divmod(x,10)))[::-1] [1, 2, 3, 4] >>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1))) 1234 >>> g = unfold(1234, lambda x:divmod(x,10)) >>> reduce((lambda (total,pow),digit:(total...
python
def unfold(seed, by, last = __unique): """ >>> list(unfold(1234, lambda x: divmod(x,10)))[::-1] [1, 2, 3, 4] >>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1))) 1234 >>> g = unfold(1234, lambda x:divmod(x,10)) >>> reduce((lambda (total,pow),digit:(total...
[ "def", "unfold", "(", "seed", ",", "by", ",", "last", "=", "__unique", ")", ":", "while", "True", ":", "seed", ",", "val", "=", "by", "(", "seed", ")", "if", "last", "==", "seed", ":", "return", "last", "=", "seed", "yield", "val" ]
>>> list(unfold(1234, lambda x: divmod(x,10)))[::-1] [1, 2, 3, 4] >>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1))) 1234 >>> g = unfold(1234, lambda x:divmod(x,10)) >>> reduce((lambda (total,pow),digit:(total+pow*digit, 10*pow)), g, (0,1)) (1234, 10000)
[ ">>>", "list", "(", "unfold", "(", "1234", "lambda", "x", ":", "divmod", "(", "x", "10", ")))", "[", "::", "-", "1", "]", "[", "1", "2", "3", "4", "]", ">>>", "sum", "(", "imap", "(", "operator", ".", "mul", "unfold", "(", "1234", "lambda", "...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1935-L1949
ewiger/mlab
src/mlab/awmstools.py
reduceR
def reduceR(f, sequence, initial=__unique): """*R*ight reduce. >>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.) True >>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4) True """ try: rev = reversed(sequence) except TypeError: rev = re...
python
def reduceR(f, sequence, initial=__unique): """*R*ight reduce. >>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.) True >>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4) True """ try: rev = reversed(sequence) except TypeError: rev = re...
[ "def", "reduceR", "(", "f", ",", "sequence", ",", "initial", "=", "__unique", ")", ":", "try", ":", "rev", "=", "reversed", "(", "sequence", ")", "except", "TypeError", ":", "rev", "=", "reversed", "(", "list", "(", "sequence", ")", ")", "if", "initi...
*R*ight reduce. >>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.) True >>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4) True
[ "*", "R", "*", "ight", "reduce", ".", ">>>", "reduceR", "(", "lambda", "x", "y", ":", "x", "/", "y", "[", "1", ".", "2", ".", "3", ".", "4", "]", ")", "==", "1", ".", "/", "(", "2", ".", "/", "(", "3", ".", "/", "4", ".", "))", "==", ...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1951-L1961
ewiger/mlab
src/mlab/awmstools.py
compose
def compose(*funcs): """Compose `funcs` to a single function. >>> compose(operator.abs, operator.add)(-2,-3) 5 >>> compose()('nada') 'nada' >>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2) [1, 2] """ # slightly optimized for most common cases and hence verbose i...
python
def compose(*funcs): """Compose `funcs` to a single function. >>> compose(operator.abs, operator.add)(-2,-3) 5 >>> compose()('nada') 'nada' >>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2) [1, 2] """ # slightly optimized for most common cases and hence verbose i...
[ "def", "compose", "(", "*", "funcs", ")", ":", "# slightly optimized for most common cases and hence verbose", "if", "len", "(", "funcs", ")", "==", "2", ":", "f0", ",", "f1", "=", "funcs", "return", "lambda", "*", "a", ",", "*", "*", "kw", ":", "f0", "(...
Compose `funcs` to a single function. >>> compose(operator.abs, operator.add)(-2,-3) 5 >>> compose()('nada') 'nada' >>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2) [1, 2]
[ "Compose", "funcs", "to", "a", "single", "function", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1964-L1984