repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
klahnakoski/pyLibrary | jx_elasticsearch/meta.py | Snowflake.sorted_query_paths | def sorted_query_paths(self):
"""
RETURN A LIST OF ALL SCHEMA'S IN DEPTH-FIRST TOPOLOGICAL ORDER
"""
return list(reversed(sorted(p[0] for p in self.namespace.alias_to_query_paths.get(self.name)))) | python | def sorted_query_paths(self):
"""
RETURN A LIST OF ALL SCHEMA'S IN DEPTH-FIRST TOPOLOGICAL ORDER
"""
return list(reversed(sorted(p[0] for p in self.namespace.alias_to_query_paths.get(self.name)))) | [
"def",
"sorted_query_paths",
"(",
"self",
")",
":",
"return",
"list",
"(",
"reversed",
"(",
"sorted",
"(",
"p",
"[",
"0",
"]",
"for",
"p",
"in",
"self",
".",
"namespace",
".",
"alias_to_query_paths",
".",
"get",
"(",
"self",
".",
"name",
")",
")",
")... | RETURN A LIST OF ALL SCHEMA'S IN DEPTH-FIRST TOPOLOGICAL ORDER | [
"RETURN",
"A",
"LIST",
"OF",
"ALL",
"SCHEMA",
"S",
"IN",
"DEPTH",
"-",
"FIRST",
"TOPOLOGICAL",
"ORDER"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_elasticsearch/meta.py#L641-L645 |
klahnakoski/pyLibrary | jx_elasticsearch/meta.py | Schema.leaves | def leaves(self, column_name):
"""
:param column_name:
:return: ALL COLUMNS THAT START WITH column_name, NOT INCLUDING DEEPER NESTED COLUMNS
"""
clean_name = unnest_path(column_name)
if clean_name != column_name:
clean_name = column_name
cleaner =... | python | def leaves(self, column_name):
"""
:param column_name:
:return: ALL COLUMNS THAT START WITH column_name, NOT INCLUDING DEEPER NESTED COLUMNS
"""
clean_name = unnest_path(column_name)
if clean_name != column_name:
clean_name = column_name
cleaner =... | [
"def",
"leaves",
"(",
"self",
",",
"column_name",
")",
":",
"clean_name",
"=",
"unnest_path",
"(",
"column_name",
")",
"if",
"clean_name",
"!=",
"column_name",
":",
"clean_name",
"=",
"column_name",
"cleaner",
"=",
"lambda",
"x",
":",
"x",
"else",
":",
"cl... | :param column_name:
:return: ALL COLUMNS THAT START WITH column_name, NOT INCLUDING DEEPER NESTED COLUMNS | [
":",
"param",
"column_name",
":",
":",
"return",
":",
"ALL",
"COLUMNS",
"THAT",
"START",
"WITH",
"column_name",
"NOT",
"INCLUDING",
"DEEPER",
"NESTED",
"COLUMNS"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_elasticsearch/meta.py#L696-L729 |
klahnakoski/pyLibrary | jx_elasticsearch/meta.py | Schema.new_leaves | def new_leaves(self, column_name):
"""
:param column_name:
:return: ALL COLUMNS THAT START WITH column_name, INCLUDING DEEP COLUMNS
"""
column_name = unnest_path(column_name)
columns = self.columns
all_paths = self.snowflake.sorted_query_paths
output = {}... | python | def new_leaves(self, column_name):
"""
:param column_name:
:return: ALL COLUMNS THAT START WITH column_name, INCLUDING DEEP COLUMNS
"""
column_name = unnest_path(column_name)
columns = self.columns
all_paths = self.snowflake.sorted_query_paths
output = {}... | [
"def",
"new_leaves",
"(",
"self",
",",
"column_name",
")",
":",
"column_name",
"=",
"unnest_path",
"(",
"column_name",
")",
"columns",
"=",
"self",
".",
"columns",
"all_paths",
"=",
"self",
".",
"snowflake",
".",
"sorted_query_paths",
"output",
"=",
"{",
"}"... | :param column_name:
:return: ALL COLUMNS THAT START WITH column_name, INCLUDING DEEP COLUMNS | [
":",
"param",
"column_name",
":",
":",
"return",
":",
"ALL",
"COLUMNS",
"THAT",
"START",
"WITH",
"column_name",
"INCLUDING",
"DEEP",
"COLUMNS"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_elasticsearch/meta.py#L731-L762 |
klahnakoski/pyLibrary | jx_elasticsearch/meta.py | Schema.values | def values(self, column_name, exclude_type=STRUCT):
"""
RETURN ALL COLUMNS THAT column_name REFERS TO
"""
column_name = unnest_path(column_name)
columns = self.columns
output = []
for path in self.query_path:
full_path = untype_path(concat_field(path, ... | python | def values(self, column_name, exclude_type=STRUCT):
"""
RETURN ALL COLUMNS THAT column_name REFERS TO
"""
column_name = unnest_path(column_name)
columns = self.columns
output = []
for path in self.query_path:
full_path = untype_path(concat_field(path, ... | [
"def",
"values",
"(",
"self",
",",
"column_name",
",",
"exclude_type",
"=",
"STRUCT",
")",
":",
"column_name",
"=",
"unnest_path",
"(",
"column_name",
")",
"columns",
"=",
"self",
".",
"columns",
"output",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",... | RETURN ALL COLUMNS THAT column_name REFERS TO | [
"RETURN",
"ALL",
"COLUMNS",
"THAT",
"column_name",
"REFERS",
"TO"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_elasticsearch/meta.py#L777-L795 |
klahnakoski/pyLibrary | jx_elasticsearch/meta.py | Schema.map_to_es | def map_to_es(self):
"""
RETURN A MAP FROM THE NAMESPACE TO THE es_column NAME
"""
output = {}
for path in self.query_path:
set_default(
output,
{
k: c.es_column
for c in self.columns
... | python | def map_to_es(self):
"""
RETURN A MAP FROM THE NAMESPACE TO THE es_column NAME
"""
output = {}
for path in self.query_path:
set_default(
output,
{
k: c.es_column
for c in self.columns
... | [
"def",
"map_to_es",
"(",
"self",
")",
":",
"output",
"=",
"{",
"}",
"for",
"path",
"in",
"self",
".",
"query_path",
":",
"set_default",
"(",
"output",
",",
"{",
"k",
":",
"c",
".",
"es_column",
"for",
"c",
"in",
"self",
".",
"columns",
"if",
"c",
... | RETURN A MAP FROM THE NAMESPACE TO THE es_column NAME | [
"RETURN",
"A",
"MAP",
"FROM",
"THE",
"NAMESPACE",
"TO",
"THE",
"es_column",
"NAME"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_elasticsearch/meta.py#L808-L824 |
klahnakoski/pyLibrary | jx_elasticsearch/es52/aggs.py | get_decoders_by_path | def get_decoders_by_path(query):
"""
RETURN MAP FROM QUERY PATH TO LIST OF DECODER ARRAYS
:param query:
:return:
"""
schema = query.frum.schema
output = Data()
if query.edges:
if query.sort and query.format != "cube":
# REORDER EDGES/GROUPBY TO MATCH THE SORT
... | python | def get_decoders_by_path(query):
"""
RETURN MAP FROM QUERY PATH TO LIST OF DECODER ARRAYS
:param query:
:return:
"""
schema = query.frum.schema
output = Data()
if query.edges:
if query.sort and query.format != "cube":
# REORDER EDGES/GROUPBY TO MATCH THE SORT
... | [
"def",
"get_decoders_by_path",
"(",
"query",
")",
":",
"schema",
"=",
"query",
".",
"frum",
".",
"schema",
"output",
"=",
"Data",
"(",
")",
"if",
"query",
".",
"edges",
":",
"if",
"query",
".",
"sort",
"and",
"query",
".",
"format",
"!=",
"\"cube\"",
... | RETURN MAP FROM QUERY PATH TO LIST OF DECODER ARRAYS
:param query:
:return: | [
"RETURN",
"MAP",
"FROM",
"QUERY",
"PATH",
"TO",
"LIST",
"OF",
"DECODER",
"ARRAYS"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_elasticsearch/es52/aggs.py#L96-L148 |
klahnakoski/pyLibrary | jx_elasticsearch/es52/aggs.py | aggs_iterator | def aggs_iterator(aggs, es_query, decoders, give_me_zeros=False):
"""
DIG INTO ES'S RECURSIVE aggs DATA-STRUCTURE:
RETURN AN ITERATOR OVER THE EFFECTIVE ROWS OF THE RESULTS
:param aggs: ES AGGREGATE OBJECT
:param es_query: THE ABSTRACT ES QUERY WE WILL TRACK ALONGSIDE aggs
:param decoders: TO C... | python | def aggs_iterator(aggs, es_query, decoders, give_me_zeros=False):
"""
DIG INTO ES'S RECURSIVE aggs DATA-STRUCTURE:
RETURN AN ITERATOR OVER THE EFFECTIVE ROWS OF THE RESULTS
:param aggs: ES AGGREGATE OBJECT
:param es_query: THE ABSTRACT ES QUERY WE WILL TRACK ALONGSIDE aggs
:param decoders: TO C... | [
"def",
"aggs_iterator",
"(",
"aggs",
",",
"es_query",
",",
"decoders",
",",
"give_me_zeros",
"=",
"False",
")",
":",
"coord",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"decoders",
")",
"parts",
"=",
"deque",
"(",
")",
"stack",
"=",
"[",
"]",
"gen",
"=",... | DIG INTO ES'S RECURSIVE aggs DATA-STRUCTURE:
RETURN AN ITERATOR OVER THE EFFECTIVE ROWS OF THE RESULTS
:param aggs: ES AGGREGATE OBJECT
:param es_query: THE ABSTRACT ES QUERY WE WILL TRACK ALONGSIDE aggs
:param decoders: TO CONVERT PARTS INTO COORDINATES | [
"DIG",
"INTO",
"ES",
"S",
"RECURSIVE",
"aggs",
"DATA",
"-",
"STRUCTURE",
":",
"RETURN",
"AN",
"ITERATOR",
"OVER",
"THE",
"EFFECTIVE",
"ROWS",
"OF",
"THE",
"RESULTS"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_elasticsearch/es52/aggs.py#L490-L534 |
jmoiron/micromongo | micromongo/spec.py | make_default | def make_default(spec):
"""Create an empty document that follows spec. Any field with a default
will take that value, required or not. Required fields with no default
will get a value of None. If your default value does not match your
type or otherwise customized Field class, this can create a spec t... | python | def make_default(spec):
"""Create an empty document that follows spec. Any field with a default
will take that value, required or not. Required fields with no default
will get a value of None. If your default value does not match your
type or otherwise customized Field class, this can create a spec t... | [
"def",
"make_default",
"(",
"spec",
")",
":",
"doc",
"=",
"{",
"}",
"for",
"key",
",",
"field",
"in",
"spec",
".",
"iteritems",
"(",
")",
":",
"if",
"field",
".",
"default",
"is",
"not",
"no_default",
":",
"doc",
"[",
"key",
"]",
"=",
"field",
".... | Create an empty document that follows spec. Any field with a default
will take that value, required or not. Required fields with no default
will get a value of None. If your default value does not match your
type or otherwise customized Field class, this can create a spec that
fails validation. | [
"Create",
"an",
"empty",
"document",
"that",
"follows",
"spec",
".",
"Any",
"field",
"with",
"a",
"default",
"will",
"take",
"that",
"value",
"required",
"or",
"not",
".",
"Required",
"fields",
"with",
"no",
"default",
"will",
"get",
"a",
"value",
"of",
... | train | https://github.com/jmoiron/micromongo/blob/0d7dd1396e2f25ece6648619ccff32345bc306a1/micromongo/spec.py#L88-L98 |
jmoiron/micromongo | micromongo/spec.py | validate | def validate(document, spec):
"""Validate that a document meets a specification. Returns True if
validation was successful, but otherwise raises a ValueError."""
if not spec:
return True
missing = []
for key, field in spec.iteritems():
if field.required and key not in document:
... | python | def validate(document, spec):
"""Validate that a document meets a specification. Returns True if
validation was successful, but otherwise raises a ValueError."""
if not spec:
return True
missing = []
for key, field in spec.iteritems():
if field.required and key not in document:
... | [
"def",
"validate",
"(",
"document",
",",
"spec",
")",
":",
"if",
"not",
"spec",
":",
"return",
"True",
"missing",
"=",
"[",
"]",
"for",
"key",
",",
"field",
"in",
"spec",
".",
"iteritems",
"(",
")",
":",
"if",
"field",
".",
"required",
"and",
"key"... | Validate that a document meets a specification. Returns True if
validation was successful, but otherwise raises a ValueError. | [
"Validate",
"that",
"a",
"document",
"meets",
"a",
"specification",
".",
"Returns",
"True",
"if",
"validation",
"was",
"successful",
"but",
"otherwise",
"raises",
"a",
"ValueError",
"."
] | train | https://github.com/jmoiron/micromongo/blob/0d7dd1396e2f25ece6648619ccff32345bc306a1/micromongo/spec.py#L100-L123 |
jmoiron/micromongo | micromongo/spec.py | Field.typecheck | def typecheck(self, t):
"""Create a typecheck from some value ``t``. This behaves differently
depending on what ``t`` is. It should take a value and return True if
the typecheck passes, or False otherwise. Override ``pre_validate``
in a child class to do type coercion.
* If `... | python | def typecheck(self, t):
"""Create a typecheck from some value ``t``. This behaves differently
depending on what ``t`` is. It should take a value and return True if
the typecheck passes, or False otherwise. Override ``pre_validate``
in a child class to do type coercion.
* If `... | [
"def",
"typecheck",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
"is",
"None",
":",
"return",
"lambda",
"x",
":",
"True",
"def",
"_isinstance",
"(",
"types",
",",
"value",
")",
":",
"return",
"isinstance",
"(",
"value",
",",
"types",
")",
"def",
"_e... | Create a typecheck from some value ``t``. This behaves differently
depending on what ``t`` is. It should take a value and return True if
the typecheck passes, or False otherwise. Override ``pre_validate``
in a child class to do type coercion.
* If ``t`` is a type, like basestring, in... | [
"Create",
"a",
"typecheck",
"from",
"some",
"value",
"t",
".",
"This",
"behaves",
"differently",
"depending",
"on",
"what",
"t",
"is",
".",
"It",
"should",
"take",
"a",
"value",
"and",
"return",
"True",
"if",
"the",
"typecheck",
"passes",
"or",
"False",
... | train | https://github.com/jmoiron/micromongo/blob/0d7dd1396e2f25ece6648619ccff32345bc306a1/micromongo/spec.py#L26-L62 |
jmoiron/micromongo | micromongo/spec.py | Field.validate | def validate(self, value):
"""Validate a value for this field. If the field is invalid, this
will raise a ValueError. Runs ``pre_validate`` hook prior to
validation, and returns value if validation passes."""
value = self.pre_validate(value)
if not self._typecheck(value):
... | python | def validate(self, value):
"""Validate a value for this field. If the field is invalid, this
will raise a ValueError. Runs ``pre_validate`` hook prior to
validation, and returns value if validation passes."""
value = self.pre_validate(value)
if not self._typecheck(value):
... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"pre_validate",
"(",
"value",
")",
"if",
"not",
"self",
".",
"_typecheck",
"(",
"value",
")",
":",
"raise",
"ValueError",
"(",
"'%r failed type check'",
"%",
"value",
")",... | Validate a value for this field. If the field is invalid, this
will raise a ValueError. Runs ``pre_validate`` hook prior to
validation, and returns value if validation passes. | [
"Validate",
"a",
"value",
"for",
"this",
"field",
".",
"If",
"the",
"field",
"is",
"invalid",
"this",
"will",
"raise",
"a",
"ValueError",
".",
"Runs",
"pre_validate",
"hook",
"prior",
"to",
"validation",
"and",
"returns",
"value",
"if",
"validation",
"passes... | train | https://github.com/jmoiron/micromongo/blob/0d7dd1396e2f25ece6648619ccff32345bc306a1/micromongo/spec.py#L79-L86 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService.init_db | def init_db(self):
'''
Creates all the tables, and indexes needed for the service.
:return: None
'''
with self.conn.transaction() as t:
t.execute('''
CREATE TABLE temporal (
tuid INTEGER,
revision CHAR(12) NOT NULL,
... | python | def init_db(self):
'''
Creates all the tables, and indexes needed for the service.
:return: None
'''
with self.conn.transaction() as t:
t.execute('''
CREATE TABLE temporal (
tuid INTEGER,
revision CHAR(12) NOT NULL,
... | [
"def",
"init_db",
"(",
"self",
")",
":",
"with",
"self",
".",
"conn",
".",
"transaction",
"(",
")",
"as",
"t",
":",
"t",
".",
"execute",
"(",
"'''\n CREATE TABLE temporal (\n tuid INTEGER,\n revision CHAR(12) NOT NULL,\n ... | Creates all the tables, and indexes needed for the service.
:return: None | [
"Creates",
"all",
"the",
"tables",
"and",
"indexes",
"needed",
"for",
"the",
"service",
"."
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L86-L118 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService.get_tuids_from_revision | def get_tuids_from_revision(self, revision):
"""
Gets the TUIDs for the files modified by a revision.
:param revision: revision to get files from
:return: list of (file, list(tuids)) tuples
"""
result = []
URL_TO_FILES = self.hg_url / self.config.hg.branch / 'jso... | python | def get_tuids_from_revision(self, revision):
"""
Gets the TUIDs for the files modified by a revision.
:param revision: revision to get files from
:return: list of (file, list(tuids)) tuples
"""
result = []
URL_TO_FILES = self.hg_url / self.config.hg.branch / 'jso... | [
"def",
"get_tuids_from_revision",
"(",
"self",
",",
"revision",
")",
":",
"result",
"=",
"[",
"]",
"URL_TO_FILES",
"=",
"self",
".",
"hg_url",
"/",
"self",
".",
"config",
".",
"hg",
".",
"branch",
"/",
"'json-info'",
"/",
"revision",
"try",
":",
"mozobje... | Gets the TUIDs for the files modified by a revision.
:param revision: revision to get files from
:return: list of (file, list(tuids)) tuples | [
"Gets",
"the",
"TUIDs",
"for",
"the",
"files",
"modified",
"by",
"a",
"revision",
"."
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L281-L299 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService._check_branch | def _check_branch(self, revision, branch):
'''
Used to find out if the revision is in the given branch.
:param revision: Revision to check.
:param branch: Branch to check revision on.
:return: True/False - Found it/Didn't find it
'''
# Get a changelog
cl... | python | def _check_branch(self, revision, branch):
'''
Used to find out if the revision is in the given branch.
:param revision: Revision to check.
:param branch: Branch to check revision on.
:return: True/False - Found it/Didn't find it
'''
# Get a changelog
cl... | [
"def",
"_check_branch",
"(",
"self",
",",
"revision",
",",
"branch",
")",
":",
"# Get a changelog",
"clog_url",
"=",
"self",
".",
"hg_url",
"/",
"branch",
"/",
"'json-log'",
"/",
"revision",
"try",
":",
"Log",
".",
"note",
"(",
"\"Searching through changelog {... | Used to find out if the revision is in the given branch.
:param revision: Revision to check.
:param branch: Branch to check revision on.
:return: True/False - Found it/Didn't find it | [
"Used",
"to",
"find",
"out",
"if",
"the",
"revision",
"is",
"in",
"the",
"given",
"branch",
"."
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L303-L326 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService.get_tuids_from_files | def get_tuids_from_files(
self,
files,
revision,
going_forward=False,
repo=None,
use_thread=True,
max_csets_proc=30
):
"""
Gets the TUIDs for a set of files, at a given revision.
list(tuids) is an array o... | python | def get_tuids_from_files(
self,
files,
revision,
going_forward=False,
repo=None,
use_thread=True,
max_csets_proc=30
):
"""
Gets the TUIDs for a set of files, at a given revision.
list(tuids) is an array o... | [
"def",
"get_tuids_from_files",
"(",
"self",
",",
"files",
",",
"revision",
",",
"going_forward",
"=",
"False",
",",
"repo",
"=",
"None",
",",
"use_thread",
"=",
"True",
",",
"max_csets_proc",
"=",
"30",
")",
":",
"completed",
"=",
"True",
"if",
"repo",
"... | Gets the TUIDs for a set of files, at a given revision.
list(tuids) is an array of tuids, one tuid for each line, in order, and `null` if no tuid assigned
Uses frontier updating to build and maintain the tuids for
the given set of files. Use changelog to determine what revisions
to proc... | [
"Gets",
"the",
"TUIDs",
"for",
"a",
"set",
"of",
"files",
"at",
"a",
"given",
"revision",
".",
"list",
"(",
"tuids",
")",
"is",
"an",
"array",
"of",
"tuids",
"one",
"tuid",
"for",
"each",
"line",
"in",
"order",
"and",
"null",
"if",
"no",
"tuid",
"a... | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L346-L561 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService._apply_diff | def _apply_diff(self, transaction, annotation, diff, cset, file):
'''
Using an annotation ([(tuid,line)] - array
of TuidMap objects), we change the line numbers to
reflect a given diff and return them. diff must
be a diff object returned from get_diff(cset, file).
Only fo... | python | def _apply_diff(self, transaction, annotation, diff, cset, file):
'''
Using an annotation ([(tuid,line)] - array
of TuidMap objects), we change the line numbers to
reflect a given diff and return them. diff must
be a diff object returned from get_diff(cset, file).
Only fo... | [
"def",
"_apply_diff",
"(",
"self",
",",
"transaction",
",",
"annotation",
",",
"diff",
",",
"cset",
",",
"file",
")",
":",
"# Ignore merges, they have duplicate entries.",
"if",
"diff",
"[",
"'merge'",
"]",
":",
"return",
"annotation",
",",
"file",
"if",
"file... | Using an annotation ([(tuid,line)] - array
of TuidMap objects), we change the line numbers to
reflect a given diff and return them. diff must
be a diff object returned from get_diff(cset, file).
Only for going forward in time, not back.
:param annotation: list of TuidMap objects... | [
"Using",
"an",
"annotation",
"(",
"[",
"(",
"tuid",
"line",
")",
"]",
"-",
"array",
"of",
"TuidMap",
"objects",
")",
"we",
"change",
"the",
"line",
"numbers",
"to",
"reflect",
"a",
"given",
"diff",
"and",
"return",
"them",
".",
"diff",
"must",
"be",
... | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L564-L630 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService._get_tuids_from_files_try_branch | def _get_tuids_from_files_try_branch(self, files, revision):
'''
Gets files from a try revision. It abuses the idea that try pushes
will come from various, but stable points (if people make many
pushes on that revision). Furthermore, updates are generally done
to a revision that ... | python | def _get_tuids_from_files_try_branch(self, files, revision):
'''
Gets files from a try revision. It abuses the idea that try pushes
will come from various, but stable points (if people make many
pushes on that revision). Furthermore, updates are generally done
to a revision that ... | [
"def",
"_get_tuids_from_files_try_branch",
"(",
"self",
",",
"files",
",",
"revision",
")",
":",
"repo",
"=",
"'try'",
"result",
"=",
"[",
"]",
"log_existing_files",
"=",
"[",
"]",
"files_to_update",
"=",
"[",
"]",
"# Check if the files were already annotated.",
"... | Gets files from a try revision. It abuses the idea that try pushes
will come from various, but stable points (if people make many
pushes on that revision). Furthermore, updates are generally done
to a revision that should eventually have tuids already in the DB
(i.e. overtime as people u... | [
"Gets",
"files",
"from",
"a",
"try",
"revision",
".",
"It",
"abuses",
"the",
"idea",
"that",
"try",
"pushes",
"will",
"come",
"from",
"various",
"but",
"stable",
"points",
"(",
"if",
"people",
"make",
"many",
"pushes",
"on",
"that",
"revision",
")",
".",... | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L633-L833 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService._update_file_frontiers | def _update_file_frontiers(
self,
frontier_list,
revision,
max_csets_proc=30,
going_forward=False
):
'''
Update the frontier for all given files, up to the given revision.
Built for quick continuous _forward_ updating of large ... | python | def _update_file_frontiers(
self,
frontier_list,
revision,
max_csets_proc=30,
going_forward=False
):
'''
Update the frontier for all given files, up to the given revision.
Built for quick continuous _forward_ updating of large ... | [
"def",
"_update_file_frontiers",
"(",
"self",
",",
"frontier_list",
",",
"revision",
",",
"max_csets_proc",
"=",
"30",
",",
"going_forward",
"=",
"False",
")",
":",
"# Get the changelogs and revisions until we find the",
"# last one we've seen, and get the modified files in",
... | Update the frontier for all given files, up to the given revision.
Built for quick continuous _forward_ updating of large sets
of files of TUIDs. Backward updating should be done through
get_tuids(files, revision). If we cannot find a frontier, we will
stop looking after max_csets_proc ... | [
"Update",
"the",
"frontier",
"for",
"all",
"given",
"files",
"up",
"to",
"the",
"given",
"revision",
"."
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L836-L1266 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService.get_tuids | def get_tuids(self, files, revision, commit=True, chunk=50, repo=None):
'''
Wrapper for `_get_tuids` to limit the number of annotation calls to hg
and separate the calls from DB transactions. Also used to simplify `_get_tuids`.
:param files:
:param revision:
:param commi... | python | def get_tuids(self, files, revision, commit=True, chunk=50, repo=None):
'''
Wrapper for `_get_tuids` to limit the number of annotation calls to hg
and separate the calls from DB transactions. Also used to simplify `_get_tuids`.
:param files:
:param revision:
:param commi... | [
"def",
"get_tuids",
"(",
"self",
",",
"files",
",",
"revision",
",",
"commit",
"=",
"True",
",",
"chunk",
"=",
"50",
",",
"repo",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"revision",
"=",
"revision",
"[",
":",
"12",
"]",
"# For a single file,... | Wrapper for `_get_tuids` to limit the number of annotation calls to hg
and separate the calls from DB transactions. Also used to simplify `_get_tuids`.
:param files:
:param revision:
:param commit:
:param chunk:
:param repo:
:return: | [
"Wrapper",
"for",
"_get_tuids",
"to",
"limit",
"the",
"number",
"of",
"annotation",
"calls",
"to",
"hg",
"and",
"separate",
"the",
"calls",
"from",
"DB",
"transactions",
".",
"Also",
"used",
"to",
"simplify",
"_get_tuids",
"."
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L1269-L1341 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService._get_tuids | def _get_tuids(
self,
transaction,
files,
revision,
annotated_files,
commit=True,
repo=None
):
'''
Returns (TUID, line) tuples for a given file at a given revision.
Uses json-annotate to find all lines i... | python | def _get_tuids(
self,
transaction,
files,
revision,
annotated_files,
commit=True,
repo=None
):
'''
Returns (TUID, line) tuples for a given file at a given revision.
Uses json-annotate to find all lines i... | [
"def",
"_get_tuids",
"(",
"self",
",",
"transaction",
",",
"files",
",",
"revision",
",",
"annotated_files",
",",
"commit",
"=",
"True",
",",
"repo",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"for",
"fcount",
",",
"annotated_object",
"in",
"enumer... | Returns (TUID, line) tuples for a given file at a given revision.
Uses json-annotate to find all lines in this revision, then it updates
the database with any missing revisions for the file changes listed
in annotate. Then, we use the information from annotate coupled with the
diff info... | [
"Returns",
"(",
"TUID",
"line",
")",
"tuples",
"for",
"a",
"given",
"file",
"at",
"a",
"given",
"revision",
"."
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L1344-L1529 |
klahnakoski/pyLibrary | tuid/service.py | TUIDService._daemon | def _daemon(self, please_stop, only_coverage_revisions=False):
'''
Runs continuously to prefill the temporal and
annotations table with the coverage revisions*.
* A coverage revision is a revision which has had
code coverage run on it.
:param please_stop: Used to stop t... | python | def _daemon(self, please_stop, only_coverage_revisions=False):
'''
Runs continuously to prefill the temporal and
annotations table with the coverage revisions*.
* A coverage revision is a revision which has had
code coverage run on it.
:param please_stop: Used to stop t... | [
"def",
"_daemon",
"(",
"self",
",",
"please_stop",
",",
"only_coverage_revisions",
"=",
"False",
")",
":",
"while",
"not",
"please_stop",
":",
"# Get all known files and their latest revisions on the frontier",
"files_n_revs",
"=",
"self",
".",
"conn",
".",
"get",
"("... | Runs continuously to prefill the temporal and
annotations table with the coverage revisions*.
* A coverage revision is a revision which has had
code coverage run on it.
:param please_stop: Used to stop the daemon
:return: None | [
"Runs",
"continuously",
"to",
"prefill",
"the",
"temporal",
"and",
"annotations",
"table",
"with",
"the",
"coverage",
"revisions",
"*",
"."
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/service.py#L1532-L1639 |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/utils.py | collapsesum | def collapsesum(data_frame, by = None, var = None):
'''
Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe.
'''
assert by is not None
assert var is not None
grouped = data_frame.groupby([by])
return grouped.apply(lambda x: weighted_sum(groupe = x, var =var)) | python | def collapsesum(data_frame, by = None, var = None):
'''
Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe.
'''
assert by is not None
assert var is not None
grouped = data_frame.groupby([by])
return grouped.apply(lambda x: weighted_sum(groupe = x, var =var)) | [
"def",
"collapsesum",
"(",
"data_frame",
",",
"by",
"=",
"None",
",",
"var",
"=",
"None",
")",
":",
"assert",
"by",
"is",
"not",
"None",
"assert",
"var",
"is",
"not",
"None",
"grouped",
"=",
"data_frame",
".",
"groupby",
"(",
"[",
"by",
"]",
")",
"... | Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. | [
"Pour",
"une",
"variable",
"fonction",
"qui",
"calcule",
"la",
"moyenne",
"pondérée",
"au",
"sein",
"de",
"chaque",
"groupe",
"."
] | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/utils.py#L30-L37 |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/utils.py | weighted_sum | def weighted_sum(groupe, var):
'''
Fonction qui calcule la moyenne pondérée par groupe d'une variable
'''
data = groupe[var]
weights = groupe['pondmen']
return (data * weights).sum() | python | def weighted_sum(groupe, var):
'''
Fonction qui calcule la moyenne pondérée par groupe d'une variable
'''
data = groupe[var]
weights = groupe['pondmen']
return (data * weights).sum() | [
"def",
"weighted_sum",
"(",
"groupe",
",",
"var",
")",
":",
"data",
"=",
"groupe",
"[",
"var",
"]",
"weights",
"=",
"groupe",
"[",
"'pondmen'",
"]",
"return",
"(",
"data",
"*",
"weights",
")",
".",
"sum",
"(",
")"
] | Fonction qui calcule la moyenne pondérée par groupe d'une variable | [
"Fonction",
"qui",
"calcule",
"la",
"moyenne",
"pondérée",
"par",
"groupe",
"d",
"une",
"variable"
] | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/utils.py#L52-L58 |
ga4gh/ga4gh-common | ga4gh/common/cli.py | addSubparser | def addSubparser(subparsers, subcommand, description):
"""
Add a subparser with subcommand to the subparsers object
"""
parser = subparsers.add_parser(
subcommand, description=description, help=description)
return parser | python | def addSubparser(subparsers, subcommand, description):
"""
Add a subparser with subcommand to the subparsers object
"""
parser = subparsers.add_parser(
subcommand, description=description, help=description)
return parser | [
"def",
"addSubparser",
"(",
"subparsers",
",",
"subcommand",
",",
"description",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"subcommand",
",",
"description",
"=",
"description",
",",
"help",
"=",
"description",
")",
"return",
"parser"
] | Add a subparser with subcommand to the subparsers object | [
"Add",
"a",
"subparser",
"with",
"subcommand",
"to",
"the",
"subparsers",
"object"
] | train | https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/cli.py#L45-L51 |
ga4gh/ga4gh-common | ga4gh/common/cli.py | createArgumentParser | def createArgumentParser(description):
"""
Create an argument parser
"""
parser = argparse.ArgumentParser(
description=description,
formatter_class=SortedHelpFormatter)
return parser | python | def createArgumentParser(description):
"""
Create an argument parser
"""
parser = argparse.ArgumentParser(
description=description,
formatter_class=SortedHelpFormatter)
return parser | [
"def",
"createArgumentParser",
"(",
"description",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
",",
"formatter_class",
"=",
"SortedHelpFormatter",
")",
"return",
"parser"
] | Create an argument parser | [
"Create",
"an",
"argument",
"parser"
] | train | https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/cli.py#L54-L61 |
ga4gh/ga4gh-common | ga4gh/common/cli.py | SortedHelpFormatter.add_arguments | def add_arguments(self, actions):
"""
Sort the flags alphabetically
"""
actions = sorted(
actions, key=operator.attrgetter('option_strings'))
super(SortedHelpFormatter, self).add_arguments(actions) | python | def add_arguments(self, actions):
"""
Sort the flags alphabetically
"""
actions = sorted(
actions, key=operator.attrgetter('option_strings'))
super(SortedHelpFormatter, self).add_arguments(actions) | [
"def",
"add_arguments",
"(",
"self",
",",
"actions",
")",
":",
"actions",
"=",
"sorted",
"(",
"actions",
",",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'option_strings'",
")",
")",
"super",
"(",
"SortedHelpFormatter",
",",
"self",
")",
".",
"add_arg... | Sort the flags alphabetically | [
"Sort",
"the",
"flags",
"alphabetically"
] | train | https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/cli.py#L17-L23 |
ga4gh/ga4gh-common | ga4gh/common/cli.py | SortedHelpFormatter._iter_indented_subactions | def _iter_indented_subactions(self, action):
"""
Sort the subcommands alphabetically
"""
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
if isinstance(action, argparse._SubParser... | python | def _iter_indented_subactions(self, action):
"""
Sort the subcommands alphabetically
"""
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
if isinstance(action, argparse._SubParser... | [
"def",
"_iter_indented_subactions",
"(",
"self",
",",
"action",
")",
":",
"try",
":",
"get_subactions",
"=",
"action",
".",
"_get_subactions",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"self",
".",
"_indent",
"(",
")",
"if",
"isinstance",
"(",
"a... | Sort the subcommands alphabetically | [
"Sort",
"the",
"subcommands",
"alphabetically"
] | train | https://github.com/ga4gh/ga4gh-common/blob/ea1b562dce5bf088ac4577b838cfac7745f08346/ga4gh/common/cli.py#L25-L42 |
clchiou/startup | examples/mul.py | main | def main(argv):
"""Call startup.call() in your main()."""
args = startup.call(argv=argv)['args']
if args.v:
print('x * y = %d' % (args.x * args.y))
else:
print(args.x * args.y)
return 0 | python | def main(argv):
"""Call startup.call() in your main()."""
args = startup.call(argv=argv)['args']
if args.v:
print('x * y = %d' % (args.x * args.y))
else:
print(args.x * args.y)
return 0 | [
"def",
"main",
"(",
"argv",
")",
":",
"args",
"=",
"startup",
".",
"call",
"(",
"argv",
"=",
"argv",
")",
"[",
"'args'",
"]",
"if",
"args",
".",
"v",
":",
"print",
"(",
"'x * y = %d'",
"%",
"(",
"args",
".",
"x",
"*",
"args",
".",
"y",
")",
"... | Call startup.call() in your main(). | [
"Call",
"startup",
".",
"call",
"()",
"in",
"your",
"main",
"()",
"."
] | train | https://github.com/clchiou/startup/blob/13cbf3ce1deffbc10d33a5f64c396a73129a5929/examples/mul.py#L67-L74 |
uralbash/pyramid_pages | pyramid_pages/resources.py | resource_of_node | def resource_of_node(resources, node):
""" Returns resource of node.
"""
for resource in resources:
model = getattr(resource, 'model', None)
if type(node) == model:
return resource
return BasePageResource | python | def resource_of_node(resources, node):
""" Returns resource of node.
"""
for resource in resources:
model = getattr(resource, 'model', None)
if type(node) == model:
return resource
return BasePageResource | [
"def",
"resource_of_node",
"(",
"resources",
",",
"node",
")",
":",
"for",
"resource",
"in",
"resources",
":",
"model",
"=",
"getattr",
"(",
"resource",
",",
"'model'",
",",
"None",
")",
"if",
"type",
"(",
"node",
")",
"==",
"model",
":",
"return",
"re... | Returns resource of node. | [
"Returns",
"resource",
"of",
"node",
"."
] | train | https://github.com/uralbash/pyramid_pages/blob/545b1ecb2e5dee5742135ba2a689b9635dd4efa1/pyramid_pages/resources.py#L133-L140 |
uralbash/pyramid_pages | pyramid_pages/resources.py | resources_of_config | def resources_of_config(config):
""" Returns all resources and models from config.
"""
return set( # unique values
sum([ # join lists to flat list
list(value) # if value is iter (ex: list of resources)
if hasattr(value, '__iter__')
el... | python | def resources_of_config(config):
""" Returns all resources and models from config.
"""
return set( # unique values
sum([ # join lists to flat list
list(value) # if value is iter (ex: list of resources)
if hasattr(value, '__iter__')
el... | [
"def",
"resources_of_config",
"(",
"config",
")",
":",
"return",
"set",
"(",
"# unique values",
"sum",
"(",
"[",
"# join lists to flat list",
"list",
"(",
"value",
")",
"# if value is iter (ex: list of resources)",
"if",
"hasattr",
"(",
"value",
",",
"'__iter__'",
"... | Returns all resources and models from config. | [
"Returns",
"all",
"resources",
"and",
"models",
"from",
"config",
"."
] | train | https://github.com/uralbash/pyramid_pages/blob/545b1ecb2e5dee5742135ba2a689b9635dd4efa1/pyramid_pages/resources.py#L143-L153 |
uralbash/pyramid_pages | pyramid_pages/resources.py | models_of_config | def models_of_config(config):
""" Return list of models from all resources in config.
"""
resources = resources_of_config(config)
models = []
for resource in resources:
if not hasattr(resource, '__table__') and hasattr(resource, 'model'):
models.append(resource.model)
els... | python | def models_of_config(config):
""" Return list of models from all resources in config.
"""
resources = resources_of_config(config)
models = []
for resource in resources:
if not hasattr(resource, '__table__') and hasattr(resource, 'model'):
models.append(resource.model)
els... | [
"def",
"models_of_config",
"(",
"config",
")",
":",
"resources",
"=",
"resources_of_config",
"(",
"config",
")",
"models",
"=",
"[",
"]",
"for",
"resource",
"in",
"resources",
":",
"if",
"not",
"hasattr",
"(",
"resource",
",",
"'__table__'",
")",
"and",
"h... | Return list of models from all resources in config. | [
"Return",
"list",
"of",
"models",
"from",
"all",
"resources",
"in",
"config",
"."
] | train | https://github.com/uralbash/pyramid_pages/blob/545b1ecb2e5dee5742135ba2a689b9635dd4efa1/pyramid_pages/resources.py#L156-L166 |
uralbash/pyramid_pages | pyramid_pages/resources.py | BasePageResource.get_prefix | def get_prefix(self):
""" Each resource defined in config for pages as dict. This method
returns key from config where located current resource.
"""
for key, value in self.pages_config.items():
if not hasattr(value, '__iter__'):
value = (value, )
f... | python | def get_prefix(self):
""" Each resource defined in config for pages as dict. This method
returns key from config where located current resource.
"""
for key, value in self.pages_config.items():
if not hasattr(value, '__iter__'):
value = (value, )
f... | [
"def",
"get_prefix",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"pages_config",
".",
"items",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"value",
",",
"'__iter__'",
")",
":",
"value",
"=",
"(",
"value",
",",
")",
"for",
... | Each resource defined in config for pages as dict. This method
returns key from config where located current resource. | [
"Each",
"resource",
"defined",
"in",
"config",
"for",
"pages",
"as",
"dict",
".",
"This",
"method",
"returns",
"key",
"from",
"config",
"where",
"located",
"current",
"resource",
"."
] | train | https://github.com/uralbash/pyramid_pages/blob/545b1ecb2e5dee5742135ba2a689b9635dd4efa1/pyramid_pages/resources.py#L59-L69 |
klahnakoski/pyLibrary | pyLibrary/convert.py | zip2bytes | def zip2bytes(compressed):
"""
UNZIP DATA
"""
if hasattr(compressed, "read"):
return gzip.GzipFile(fileobj=compressed, mode='r')
buff = BytesIO(compressed)
archive = gzip.GzipFile(fileobj=buff, mode='r')
from pyLibrary.env.big_data import safe_size
return safe_size(archive) | python | def zip2bytes(compressed):
"""
UNZIP DATA
"""
if hasattr(compressed, "read"):
return gzip.GzipFile(fileobj=compressed, mode='r')
buff = BytesIO(compressed)
archive = gzip.GzipFile(fileobj=buff, mode='r')
from pyLibrary.env.big_data import safe_size
return safe_size(archive) | [
"def",
"zip2bytes",
"(",
"compressed",
")",
":",
"if",
"hasattr",
"(",
"compressed",
",",
"\"read\"",
")",
":",
"return",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"compressed",
",",
"mode",
"=",
"'r'",
")",
"buff",
"=",
"BytesIO",
"(",
"compressed",... | UNZIP DATA | [
"UNZIP",
"DATA"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/convert.py#L458-L468 |
klahnakoski/pyLibrary | pyLibrary/convert.py | bytes2zip | def bytes2zip(bytes):
"""
RETURN COMPRESSED BYTES
"""
if hasattr(bytes, "read"):
buff = TemporaryFile()
archive = gzip.GzipFile(fileobj=buff, mode='w')
for b in bytes:
archive.write(b)
archive.close()
buff.seek(0)
from pyLibrary.env.big_data im... | python | def bytes2zip(bytes):
"""
RETURN COMPRESSED BYTES
"""
if hasattr(bytes, "read"):
buff = TemporaryFile()
archive = gzip.GzipFile(fileobj=buff, mode='w')
for b in bytes:
archive.write(b)
archive.close()
buff.seek(0)
from pyLibrary.env.big_data im... | [
"def",
"bytes2zip",
"(",
"bytes",
")",
":",
"if",
"hasattr",
"(",
"bytes",
",",
"\"read\"",
")",
":",
"buff",
"=",
"TemporaryFile",
"(",
")",
"archive",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"buff",
",",
"mode",
"=",
"'w'",
")",
"for",
... | RETURN COMPRESSED BYTES | [
"RETURN",
"COMPRESSED",
"BYTES"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/convert.py#L471-L489 |
klahnakoski/pyLibrary | pyLibrary/convert.py | ini2value | def ini2value(ini_content):
"""
INI FILE CONTENT TO Data
"""
from mo_future import ConfigParser, StringIO
buff = StringIO(ini_content)
config = ConfigParser()
config._read(buff, "dummy")
output = {}
for section in config.sections():
output[section]=s = {}
for k, v i... | python | def ini2value(ini_content):
"""
INI FILE CONTENT TO Data
"""
from mo_future import ConfigParser, StringIO
buff = StringIO(ini_content)
config = ConfigParser()
config._read(buff, "dummy")
output = {}
for section in config.sections():
output[section]=s = {}
for k, v i... | [
"def",
"ini2value",
"(",
"ini_content",
")",
":",
"from",
"mo_future",
"import",
"ConfigParser",
",",
"StringIO",
"buff",
"=",
"StringIO",
"(",
"ini_content",
")",
"config",
"=",
"ConfigParser",
"(",
")",
"config",
".",
"_read",
"(",
"buff",
",",
"\"dummy\""... | INI FILE CONTENT TO Data | [
"INI",
"FILE",
"CONTENT",
"TO",
"Data"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/convert.py#L492-L507 |
klahnakoski/pyLibrary | pyLibrary/convert.py | table2csv | def table2csv(table_data):
"""
:param table_data: expecting a list of tuples
:return: text in nice formatted csv
"""
text_data = [tuple(value2json(vals, pretty=True) for vals in rows) for rows in table_data]
col_widths = [max(len(text) for text in cols) for cols in zip(*text_data)]
template... | python | def table2csv(table_data):
"""
:param table_data: expecting a list of tuples
:return: text in nice formatted csv
"""
text_data = [tuple(value2json(vals, pretty=True) for vals in rows) for rows in table_data]
col_widths = [max(len(text) for text in cols) for cols in zip(*text_data)]
template... | [
"def",
"table2csv",
"(",
"table_data",
")",
":",
"text_data",
"=",
"[",
"tuple",
"(",
"value2json",
"(",
"vals",
",",
"pretty",
"=",
"True",
")",
"for",
"vals",
"in",
"rows",
")",
"for",
"rows",
"in",
"table_data",
"]",
"col_widths",
"=",
"[",
"max",
... | :param table_data: expecting a list of tuples
:return: text in nice formatted csv | [
":",
"param",
"table_data",
":",
"expecting",
"a",
"list",
"of",
"tuples",
":",
"return",
":",
"text",
"in",
"nice",
"formatted",
"csv"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/convert.py#L600-L613 |
note35/sinon | sinon/lib/util/CollectionHandler.py | tuple_in_list_always | def tuple_in_list_always(main, sub):
"""
>>> main = [('a', 'b', 'c'), ('c', 'd')]
>>> tuple_in_list_always(main, ('a' ,'b', 'c'))
False
>>> tuple_in_list_always(main, ('c', 'd'))
False
>>> tuple_in_list_always(main, ('a', 'c'))
False
>>> tuple_in_list_always(main, ('a'))
False
... | python | def tuple_in_list_always(main, sub):
"""
>>> main = [('a', 'b', 'c'), ('c', 'd')]
>>> tuple_in_list_always(main, ('a' ,'b', 'c'))
False
>>> tuple_in_list_always(main, ('c', 'd'))
False
>>> tuple_in_list_always(main, ('a', 'c'))
False
>>> tuple_in_list_always(main, ('a'))
False
... | [
"def",
"tuple_in_list_always",
"(",
"main",
",",
"sub",
")",
":",
"return",
"True",
"if",
"sub",
"in",
"set",
"(",
"main",
")",
"and",
"len",
"(",
"set",
"(",
"main",
")",
")",
"==",
"1",
"else",
"False"
] | >>> main = [('a', 'b', 'c'), ('c', 'd')]
>>> tuple_in_list_always(main, ('a' ,'b', 'c'))
False
>>> tuple_in_list_always(main, ('c', 'd'))
False
>>> tuple_in_list_always(main, ('a', 'c'))
False
>>> tuple_in_list_always(main, ('a'))
False
>>> tuple_in_list_always(main, ((),))
False... | [
">>>",
"main",
"=",
"[",
"(",
"a",
"b",
"c",
")",
"(",
"c",
"d",
")",
"]",
">>>",
"tuple_in_list_always",
"(",
"main",
"(",
"a",
"b",
"c",
"))",
"False",
">>>",
"tuple_in_list_always",
"(",
"main",
"(",
"c",
"d",
"))",
"False",
">>>",
"tuple_in_lis... | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/util/CollectionHandler.py#L44-L64 |
note35/sinon | sinon/lib/util/CollectionHandler.py | obj_in_list_always | def obj_in_list_always(target_list, obj):
"""
>>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False
"""
for item in set(target_list):
if item is not obj:
return False
return True | python | def obj_in_list_always(target_list, obj):
"""
>>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False
"""
for item in set(target_list):
if item is not obj:
return False
return True | [
"def",
"obj_in_list_always",
"(",
"target_list",
",",
"obj",
")",
":",
"for",
"item",
"in",
"set",
"(",
"target_list",
")",
":",
"if",
"item",
"is",
"not",
"obj",
":",
"return",
"False",
"return",
"True"
] | >>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False | [
">>>",
"l",
"=",
"[",
"1",
"1",
"1",
"]",
">>>",
"obj_in_list_always",
"(",
"l",
"1",
")",
"True",
">>>",
"l",
".",
"append",
"(",
"2",
")",
">>>",
"obj_in_list_always",
"(",
"l",
"1",
")",
"False"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/util/CollectionHandler.py#L101-L113 |
note35/sinon | sinon/lib/util/CollectionHandler.py | dict_partial_cmp | def dict_partial_cmp(target_dict, dict_list, ducktype):
"""
Whether partial dict are in dict_list or not
"""
for called_dict in dict_list:
# ignore invalid test case
if len(target_dict) > len(called_dict):
continue
# get the intersection of two dicts
intersect... | python | def dict_partial_cmp(target_dict, dict_list, ducktype):
"""
Whether partial dict are in dict_list or not
"""
for called_dict in dict_list:
# ignore invalid test case
if len(target_dict) > len(called_dict):
continue
# get the intersection of two dicts
intersect... | [
"def",
"dict_partial_cmp",
"(",
"target_dict",
",",
"dict_list",
",",
"ducktype",
")",
":",
"for",
"called_dict",
"in",
"dict_list",
":",
"# ignore invalid test case",
"if",
"len",
"(",
"target_dict",
")",
">",
"len",
"(",
"called_dict",
")",
":",
"continue",
... | Whether partial dict are in dict_list or not | [
"Whether",
"partial",
"dict",
"are",
"in",
"dict_list",
"or",
"not"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/util/CollectionHandler.py#L115-L136 |
note35/sinon | sinon/lib/util/CollectionHandler.py | dict_partial_cmp_always | def dict_partial_cmp_always(target_dict, dict_list, ducktype):
"""
Whether partial dict are always in dict_list or not
"""
res = []
for called_dict in dict_list:
# ignore invalid test case
if len(target_dict) > len(called_dict):
continue
# get the intersection of ... | python | def dict_partial_cmp_always(target_dict, dict_list, ducktype):
"""
Whether partial dict are always in dict_list or not
"""
res = []
for called_dict in dict_list:
# ignore invalid test case
if len(target_dict) > len(called_dict):
continue
# get the intersection of ... | [
"def",
"dict_partial_cmp_always",
"(",
"target_dict",
",",
"dict_list",
",",
"ducktype",
")",
":",
"res",
"=",
"[",
"]",
"for",
"called_dict",
"in",
"dict_list",
":",
"# ignore invalid test case",
"if",
"len",
"(",
"target_dict",
")",
">",
"len",
"(",
"called_... | Whether partial dict are always in dict_list or not | [
"Whether",
"partial",
"dict",
"are",
"always",
"in",
"dict_list",
"or",
"not"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/util/CollectionHandler.py#L138-L160 |
note35/sinon | sinon/lib/util/CollectionHandler.py | tuple_partial_cmp | def tuple_partial_cmp(target_tuple, tuple_list, ducktype):
"""
Whether partial target_tuple are in tuple_list or not
"""
for called_tuple in tuple_list:
# ignore invalid test case
if len(target_tuple) > len(called_tuple):
continue
# loop all argument from "current arg... | python | def tuple_partial_cmp(target_tuple, tuple_list, ducktype):
"""
Whether partial target_tuple are in tuple_list or not
"""
for called_tuple in tuple_list:
# ignore invalid test case
if len(target_tuple) > len(called_tuple):
continue
# loop all argument from "current arg... | [
"def",
"tuple_partial_cmp",
"(",
"target_tuple",
",",
"tuple_list",
",",
"ducktype",
")",
":",
"for",
"called_tuple",
"in",
"tuple_list",
":",
"# ignore invalid test case",
"if",
"len",
"(",
"target_tuple",
")",
">",
"len",
"(",
"called_tuple",
")",
":",
"contin... | Whether partial target_tuple are in tuple_list or not | [
"Whether",
"partial",
"target_tuple",
"are",
"in",
"tuple_list",
"or",
"not"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/util/CollectionHandler.py#L162-L185 |
note35/sinon | sinon/lib/util/CollectionHandler.py | tuple_partial_cmp_always | def tuple_partial_cmp_always(target_tuple, tuple_list, ducktype):
"""
Whether partial target_tuple are always in tuple_list or not
"""
res = []
for called_tuple in tuple_list:
# ignore invalid test case
if len(target_tuple) > len(called_tuple):
continue
# loop all... | python | def tuple_partial_cmp_always(target_tuple, tuple_list, ducktype):
"""
Whether partial target_tuple are always in tuple_list or not
"""
res = []
for called_tuple in tuple_list:
# ignore invalid test case
if len(target_tuple) > len(called_tuple):
continue
# loop all... | [
"def",
"tuple_partial_cmp_always",
"(",
"target_tuple",
",",
"tuple_list",
",",
"ducktype",
")",
":",
"res",
"=",
"[",
"]",
"for",
"called_tuple",
"in",
"tuple_list",
":",
"# ignore invalid test case",
"if",
"len",
"(",
"target_tuple",
")",
">",
"len",
"(",
"c... | Whether partial target_tuple are always in tuple_list or not | [
"Whether",
"partial",
"target_tuple",
"are",
"always",
"in",
"tuple_list",
"or",
"not"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/util/CollectionHandler.py#L187-L211 |
delfick/nose-of-yeti | noseOfYeti/tokeniser/spec_codec.py | register_from_options | def register_from_options(options=None, template=None, extractor=None):
"""Register the spec codec using the provided options"""
if template is None:
from noseOfYeti.plugins.support.spec_options import spec_options as template
if extractor is None:
from noseOfYeti.plugins.support.spec_optio... | python | def register_from_options(options=None, template=None, extractor=None):
"""Register the spec codec using the provided options"""
if template is None:
from noseOfYeti.plugins.support.spec_options import spec_options as template
if extractor is None:
from noseOfYeti.plugins.support.spec_optio... | [
"def",
"register_from_options",
"(",
"options",
"=",
"None",
",",
"template",
"=",
"None",
",",
"extractor",
"=",
"None",
")",
":",
"if",
"template",
"is",
"None",
":",
"from",
"noseOfYeti",
".",
"plugins",
".",
"support",
".",
"spec_options",
"import",
"s... | Register the spec codec using the provided options | [
"Register",
"the",
"spec",
"codec",
"using",
"the",
"provided",
"options"
] | train | https://github.com/delfick/nose-of-yeti/blob/0b545ff350cebd59b40b601333c13033ce40d6dc/noseOfYeti/tokeniser/spec_codec.py#L156-L179 |
delfick/nose-of-yeti | noseOfYeti/tokeniser/spec_codec.py | TokeniserCodec.register | def register(self):
"""Register spec codec"""
# Assume utf8 encoding
utf8 = encodings.search_function('utf8')
class StreamReader(utf_8.StreamReader):
"""Used by cPython to deal with a spec file"""
def __init__(sr, stream, *args, **kwargs):
codecs.... | python | def register(self):
"""Register spec codec"""
# Assume utf8 encoding
utf8 = encodings.search_function('utf8')
class StreamReader(utf_8.StreamReader):
"""Used by cPython to deal with a spec file"""
def __init__(sr, stream, *args, **kwargs):
codecs.... | [
"def",
"register",
"(",
"self",
")",
":",
"# Assume utf8 encoding",
"utf8",
"=",
"encodings",
".",
"search_function",
"(",
"'utf8'",
")",
"class",
"StreamReader",
"(",
"utf_8",
".",
"StreamReader",
")",
":",
"\"\"\"Used by cPython to deal with a spec file\"\"\"",
"def... | Register spec codec | [
"Register",
"spec",
"codec"
] | train | https://github.com/delfick/nose-of-yeti/blob/0b545ff350cebd59b40b601333c13033ce40d6dc/noseOfYeti/tokeniser/spec_codec.py#L25-L108 |
delfick/nose-of-yeti | noseOfYeti/tokeniser/spec_codec.py | TokeniserCodec.dealwith | def dealwith(self, readline, **kwargs):
"""
Replace the contents of spec file with the translated version
readline should be a callable object
, which provides the same interface as the readline() method of built-in file objects
"""
data = []
try:
... | python | def dealwith(self, readline, **kwargs):
"""
Replace the contents of spec file with the translated version
readline should be a callable object
, which provides the same interface as the readline() method of built-in file objects
"""
data = []
try:
... | [
"def",
"dealwith",
"(",
"self",
",",
"readline",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"[",
"]",
"try",
":",
"# We pass in the data variable as an argument so that we",
"# get partial output even in the case of an exception.",
"self",
".",
"tokeniser",
".",
... | Replace the contents of spec file with the translated version
readline should be a callable object
, which provides the same interface as the readline() method of built-in file objects | [
"Replace",
"the",
"contents",
"of",
"spec",
"file",
"with",
"the",
"translated",
"version",
"readline",
"should",
"be",
"a",
"callable",
"object",
"which",
"provides",
"the",
"same",
"interface",
"as",
"the",
"readline",
"()",
"method",
"of",
"built",
"-",
"... | train | https://github.com/delfick/nose-of-yeti/blob/0b545ff350cebd59b40b601333c13033ce40d6dc/noseOfYeti/tokeniser/spec_codec.py#L110-L146 |
delfick/nose-of-yeti | noseOfYeti/tokeniser/spec_codec.py | TokeniserCodec.output_for_debugging | def output_for_debugging(self, stream, data):
"""It will write the translated version of the file"""
with open('%s.spec.out' % stream.name, 'w') as f: f.write(str(data)) | python | def output_for_debugging(self, stream, data):
"""It will write the translated version of the file"""
with open('%s.spec.out' % stream.name, 'w') as f: f.write(str(data)) | [
"def",
"output_for_debugging",
"(",
"self",
",",
"stream",
",",
"data",
")",
":",
"with",
"open",
"(",
"'%s.spec.out'",
"%",
"stream",
".",
"name",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"data",
")",
")"
] | It will write the translated version of the file | [
"It",
"will",
"write",
"the",
"translated",
"version",
"of",
"the",
"file"
] | train | https://github.com/delfick/nose-of-yeti/blob/0b545ff350cebd59b40b601333c13033ce40d6dc/noseOfYeti/tokeniser/spec_codec.py#L148-L150 |
oblalex/django-candv-choices | candv_x/django/choices/forms.py | ChoicesField.to_python | def to_python(self, value):
"""
Validates that the value is in self.choices and can be coerced to the
right type.
"""
value = '' if value in validators.EMPTY_VALUES else smart_text(value)
if value == self.empty_value or value in validators.EMPTY_VALUES:
return... | python | def to_python(self, value):
"""
Validates that the value is in self.choices and can be coerced to the
right type.
"""
value = '' if value in validators.EMPTY_VALUES else smart_text(value)
if value == self.empty_value or value in validators.EMPTY_VALUES:
return... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"''",
"if",
"value",
"in",
"validators",
".",
"EMPTY_VALUES",
"else",
"smart_text",
"(",
"value",
")",
"if",
"value",
"==",
"self",
".",
"empty_value",
"or",
"value",
"in",
"validator... | Validates that the value is in self.choices and can be coerced to the
right type. | [
"Validates",
"that",
"the",
"value",
"is",
"in",
"self",
".",
"choices",
"and",
"can",
"be",
"coerced",
"to",
"the",
"right",
"type",
"."
] | train | https://github.com/oblalex/django-candv-choices/blob/a299cefceebc2fb23e223dfcc63700dff572b6a0/candv_x/django/choices/forms.py#L30-L42 |
oblalex/django-candv-choices | candv_x/django/choices/forms.py | ChoicesField.validate | def validate(self, value):
"""
Validates that the input is in self.choices.
"""
super(ChoicesField, self).validate(value)
if value and not self.valid_value(value):
self._on_invalid_value(value) | python | def validate(self, value):
"""
Validates that the input is in self.choices.
"""
super(ChoicesField, self).validate(value)
if value and not self.valid_value(value):
self._on_invalid_value(value) | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"ChoicesField",
",",
"self",
")",
".",
"validate",
"(",
"value",
")",
"if",
"value",
"and",
"not",
"self",
".",
"valid_value",
"(",
"value",
")",
":",
"self",
".",
"_on_invalid_value... | Validates that the input is in self.choices. | [
"Validates",
"that",
"the",
"input",
"is",
"in",
"self",
".",
"choices",
"."
] | train | https://github.com/oblalex/django-candv-choices/blob/a299cefceebc2fb23e223dfcc63700dff572b6a0/candv_x/django/choices/forms.py#L44-L50 |
oblalex/django-candv-choices | candv_x/django/choices/forms.py | ChoicesField.valid_value | def valid_value(self, value):
"""
Check if the provided value is a valid choice.
"""
if isinstance(value, Constant):
value = value.name
text_value = force_text(value)
for option_value, option_label, option_title in self.choices:
if value == option_... | python | def valid_value(self, value):
"""
Check if the provided value is a valid choice.
"""
if isinstance(value, Constant):
value = value.name
text_value = force_text(value)
for option_value, option_label, option_title in self.choices:
if value == option_... | [
"def",
"valid_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Constant",
")",
":",
"value",
"=",
"value",
".",
"name",
"text_value",
"=",
"force_text",
"(",
"value",
")",
"for",
"option_value",
",",
"option_label",
",... | Check if the provided value is a valid choice. | [
"Check",
"if",
"the",
"provided",
"value",
"is",
"a",
"valid",
"choice",
"."
] | train | https://github.com/oblalex/django-candv-choices/blob/a299cefceebc2fb23e223dfcc63700dff572b6a0/candv_x/django/choices/forms.py#L52-L62 |
ofir123/py-printer | pyprinter/file_size.py | FileSize._unit_info | def _unit_info(self) -> Tuple[str, int]:
"""
Returns both the best unit to measure the size, and its power.
:return: A tuple containing the unit and its power.
"""
abs_bytes = abs(self.size)
if abs_bytes < 1024:
unit = 'B'
unit_divider = 1
... | python | def _unit_info(self) -> Tuple[str, int]:
"""
Returns both the best unit to measure the size, and its power.
:return: A tuple containing the unit and its power.
"""
abs_bytes = abs(self.size)
if abs_bytes < 1024:
unit = 'B'
unit_divider = 1
... | [
"def",
"_unit_info",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"int",
"]",
":",
"abs_bytes",
"=",
"abs",
"(",
"self",
".",
"size",
")",
"if",
"abs_bytes",
"<",
"1024",
":",
"unit",
"=",
"'B'",
"unit_divider",
"=",
"1",
"elif",
"abs_bytes",
... | Returns both the best unit to measure the size, and its power.
:return: A tuple containing the unit and its power. | [
"Returns",
"both",
"the",
"best",
"unit",
"to",
"measure",
"the",
"size",
"and",
"its",
"power",
"."
] | train | https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/file_size.py#L54-L77 |
ofir123/py-printer | pyprinter/file_size.py | FileSize.pretty_print | def pretty_print(self, printer: Optional[Printer] = None, min_width: int = 1, min_unit_width: int = 1):
"""
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min... | python | def pretty_print(self, printer: Optional[Printer] = None, min_width: int = 1, min_unit_width: int = 1):
"""
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min... | [
"def",
"pretty_print",
"(",
"self",
",",
"printer",
":",
"Optional",
"[",
"Printer",
"]",
"=",
"None",
",",
"min_width",
":",
"int",
"=",
"1",
",",
"min_unit_width",
":",
"int",
"=",
"1",
")",
":",
"unit",
",",
"unit_divider",
"=",
"self",
".",
"_uni... | Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min_unit_width = 2:
793 B
100 KB
min_unit_width = 3:
793 B
... | [
"Prints",
"the",
"file",
"size",
"(",
"and",
"it",
"s",
"unit",
")",
"reserving",
"places",
"for",
"longer",
"sizes",
"and",
"units",
".",
"For",
"example",
":",
"min_unit_width",
"=",
"1",
":",
"793",
"B",
"100",
"KB",
"min_unit_width",
"=",
"2",
":",... | train | https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/file_size.py#L208-L235 |
klahnakoski/pyLibrary | pyLibrary/sql/mysql.py | execute_sql | def execute_sql(
host,
username,
password,
sql,
schema=None,
param=None,
kwargs=None
):
"""EXECUTE MANY LINES OF SQL (FROM SQLDUMP FILE, MAYBE?"""
kwargs.schema = coalesce(kwargs.schema, kwargs.database)
if param:
with MySQL(kwargs) as temp:
sql = expand_temp... | python | def execute_sql(
host,
username,
password,
sql,
schema=None,
param=None,
kwargs=None
):
"""EXECUTE MANY LINES OF SQL (FROM SQLDUMP FILE, MAYBE?"""
kwargs.schema = coalesce(kwargs.schema, kwargs.database)
if param:
with MySQL(kwargs) as temp:
sql = expand_temp... | [
"def",
"execute_sql",
"(",
"host",
",",
"username",
",",
"password",
",",
"sql",
",",
"schema",
"=",
"None",
",",
"param",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"kwargs",
".",
"schema",
"=",
"coalesce",
"(",
"kwargs",
".",
"schema",
",",... | EXECUTE MANY LINES OF SQL (FROM SQLDUMP FILE, MAYBE? | [
"EXECUTE",
"MANY",
"LINES",
"OF",
"SQL",
"(",
"FROM",
"SQLDUMP",
"FILE",
"MAYBE?"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/sql/mysql.py#L469-L518 |
klahnakoski/pyLibrary | pyLibrary/sql/mysql.py | quote_value | def quote_value(value):
"""
convert values to mysql code for the same
mostly delegate directly to the mysql lib, but some exceptions exist
"""
try:
if value == None:
return SQL_NULL
elif isinstance(value, SQL):
return quote_sql(value.template, value.param)
... | python | def quote_value(value):
"""
convert values to mysql code for the same
mostly delegate directly to the mysql lib, but some exceptions exist
"""
try:
if value == None:
return SQL_NULL
elif isinstance(value, SQL):
return quote_sql(value.template, value.param)
... | [
"def",
"quote_value",
"(",
"value",
")",
":",
"try",
":",
"if",
"value",
"==",
"None",
":",
"return",
"SQL_NULL",
"elif",
"isinstance",
"(",
"value",
",",
"SQL",
")",
":",
"return",
"quote_sql",
"(",
"value",
".",
"template",
",",
"value",
".",
"param"... | convert values to mysql code for the same
mostly delegate directly to the mysql lib, but some exceptions exist | [
"convert",
"values",
"to",
"mysql",
"code",
"for",
"the",
"same",
"mostly",
"delegate",
"directly",
"to",
"the",
"mysql",
"lib",
"but",
"some",
"exceptions",
"exist"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/sql/mysql.py#L558-L583 |
klahnakoski/pyLibrary | pyLibrary/sql/mysql.py | quote_sql | def quote_sql(value, param=None):
"""
USED TO EXPAND THE PARAMETERS TO THE SQL() OBJECT
"""
try:
if isinstance(value, SQL):
if not param:
return value
param = {k: quote_sql(v) for k, v in param.items()}
return SQL(expand_template(value, param))... | python | def quote_sql(value, param=None):
"""
USED TO EXPAND THE PARAMETERS TO THE SQL() OBJECT
"""
try:
if isinstance(value, SQL):
if not param:
return value
param = {k: quote_sql(v) for k, v in param.items()}
return SQL(expand_template(value, param))... | [
"def",
"quote_sql",
"(",
"value",
",",
"param",
"=",
"None",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"SQL",
")",
":",
"if",
"not",
"param",
":",
"return",
"value",
"param",
"=",
"{",
"k",
":",
"quote_sql",
"(",
"v",
")",
"for... | USED TO EXPAND THE PARAMETERS TO THE SQL() OBJECT | [
"USED",
"TO",
"EXPAND",
"THE",
"PARAMETERS",
"TO",
"THE",
"SQL",
"()",
"OBJECT"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/sql/mysql.py#L605-L624 |
klahnakoski/pyLibrary | pyLibrary/sql/mysql.py | int_list_packer | def int_list_packer(term, values):
"""
return singletons, ranges and exclusions
"""
DENSITY = 10 # a range can have holes, this is inverse of the hole density
MIN_RANGE = 20 # min members before a range is allowed to be used
singletons = set()
ranges = []
exclude = set()
sorted =... | python | def int_list_packer(term, values):
"""
return singletons, ranges and exclusions
"""
DENSITY = 10 # a range can have holes, this is inverse of the hole density
MIN_RANGE = 20 # min members before a range is allowed to be used
singletons = set()
ranges = []
exclude = set()
sorted =... | [
"def",
"int_list_packer",
"(",
"term",
",",
"values",
")",
":",
"DENSITY",
"=",
"10",
"# a range can have holes, this is inverse of the hole density",
"MIN_RANGE",
"=",
"20",
"# min members before a range is allowed to be used",
"singletons",
"=",
"set",
"(",
")",
"ranges",... | return singletons, ranges and exclusions | [
"return",
"singletons",
"ranges",
"and",
"exclusions"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/sql/mysql.py#L646-L724 |
klahnakoski/pyLibrary | pyLibrary/sql/mysql.py | MySQL._open | def _open(self):
""" DO NOT USE THIS UNLESS YOU close() FIRST"""
try:
self.db = connect(
host=self.settings.host,
port=self.settings.port,
user=coalesce(self.settings.username, self.settings.user),
passwd=coalesce(self.settings.... | python | def _open(self):
""" DO NOT USE THIS UNLESS YOU close() FIRST"""
try:
self.db = connect(
host=self.settings.host,
port=self.settings.port,
user=coalesce(self.settings.username, self.settings.user),
passwd=coalesce(self.settings.... | [
"def",
"_open",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"db",
"=",
"connect",
"(",
"host",
"=",
"self",
".",
"settings",
".",
"host",
",",
"port",
"=",
"self",
".",
"settings",
".",
"port",
",",
"user",
"=",
"coalesce",
"(",
"self",
".",
... | DO NOT USE THIS UNLESS YOU close() FIRST | [
"DO",
"NOT",
"USE",
"THIS",
"UNLESS",
"YOU",
"close",
"()",
"FIRST"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/sql/mysql.py#L86-L116 |
klahnakoski/pyLibrary | pyLibrary/sql/mysql.py | MySQL.query | def query(self, sql, param=None, stream=False, row_tuples=False):
"""
RETURN LIST OF dicts
"""
if not self.cursor: # ALLOW NON-TRANSACTIONAL READS
Log.error("must perform all queries inside a transaction")
self._execute_backlog()
try:
if param:
... | python | def query(self, sql, param=None, stream=False, row_tuples=False):
"""
RETURN LIST OF dicts
"""
if not self.cursor: # ALLOW NON-TRANSACTIONAL READS
Log.error("must perform all queries inside a transaction")
self._execute_backlog()
try:
if param:
... | [
"def",
"query",
"(",
"self",
",",
"sql",
",",
"param",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"row_tuples",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"cursor",
":",
"# ALLOW NON-TRANSACTIONAL READS",
"Log",
".",
"error",
"(",
"\"must perf... | RETURN LIST OF dicts | [
"RETURN",
"LIST",
"OF",
"dicts"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/sql/mysql.py#L249-L281 |
klahnakoski/pyLibrary | pyLibrary/sql/mysql.py | MySQL.column_query | def column_query(self, sql, param=None):
"""
RETURN RESULTS IN [column][row_num] GRID
"""
self._execute_backlog()
try:
old_cursor = self.cursor
if not old_cursor: # ALLOW NON-TRANSACTIONAL READS
self.cursor = self.db.cursor()
... | python | def column_query(self, sql, param=None):
"""
RETURN RESULTS IN [column][row_num] GRID
"""
self._execute_backlog()
try:
old_cursor = self.cursor
if not old_cursor: # ALLOW NON-TRANSACTIONAL READS
self.cursor = self.db.cursor()
... | [
"def",
"column_query",
"(",
"self",
",",
"sql",
",",
"param",
"=",
"None",
")",
":",
"self",
".",
"_execute_backlog",
"(",
")",
"try",
":",
"old_cursor",
"=",
"self",
".",
"cursor",
"if",
"not",
"old_cursor",
":",
"# ALLOW NON-TRANSACTIONAL READS",
"self",
... | RETURN RESULTS IN [column][row_num] GRID | [
"RETURN",
"RESULTS",
"IN",
"[",
"column",
"]",
"[",
"row_num",
"]",
"GRID"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/sql/mysql.py#L283-L314 |
klahnakoski/pyLibrary | pyLibrary/sql/mysql.py | MySQL.update | def update(self, table_name, where_slice, new_values):
"""
where_slice - A Data WHICH WILL BE USED TO MATCH ALL IN table
eg {"id": 42}
new_values - A dict WITH COLUMN NAME, COLUMN VALUE PAIRS TO SET
"""
new_values = quote_param(new_values)
where_cl... | python | def update(self, table_name, where_slice, new_values):
"""
where_slice - A Data WHICH WILL BE USED TO MATCH ALL IN table
eg {"id": 42}
new_values - A dict WITH COLUMN NAME, COLUMN VALUE PAIRS TO SET
"""
new_values = quote_param(new_values)
where_cl... | [
"def",
"update",
"(",
"self",
",",
"table_name",
",",
"where_slice",
",",
"new_values",
")",
":",
"new_values",
"=",
"quote_param",
"(",
"new_values",
")",
"where_clause",
"=",
"SQL_AND",
".",
"join",
"(",
"[",
"quote_column",
"(",
"k",
")",
"+",
"\"=\"",
... | where_slice - A Data WHICH WILL BE USED TO MATCH ALL IN table
eg {"id": 42}
new_values - A dict WITH COLUMN NAME, COLUMN VALUE PAIRS TO SET | [
"where_slice",
"-",
"A",
"Data",
"WHICH",
"WILL",
"BE",
"USED",
"TO",
"MATCH",
"ALL",
"IN",
"table",
"eg",
"{",
"id",
":",
"42",
"}",
"new_values",
"-",
"A",
"dict",
"WITH",
"COLUMN",
"NAME",
"COLUMN",
"VALUE",
"PAIRS",
"TO",
"SET"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/sql/mysql.py#L442-L462 |
ff0000/scarlet | scarlet/cms/internal_tags/taggit_handler.py | tokenize_tags | def tokenize_tags(tags_string):
"""
This function is responsible to extract usable tags from a text.
:param tags_string: a string of text
:return: a string of comma separated tags
"""
# text is parsed in two steps:
# the first step extract every single world that is 3 > chars long
# and... | python | def tokenize_tags(tags_string):
"""
This function is responsible to extract usable tags from a text.
:param tags_string: a string of text
:return: a string of comma separated tags
"""
# text is parsed in two steps:
# the first step extract every single world that is 3 > chars long
# and... | [
"def",
"tokenize_tags",
"(",
"tags_string",
")",
":",
"# text is parsed in two steps:",
"# the first step extract every single world that is 3 > chars long",
"# and that contains only alphanumeric characters, underscores and dashes",
"tags_string",
"=",
"tags_string",
".",
"lower",
"(",
... | This function is responsible to extract usable tags from a text.
:param tags_string: a string of text
:return: a string of comma separated tags | [
"This",
"function",
"is",
"responsible",
"to",
"extract",
"usable",
"tags",
"from",
"a",
"text",
".",
":",
"param",
"tags_string",
":",
"a",
"string",
"of",
"text",
":",
"return",
":",
"a",
"string",
"of",
"comma",
"separated",
"tags"
] | train | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/internal_tags/taggit_handler.py#L21-L37 |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/step_1_1_homogeneisation_donnees_depenses.py | build_depenses_homogenisees | def build_depenses_homogenisees(temporary_store = None, year = None):
"""Build menage consumption by categorie fiscale dataframe """
assert temporary_store is not None
assert year is not None
bdf_survey_collection = SurveyCollection.load(
collection = 'budget_des_familles', config_files_directo... | python | def build_depenses_homogenisees(temporary_store = None, year = None):
"""Build menage consumption by categorie fiscale dataframe """
assert temporary_store is not None
assert year is not None
bdf_survey_collection = SurveyCollection.load(
collection = 'budget_des_familles', config_files_directo... | [
"def",
"build_depenses_homogenisees",
"(",
"temporary_store",
"=",
"None",
",",
"year",
"=",
"None",
")",
":",
"assert",
"temporary_store",
"is",
"not",
"None",
"assert",
"year",
"is",
"not",
"None",
"bdf_survey_collection",
"=",
"SurveyCollection",
".",
"load",
... | Build menage consumption by categorie fiscale dataframe | [
"Build",
"menage",
"consumption",
"by",
"categorie",
"fiscale",
"dataframe"
] | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_1_1_homogeneisation_donnees_depenses.py#L47-L217 |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/step_1_1_homogeneisation_donnees_depenses.py | normalize_code_coicop | def normalize_code_coicop(code):
'''Normalize_coicop est function d'harmonisation de la colonne d'entiers posteCOICOP de la table
matrice_passage_data_frame en la transformant en une chaine de 5 caractères afin de pouvoir par la suite agréger les postes
COICOP selon les 12 postes agrégés de la nomenclature de la co... | python | def normalize_code_coicop(code):
'''Normalize_coicop est function d'harmonisation de la colonne d'entiers posteCOICOP de la table
matrice_passage_data_frame en la transformant en une chaine de 5 caractères afin de pouvoir par la suite agréger les postes
COICOP selon les 12 postes agrégés de la nomenclature de la co... | [
"def",
"normalize_code_coicop",
"(",
"code",
")",
":",
"# TODO: vérifier la formule !!!",
"try",
":",
"code",
"=",
"unicode",
"(",
"code",
")",
"except",
":",
"code",
"=",
"code",
"if",
"len",
"(",
"code",
")",
"==",
"3",
":",
"code_coicop",
"=",
"\"0\"",
... | Normalize_coicop est function d'harmonisation de la colonne d'entiers posteCOICOP de la table
matrice_passage_data_frame en la transformant en une chaine de 5 caractères afin de pouvoir par la suite agréger les postes
COICOP selon les 12 postes agrégés de la nomenclature de la comptabilité nationale. Chaque poste conti... | [
"Normalize_coicop",
"est",
"function",
"d",
"harmonisation",
"de",
"la",
"colonne",
"d",
"entiers",
"posteCOICOP",
"de",
"la",
"table",
"matrice_passage_data_frame",
"en",
"la",
"transformant",
"en",
"une",
"chaine",
"de",
"5",
"caractères",
"afin",
"de",
"pouvoir... | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_1_1_homogeneisation_donnees_depenses.py#L220-L258 |
ff0000/scarlet | scarlet/versioning/manager.py | deactivate | def deactivate():
"""
Deactivate a state in this thread.
"""
if hasattr(_mode, "current_state"):
del _mode.current_state
if hasattr(_mode, "schema"):
del _mode.schema
for k in connections:
con = connections[k]
if hasattr(con, 'reset_schema'):
con.res... | python | def deactivate():
"""
Deactivate a state in this thread.
"""
if hasattr(_mode, "current_state"):
del _mode.current_state
if hasattr(_mode, "schema"):
del _mode.schema
for k in connections:
con = connections[k]
if hasattr(con, 'reset_schema'):
con.res... | [
"def",
"deactivate",
"(",
")",
":",
"if",
"hasattr",
"(",
"_mode",
",",
"\"current_state\"",
")",
":",
"del",
"_mode",
".",
"current_state",
"if",
"hasattr",
"(",
"_mode",
",",
"\"schema\"",
")",
":",
"del",
"_mode",
".",
"schema",
"for",
"k",
"in",
"c... | Deactivate a state in this thread. | [
"Deactivate",
"a",
"state",
"in",
"this",
"thread",
"."
] | train | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/versioning/manager.py#L38-L51 |
cburgmer/upsidedown | util.py | readScriptRanges | def readScriptRanges(scripts=None):
"""
Read script ranges from http://unicode.org/Public/UNIDATA/Scripts.txt file.
"""
scripts = scripts or LATIN_LIKE_SCRIPTS
ranges = []
f = open('Scripts.txt', 'r')
for line in f:
line = line.strip('\n')
matchObj = re.match(
'^... | python | def readScriptRanges(scripts=None):
"""
Read script ranges from http://unicode.org/Public/UNIDATA/Scripts.txt file.
"""
scripts = scripts or LATIN_LIKE_SCRIPTS
ranges = []
f = open('Scripts.txt', 'r')
for line in f:
line = line.strip('\n')
matchObj = re.match(
'^... | [
"def",
"readScriptRanges",
"(",
"scripts",
"=",
"None",
")",
":",
"scripts",
"=",
"scripts",
"or",
"LATIN_LIKE_SCRIPTS",
"ranges",
"=",
"[",
"]",
"f",
"=",
"open",
"(",
"'Scripts.txt'",
",",
"'r'",
")",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line... | Read script ranges from http://unicode.org/Public/UNIDATA/Scripts.txt file. | [
"Read",
"script",
"ranges",
"from",
"http",
":",
"//",
"unicode",
".",
"org",
"/",
"Public",
"/",
"UNIDATA",
"/",
"Scripts",
".",
"txt",
"file",
"."
] | train | https://github.com/cburgmer/upsidedown/blob/0bc80421d197cbda0f824a44ceed5c4fcb5cf8ba/util.py#L6-L29 |
inveniosoftware/invenio-collections | invenio_collections/contrib/dojson.py | collections | def collections(record, key, value):
"""Parse custom MARC tag 980."""
return {
'primary': value.get('a'),
'secondary': value.get('b'),
'deleted': value.get('c'),
} | python | def collections(record, key, value):
"""Parse custom MARC tag 980."""
return {
'primary': value.get('a'),
'secondary': value.get('b'),
'deleted': value.get('c'),
} | [
"def",
"collections",
"(",
"record",
",",
"key",
",",
"value",
")",
":",
"return",
"{",
"'primary'",
":",
"value",
".",
"get",
"(",
"'a'",
")",
",",
"'secondary'",
":",
"value",
".",
"get",
"(",
"'b'",
")",
",",
"'deleted'",
":",
"value",
".",
"get... | Parse custom MARC tag 980. | [
"Parse",
"custom",
"MARC",
"tag",
"980",
"."
] | train | https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/contrib/dojson.py#L32-L38 |
inveniosoftware/invenio-collections | invenio_collections/contrib/dojson.py | reverse_collections | def reverse_collections(self, key, value):
"""Reverse colections field to custom MARC tag 980."""
return {
'a': value.get('primary'),
'b': value.get('secondary'),
'c': value.get('deleted'),
} | python | def reverse_collections(self, key, value):
"""Reverse colections field to custom MARC tag 980."""
return {
'a': value.get('primary'),
'b': value.get('secondary'),
'c': value.get('deleted'),
} | [
"def",
"reverse_collections",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"{",
"'a'",
":",
"value",
".",
"get",
"(",
"'primary'",
")",
",",
"'b'",
":",
"value",
".",
"get",
"(",
"'secondary'",
")",
",",
"'c'",
":",
"value",
".",
"get... | Reverse colections field to custom MARC tag 980. | [
"Reverse",
"colections",
"field",
"to",
"custom",
"MARC",
"tag",
"980",
"."
] | train | https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/contrib/dojson.py#L44-L50 |
klahnakoski/pyLibrary | jx_python/flat_list.py | _select1 | def _select1(data, field, depth, output):
"""
SELECT A SINGLE FIELD
"""
for d in data:
for i, f in enumerate(field[depth:]):
d = d[f]
if d == None:
output.append(None)
break
elif is_list(d):
_select1(d, field, i ... | python | def _select1(data, field, depth, output):
"""
SELECT A SINGLE FIELD
"""
for d in data:
for i, f in enumerate(field[depth:]):
d = d[f]
if d == None:
output.append(None)
break
elif is_list(d):
_select1(d, field, i ... | [
"def",
"_select1",
"(",
"data",
",",
"field",
",",
"depth",
",",
"output",
")",
":",
"for",
"d",
"in",
"data",
":",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"field",
"[",
"depth",
":",
"]",
")",
":",
"d",
"=",
"d",
"[",
"f",
"]",
"if",
... | SELECT A SINGLE FIELD | [
"SELECT",
"A",
"SINGLE",
"FIELD"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_python/flat_list.py#L124-L138 |
spaam/swedbank-cli | pyswedbank/wrapper.py | Swedbank.request | def request(self, url, post=None, method="GET"):
""" Make the request"""
dsid = self.get_dsid()
baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % (
url, dsid)
if self.pch is None:
self.pch = build_opener(HTTPCookieProcessor(self... | python | def request(self, url, post=None, method="GET"):
""" Make the request"""
dsid = self.get_dsid()
baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % (
url, dsid)
if self.pch is None:
self.pch = build_opener(HTTPCookieProcessor(self... | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"post",
"=",
"None",
",",
"method",
"=",
"\"GET\"",
")",
":",
"dsid",
"=",
"self",
".",
"get_dsid",
"(",
")",
"baseurl",
"=",
"\"https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s\"",
"%",
"(",
... | Make the request | [
"Make",
"the",
"request"
] | train | https://github.com/spaam/swedbank-cli/blob/a33702d5a7de424f1f93137dc5be65d2eedbf824/pyswedbank/wrapper.py#L83-L115 |
spaam/swedbank-cli | pyswedbank/wrapper.py | Swedbank.login | def login(self, user, passwd, bank):
""" Login """
logger.info("login...")
if bank not in self.BANKS:
logger.error("Can't find that bank.")
return False
self.useragent = self.BANKS[bank]["u-a"]
self.bankid = self.BANKS[bank]["id"]
login = json.dump... | python | def login(self, user, passwd, bank):
""" Login """
logger.info("login...")
if bank not in self.BANKS:
logger.error("Can't find that bank.")
return False
self.useragent = self.BANKS[bank]["u-a"]
self.bankid = self.BANKS[bank]["id"]
login = json.dump... | [
"def",
"login",
"(",
"self",
",",
"user",
",",
"passwd",
",",
"bank",
")",
":",
"logger",
".",
"info",
"(",
"\"login...\"",
")",
"if",
"bank",
"not",
"in",
"self",
".",
"BANKS",
":",
"logger",
".",
"error",
"(",
"\"Can't find that bank.\"",
")",
"retur... | Login | [
"Login"
] | train | https://github.com/spaam/swedbank-cli/blob/a33702d5a7de424f1f93137dc5be65d2eedbf824/pyswedbank/wrapper.py#L117-L157 |
spaam/swedbank-cli | pyswedbank/wrapper.py | Swedbank.accounts | def accounts(self):
""" Accounts """
logger.info("Fetching data...")
try:
self.request("engagement/overview")
except HTTPError as e:
error = json.loads(e.read().decode("utf8"))
logger.error(error["errorMessages"]["general"][0]["message"])
r... | python | def accounts(self):
""" Accounts """
logger.info("Fetching data...")
try:
self.request("engagement/overview")
except HTTPError as e:
error = json.loads(e.read().decode("utf8"))
logger.error(error["errorMessages"]["general"][0]["message"])
r... | [
"def",
"accounts",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Fetching data...\"",
")",
"try",
":",
"self",
".",
"request",
"(",
"\"engagement/overview\"",
")",
"except",
"HTTPError",
"as",
"e",
":",
"error",
"=",
"json",
".",
"loads",
"(",
"e... | Accounts | [
"Accounts"
] | train | https://github.com/spaam/swedbank-cli/blob/a33702d5a7de424f1f93137dc5be65d2eedbf824/pyswedbank/wrapper.py#L159-L183 |
spaam/swedbank-cli | pyswedbank/wrapper.py | Swedbank.history | def history(self):
""" History """
logger.info("Transactions:")
try:
logger.debug("Account: %s", self.account)
self.request("engagement/transactions/%s" % self.account)
except HTTPError as e:
error = json.loads(e.read().decode("utf8"))
logg... | python | def history(self):
""" History """
logger.info("Transactions:")
try:
logger.debug("Account: %s", self.account)
self.request("engagement/transactions/%s" % self.account)
except HTTPError as e:
error = json.loads(e.read().decode("utf8"))
logg... | [
"def",
"history",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Transactions:\"",
")",
"try",
":",
"logger",
".",
"debug",
"(",
"\"Account: %s\"",
",",
"self",
".",
"account",
")",
"self",
".",
"request",
"(",
"\"engagement/transactions/%s\"",
"%",
... | History | [
"History"
] | train | https://github.com/spaam/swedbank-cli/blob/a33702d5a7de424f1f93137dc5be65d2eedbf824/pyswedbank/wrapper.py#L185-L200 |
ff0000/scarlet | scarlet/cms/forms.py | search_form | def search_form(*fields, **kwargs):
"""
Construct a search form filter form using the fields
provided as arguments to this function.
By default a field will be created for each field passed
and hidden field will be created for search. If you pass
the key work argument `search_only` then only a ... | python | def search_form(*fields, **kwargs):
"""
Construct a search form filter form using the fields
provided as arguments to this function.
By default a field will be created for each field passed
and hidden field will be created for search. If you pass
the key work argument `search_only` then only a ... | [
"def",
"search_form",
"(",
"*",
"fields",
",",
"*",
"*",
"kwargs",
")",
":",
"fdict",
"=",
"{",
"'search_fields'",
":",
"set",
"(",
"fields",
")",
"}",
"if",
"kwargs",
".",
"get",
"(",
"'search_only'",
")",
":",
"fdict",
"[",
"'search'",
"]",
"=",
... | Construct a search form filter form using the fields
provided as arguments to this function.
By default a field will be created for each field passed
and hidden field will be created for search. If you pass
the key work argument `search_only` then only a visible
search field will be created on the ... | [
"Construct",
"a",
"search",
"form",
"filter",
"form",
"using",
"the",
"fields",
"provided",
"as",
"arguments",
"to",
"this",
"function",
"."
] | train | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/forms.py#L134-L163 |
ff0000/scarlet | scarlet/cms/forms.py | BaseFilterForm.get_filter_fields | def get_filter_fields(self, exclude=None):
"""
Get the fields that are normal filter fields
"""
exclude_set = set(self.exclude)
if exclude:
exclude_set = exclude_set.union(set(exclude))
return [name for name in self.fields
if name not in excl... | python | def get_filter_fields(self, exclude=None):
"""
Get the fields that are normal filter fields
"""
exclude_set = set(self.exclude)
if exclude:
exclude_set = exclude_set.union(set(exclude))
return [name for name in self.fields
if name not in excl... | [
"def",
"get_filter_fields",
"(",
"self",
",",
"exclude",
"=",
"None",
")",
":",
"exclude_set",
"=",
"set",
"(",
"self",
".",
"exclude",
")",
"if",
"exclude",
":",
"exclude_set",
"=",
"exclude_set",
".",
"union",
"(",
"set",
"(",
"exclude",
")",
")",
"r... | Get the fields that are normal filter fields | [
"Get",
"the",
"fields",
"that",
"are",
"normal",
"filter",
"fields"
] | train | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/forms.py#L16-L26 |
ff0000/scarlet | scarlet/cms/forms.py | BaseFilterForm.get_search_fields | def get_search_fields(self, exclude=None):
"""
Get the fields for searching for an item.
"""
exclude = set(exclude)
if self.search_fields and len(self.search_fields) > 1:
exclude = exclude.union(self.search_fields)
return self.get_filter_fields(exclude=exclud... | python | def get_search_fields(self, exclude=None):
"""
Get the fields for searching for an item.
"""
exclude = set(exclude)
if self.search_fields and len(self.search_fields) > 1:
exclude = exclude.union(self.search_fields)
return self.get_filter_fields(exclude=exclud... | [
"def",
"get_search_fields",
"(",
"self",
",",
"exclude",
"=",
"None",
")",
":",
"exclude",
"=",
"set",
"(",
"exclude",
")",
"if",
"self",
".",
"search_fields",
"and",
"len",
"(",
"self",
".",
"search_fields",
")",
">",
"1",
":",
"exclude",
"=",
"exclud... | Get the fields for searching for an item. | [
"Get",
"the",
"fields",
"for",
"searching",
"for",
"an",
"item",
"."
] | train | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/forms.py#L28-L36 |
ff0000/scarlet | scarlet/cms/forms.py | BaseFilterForm.get_filter_kwargs | def get_filter_kwargs(self):
"""
Translates the cleaned data into a dictionary
that can used to generate the filter removing
blank values.
"""
if self.is_valid():
filter_kwargs = {}
for field in self.get_filter_fields():
empty_value... | python | def get_filter_kwargs(self):
"""
Translates the cleaned data into a dictionary
that can used to generate the filter removing
blank values.
"""
if self.is_valid():
filter_kwargs = {}
for field in self.get_filter_fields():
empty_value... | [
"def",
"get_filter_kwargs",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_valid",
"(",
")",
":",
"filter_kwargs",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"get_filter_fields",
"(",
")",
":",
"empty_values",
"=",
"EMPTY_VALUES",
"if",
"hasattr",
... | Translates the cleaned data into a dictionary
that can used to generate the filter removing
blank values. | [
"Translates",
"the",
"cleaned",
"data",
"into",
"a",
"dictionary",
"that",
"can",
"used",
"to",
"generate",
"the",
"filter",
"removing",
"blank",
"values",
"."
] | train | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/forms.py#L38-L59 |
ff0000/scarlet | scarlet/cms/forms.py | BaseFilterForm.get_filter | def get_filter(self):
"""
Returns a list of Q objects
that is created by passing for the keyword arguments
from `self.get_filter_kwargs`.
If search_fields are specified and we received
a seach query all search_fields will be queried use
using OR (|) for that term... | python | def get_filter(self):
"""
Returns a list of Q objects
that is created by passing for the keyword arguments
from `self.get_filter_kwargs`.
If search_fields are specified and we received
a seach query all search_fields will be queried use
using OR (|) for that term... | [
"def",
"get_filter",
"(",
"self",
")",
":",
"args",
"=",
"[",
"]",
"filter_kwargs",
"=",
"self",
".",
"get_filter_kwargs",
"(",
")",
"search",
"=",
"filter_kwargs",
".",
"pop",
"(",
"'search'",
",",
"None",
")",
"if",
"search",
"and",
"self",
".",
"sea... | Returns a list of Q objects
that is created by passing for the keyword arguments
from `self.get_filter_kwargs`.
If search_fields are specified and we received
a seach query all search_fields will be queried use
using OR (|) for that term and any specific terms for
those ... | [
"Returns",
"a",
"list",
"of",
"Q",
"objects",
"that",
"is",
"created",
"by",
"passing",
"for",
"the",
"keyword",
"arguments",
"from",
"self",
".",
"get_filter_kwargs",
"."
] | train | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/forms.py#L61-L94 |
klahnakoski/pyLibrary | jx_python/expressions.py | jx_expression_to_function | def jx_expression_to_function(expr):
"""
RETURN FUNCTION THAT REQUIRES PARAMETERS (row, rownum=None, rows=None):
"""
if is_expression(expr):
if is_op(expr, ScriptOp) and not is_text(expr.script):
return expr.script
else:
return compile_expression(Python[expr].to_p... | python | def jx_expression_to_function(expr):
"""
RETURN FUNCTION THAT REQUIRES PARAMETERS (row, rownum=None, rows=None):
"""
if is_expression(expr):
if is_op(expr, ScriptOp) and not is_text(expr.script):
return expr.script
else:
return compile_expression(Python[expr].to_p... | [
"def",
"jx_expression_to_function",
"(",
"expr",
")",
":",
"if",
"is_expression",
"(",
"expr",
")",
":",
"if",
"is_op",
"(",
"expr",
",",
"ScriptOp",
")",
"and",
"not",
"is_text",
"(",
"expr",
".",
"script",
")",
":",
"return",
"expr",
".",
"script",
"... | RETURN FUNCTION THAT REQUIRES PARAMETERS (row, rownum=None, rows=None): | [
"RETURN",
"FUNCTION",
"THAT",
"REQUIRES",
"PARAMETERS",
"(",
"row",
"rownum",
"=",
"None",
"rows",
"=",
"None",
")",
":"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_python/expressions.py#L91-L107 |
dantezhu/melon | melon/melon.py | Melon.make_proc_name | def make_proc_name(self, subtitle):
"""
获取进程名称
:param subtitle:
:return:
"""
proc_name = '[%s:%s %s] %s' % (
constants.NAME,
subtitle,
self.name,
' '.join([sys.executable] + sys.argv)
)
return proc_name | python | def make_proc_name(self, subtitle):
"""
获取进程名称
:param subtitle:
:return:
"""
proc_name = '[%s:%s %s] %s' % (
constants.NAME,
subtitle,
self.name,
' '.join([sys.executable] + sys.argv)
)
return proc_name | [
"def",
"make_proc_name",
"(",
"self",
",",
"subtitle",
")",
":",
"proc_name",
"=",
"'[%s:%s %s] %s'",
"%",
"(",
"constants",
".",
"NAME",
",",
"subtitle",
",",
"self",
".",
"name",
",",
"' '",
".",
"join",
"(",
"[",
"sys",
".",
"executable",
"]",
"+",
... | 获取进程名称
:param subtitle:
:return: | [
"获取进程名称",
":",
"param",
"subtitle",
":",
":",
"return",
":"
] | train | https://github.com/dantezhu/melon/blob/44d859fa85fbfb2d77479e01eade925a0d26e4f7/melon/melon.py#L113-L126 |
dantezhu/melon | melon/melon.py | Melon._validate_cmds | def _validate_cmds(self):
"""
确保 cmd 没有重复
:return:
"""
cmd_list = list(self.rule_map.keys())
for bp in self.blueprints:
cmd_list.extend(bp.rule_map.keys())
duplicate_cmds = (Counter(cmd_list) - Counter(set(cmd_list))).keys()
assert not dupl... | python | def _validate_cmds(self):
"""
确保 cmd 没有重复
:return:
"""
cmd_list = list(self.rule_map.keys())
for bp in self.blueprints:
cmd_list.extend(bp.rule_map.keys())
duplicate_cmds = (Counter(cmd_list) - Counter(set(cmd_list))).keys()
assert not dupl... | [
"def",
"_validate_cmds",
"(",
"self",
")",
":",
"cmd_list",
"=",
"list",
"(",
"self",
".",
"rule_map",
".",
"keys",
"(",
")",
")",
"for",
"bp",
"in",
"self",
".",
"blueprints",
":",
"cmd_list",
".",
"extend",
"(",
"bp",
".",
"rule_map",
".",
"keys",
... | 确保 cmd 没有重复
:return: | [
"确保",
"cmd",
"没有重复",
":",
"return",
":"
] | train | https://github.com/dantezhu/melon/blob/44d859fa85fbfb2d77479e01eade925a0d26e4f7/melon/melon.py#L128-L141 |
dantezhu/melon | melon/melon.py | Melon._init_groups | def _init_groups(self):
"""
初始化group数据
:return:
"""
for group_id, conf in self.group_conf.items():
self.parent_input_dict[group_id] = Queue(conf.get('input_max_size', 0))
self.parent_output_dict[group_id] = Queue(conf.get('output_max_size', 0)) | python | def _init_groups(self):
"""
初始化group数据
:return:
"""
for group_id, conf in self.group_conf.items():
self.parent_input_dict[group_id] = Queue(conf.get('input_max_size', 0))
self.parent_output_dict[group_id] = Queue(conf.get('output_max_size', 0)) | [
"def",
"_init_groups",
"(",
"self",
")",
":",
"for",
"group_id",
",",
"conf",
"in",
"self",
".",
"group_conf",
".",
"items",
"(",
")",
":",
"self",
".",
"parent_input_dict",
"[",
"group_id",
"]",
"=",
"Queue",
"(",
"conf",
".",
"get",
"(",
"'input_max_... | 初始化group数据
:return: | [
"初始化group数据",
":",
"return",
":"
] | train | https://github.com/dantezhu/melon/blob/44d859fa85fbfb2d77479e01eade925a0d26e4f7/melon/melon.py#L143-L150 |
dantezhu/melon | melon/melon.py | Melon._spawn_poll_worker_result_thread | def _spawn_poll_worker_result_thread(self):
"""
启动获取worker数据的线程
"""
for group_id in self.group_conf:
thread = Thread(target=self._poll_worker_result, args=(group_id,))
thread.daemon = True
thread.start() | python | def _spawn_poll_worker_result_thread(self):
"""
启动获取worker数据的线程
"""
for group_id in self.group_conf:
thread = Thread(target=self._poll_worker_result, args=(group_id,))
thread.daemon = True
thread.start() | [
"def",
"_spawn_poll_worker_result_thread",
"(",
"self",
")",
":",
"for",
"group_id",
"in",
"self",
".",
"group_conf",
":",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_poll_worker_result",
",",
"args",
"=",
"(",
"group_id",
",",
")",
")",
"t... | 启动获取worker数据的线程 | [
"启动获取worker数据的线程"
] | train | https://github.com/dantezhu/melon/blob/44d859fa85fbfb2d77479e01eade925a0d26e4f7/melon/melon.py#L152-L159 |
dantezhu/melon | melon/melon.py | Melon._spawn_fork_workers | def _spawn_fork_workers(self):
"""
通过线程启动多个worker
"""
thread = Thread(target=self._fork_workers, args=())
thread.daemon = True
thread.start() | python | def _spawn_fork_workers(self):
"""
通过线程启动多个worker
"""
thread = Thread(target=self._fork_workers, args=())
thread.daemon = True
thread.start() | [
"def",
"_spawn_fork_workers",
"(",
"self",
")",
":",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_fork_workers",
",",
"args",
"=",
"(",
")",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
")"
] | 通过线程启动多个worker | [
"通过线程启动多个worker"
] | train | https://github.com/dantezhu/melon/blob/44d859fa85fbfb2d77479e01eade925a0d26e4f7/melon/melon.py#L161-L167 |
dantezhu/melon | melon/melon.py | Melon._poll_worker_result | def _poll_worker_result(self, group_id):
"""
从队列里面获取worker的返回
"""
while 1:
try:
msg = self.parent_input_dict[group_id].get()
except KeyboardInterrupt:
break
except:
logger.error('exc occur.', exc_info=Tru... | python | def _poll_worker_result(self, group_id):
"""
从队列里面获取worker的返回
"""
while 1:
try:
msg = self.parent_input_dict[group_id].get()
except KeyboardInterrupt:
break
except:
logger.error('exc occur.', exc_info=Tru... | [
"def",
"_poll_worker_result",
"(",
"self",
",",
"group_id",
")",
":",
"while",
"1",
":",
"try",
":",
"msg",
"=",
"self",
".",
"parent_input_dict",
"[",
"group_id",
"]",
".",
"get",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"break",
"except",
":",
"lo... | 从队列里面获取worker的返回 | [
"从队列里面获取worker的返回"
] | train | https://github.com/dantezhu/melon/blob/44d859fa85fbfb2d77479e01eade925a0d26e4f7/melon/melon.py#L211-L225 |
cathalgarvey/deadlock | deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py | get_ranked_english | def get_ranked_english():
'''
wikitionary has a list of ~40k English words, ranked by frequency of occurance in TV and movie transcripts.
more details at:
http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/TV/2006/explanation
the list is separated into pages of 1000 or 2000 terms each.
* ... | python | def get_ranked_english():
'''
wikitionary has a list of ~40k English words, ranked by frequency of occurance in TV and movie transcripts.
more details at:
http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/TV/2006/explanation
the list is separated into pages of 1000 or 2000 terms each.
* ... | [
"def",
"get_ranked_english",
"(",
")",
":",
"URL_TMPL",
"=",
"'http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/TV/2006/%s'",
"urls",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"freq_range",
"=",
"\"%d-%d\"",
"%",
"(",
"i",
"*",
"1000... | wikitionary has a list of ~40k English words, ranked by frequency of occurance in TV and movie transcripts.
more details at:
http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/TV/2006/explanation
the list is separated into pages of 1000 or 2000 terms each.
* the first 10k words are separated into... | [
"wikitionary",
"has",
"a",
"list",
"of",
"~40k",
"English",
"words",
"ranked",
"by",
"frequency",
"of",
"occurance",
"in",
"TV",
"and",
"movie",
"transcripts",
".",
"more",
"details",
"at",
":",
"http",
":",
"//",
"en",
".",
"wiktionary",
".",
"org",
"/"... | train | https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py#L15-L45 |
cathalgarvey/deadlock | deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py | wiki_download | def wiki_download(url):
'''
scrape friendly: sleep 20 seconds between each request, cache each result.
'''
DOWNLOAD_TMPL = '../data/tv_and_movie_freqlist%s.html'
freq_range = url[url.rindex('/')+1:]
tmp_path = DOWNLOAD_TMPL % freq_range
if os.path.exists(tmp_path):
print('cached....... | python | def wiki_download(url):
'''
scrape friendly: sleep 20 seconds between each request, cache each result.
'''
DOWNLOAD_TMPL = '../data/tv_and_movie_freqlist%s.html'
freq_range = url[url.rindex('/')+1:]
tmp_path = DOWNLOAD_TMPL % freq_range
if os.path.exists(tmp_path):
print('cached....... | [
"def",
"wiki_download",
"(",
"url",
")",
":",
"DOWNLOAD_TMPL",
"=",
"'../data/tv_and_movie_freqlist%s.html'",
"freq_range",
"=",
"url",
"[",
"url",
".",
"rindex",
"(",
"'/'",
")",
"+",
"1",
":",
"]",
"tmp_path",
"=",
"DOWNLOAD_TMPL",
"%",
"freq_range",
"if",
... | scrape friendly: sleep 20 seconds between each request, cache each result. | [
"scrape",
"friendly",
":",
"sleep",
"20",
"seconds",
"between",
"each",
"request",
"cache",
"each",
"result",
"."
] | train | https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py#L47-L67 |
cathalgarvey/deadlock | deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py | parse_wiki_terms | def parse_wiki_terms(doc):
'''who needs an html parser. fragile hax, but checks the result at the end'''
results = []
last3 = ['', '', '']
header = True
for line in doc.split('\n'):
last3.pop(0)
last3.append(line.strip())
if all(s.startswith('<td>') and not s == '<td></td>' f... | python | def parse_wiki_terms(doc):
'''who needs an html parser. fragile hax, but checks the result at the end'''
results = []
last3 = ['', '', '']
header = True
for line in doc.split('\n'):
last3.pop(0)
last3.append(line.strip())
if all(s.startswith('<td>') and not s == '<td></td>' f... | [
"def",
"parse_wiki_terms",
"(",
"doc",
")",
":",
"results",
"=",
"[",
"]",
"last3",
"=",
"[",
"''",
",",
"''",
",",
"''",
"]",
"header",
"=",
"True",
"for",
"line",
"in",
"doc",
".",
"split",
"(",
"'\\n'",
")",
":",
"last3",
".",
"pop",
"(",
"0... | who needs an html parser. fragile hax, but checks the result at the end | [
"who",
"needs",
"an",
"html",
"parser",
".",
"fragile",
"hax",
"but",
"checks",
"the",
"result",
"at",
"the",
"end"
] | train | https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py#L69-L88 |
cathalgarvey/deadlock | deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py | get_ranked_census_names | def get_ranked_census_names():
'''
takes name lists from the the 2000 us census, prepares as a json array in order of frequency (most common names first).
more info:
http://www.census.gov/genealogy/www/data/2000surnames/index.html
files in data are downloaded copies of:
http://www.census.gov/g... | python | def get_ranked_census_names():
'''
takes name lists from the the 2000 us census, prepares as a json array in order of frequency (most common names first).
more info:
http://www.census.gov/genealogy/www/data/2000surnames/index.html
files in data are downloaded copies of:
http://www.census.gov/g... | [
"def",
"get_ranked_census_names",
"(",
")",
":",
"FILE_TMPL",
"=",
"'../data/us_census_2000_%s.txt'",
"SURNAME_CUTOFF_PERCENTILE",
"=",
"85",
"# ie7 can't handle huge lists. cut surname list off at a certain percentile.",
"lists",
"=",
"[",
"]",
"for",
"list_name",
"in",
"[",
... | takes name lists from the the 2000 us census, prepares as a json array in order of frequency (most common names first).
more info:
http://www.census.gov/genealogy/www/data/2000surnames/index.html
files in data are downloaded copies of:
http://www.census.gov/genealogy/names/dist.all.last
http://www... | [
"takes",
"name",
"lists",
"from",
"the",
"the",
"2000",
"us",
"census",
"prepares",
"as",
"a",
"json",
"array",
"in",
"order",
"of",
"frequency",
"(",
"most",
"common",
"names",
"first",
")",
"."
] | train | https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py#L90-L115 |
cathalgarvey/deadlock | deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py | filter_short | def filter_short(terms):
'''
only keep if brute-force possibilities are greater than this word's rank in the dictionary
'''
return [term for i, term in enumerate(terms) if 26**(len(term)) > i] | python | def filter_short(terms):
'''
only keep if brute-force possibilities are greater than this word's rank in the dictionary
'''
return [term for i, term in enumerate(terms) if 26**(len(term)) > i] | [
"def",
"filter_short",
"(",
"terms",
")",
":",
"return",
"[",
"term",
"for",
"i",
",",
"term",
"in",
"enumerate",
"(",
"terms",
")",
"if",
"26",
"**",
"(",
"len",
"(",
"term",
")",
")",
">",
"i",
"]"
] | only keep if brute-force possibilities are greater than this word's rank in the dictionary | [
"only",
"keep",
"if",
"brute",
"-",
"force",
"possibilities",
"are",
"greater",
"than",
"this",
"word",
"s",
"rank",
"in",
"the",
"dictionary"
] | train | https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py#L127-L131 |
cathalgarvey/deadlock | deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py | filter_dup | def filter_dup(lst, lists):
'''
filters lst to only include terms that don't have lower rank in another list
'''
max_rank = len(lst) + 1
dct = to_ranked_dict(lst)
dicts = [to_ranked_dict(l) for l in lists]
return [word for word in lst if all(dct[word] < dct2.get(word, max_rank) for dct2 in d... | python | def filter_dup(lst, lists):
'''
filters lst to only include terms that don't have lower rank in another list
'''
max_rank = len(lst) + 1
dct = to_ranked_dict(lst)
dicts = [to_ranked_dict(l) for l in lists]
return [word for word in lst if all(dct[word] < dct2.get(word, max_rank) for dct2 in d... | [
"def",
"filter_dup",
"(",
"lst",
",",
"lists",
")",
":",
"max_rank",
"=",
"len",
"(",
"lst",
")",
"+",
"1",
"dct",
"=",
"to_ranked_dict",
"(",
"lst",
")",
"dicts",
"=",
"[",
"to_ranked_dict",
"(",
"l",
")",
"for",
"l",
"in",
"lists",
"]",
"return",... | filters lst to only include terms that don't have lower rank in another list | [
"filters",
"lst",
"to",
"only",
"include",
"terms",
"that",
"don",
"t",
"have",
"lower",
"rank",
"in",
"another",
"list"
] | train | https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py#L133-L140 |
cathalgarvey/deadlock | deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py | filter_ascii | def filter_ascii(lst):
'''
removes words with accent chars etc.
(most accented words in the english lookup exist in the same table unaccented.)
'''
return [word for word in lst if all(ord(c) < 128 for c in word)] | python | def filter_ascii(lst):
'''
removes words with accent chars etc.
(most accented words in the english lookup exist in the same table unaccented.)
'''
return [word for word in lst if all(ord(c) < 128 for c in word)] | [
"def",
"filter_ascii",
"(",
"lst",
")",
":",
"return",
"[",
"word",
"for",
"word",
"in",
"lst",
"if",
"all",
"(",
"ord",
"(",
"c",
")",
"<",
"128",
"for",
"c",
"in",
"word",
")",
"]"
] | removes words with accent chars etc.
(most accented words in the english lookup exist in the same table unaccented.) | [
"removes",
"words",
"with",
"accent",
"chars",
"etc",
".",
"(",
"most",
"accented",
"words",
"in",
"the",
"english",
"lookup",
"exist",
"in",
"the",
"same",
"table",
"unaccented",
".",
")"
] | train | https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/passwords/zxcvbn/scripts/build_frequency_lists.py#L142-L147 |
note35/sinon | sinon/lib/matcher.py | Matcher.__get_type | def __get_type(self, expectation, options):
"""
Determining the type of Matcher
Return: string
"""
if "is_custom_func" in options.keys():
setattr(self, "mtest", expectation)
return "CUSTOMFUNC"
elif "is_substring" in options.keys():
ret... | python | def __get_type(self, expectation, options):
"""
Determining the type of Matcher
Return: string
"""
if "is_custom_func" in options.keys():
setattr(self, "mtest", expectation)
return "CUSTOMFUNC"
elif "is_substring" in options.keys():
ret... | [
"def",
"__get_type",
"(",
"self",
",",
"expectation",
",",
"options",
")",
":",
"if",
"\"is_custom_func\"",
"in",
"options",
".",
"keys",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"\"mtest\"",
",",
"expectation",
")",
"return",
"\"CUSTOMFUNC\"",
"elif",
... | Determining the type of Matcher
Return: string | [
"Determining",
"the",
"type",
"of",
"Matcher",
"Return",
":",
"string"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/matcher.py#L21-L36 |
note35/sinon | sinon/lib/matcher.py | Matcher.__value_compare | def __value_compare(self, target):
"""
Comparing result based on expectation if arg_type is "VALUE"
Args: Anything
Return: Boolean
"""
if self.expectation == "__ANY__":
return True
elif self.expectation == "__DEFINED__":
return True if targ... | python | def __value_compare(self, target):
"""
Comparing result based on expectation if arg_type is "VALUE"
Args: Anything
Return: Boolean
"""
if self.expectation == "__ANY__":
return True
elif self.expectation == "__DEFINED__":
return True if targ... | [
"def",
"__value_compare",
"(",
"self",
",",
"target",
")",
":",
"if",
"self",
".",
"expectation",
"==",
"\"__ANY__\"",
":",
"return",
"True",
"elif",
"self",
".",
"expectation",
"==",
"\"__DEFINED__\"",
":",
"return",
"True",
"if",
"target",
"is",
"not",
"... | Comparing result based on expectation if arg_type is "VALUE"
Args: Anything
Return: Boolean | [
"Comparing",
"result",
"based",
"on",
"expectation",
"if",
"arg_type",
"is",
"VALUE",
"Args",
":",
"Anything",
"Return",
":",
"Boolean"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/matcher.py#L46-L61 |
note35/sinon | sinon/lib/matcher.py | Matcher.__get_match_result | def __get_match_result(self, ret, ret2):
"""
Getting match result
"""
if self.another_compare == "__MATCH_AND__":
return ret and ret2
elif self.another_compare == "__MATCH_OR__":
return ret or ret2
return ret | python | def __get_match_result(self, ret, ret2):
"""
Getting match result
"""
if self.another_compare == "__MATCH_AND__":
return ret and ret2
elif self.another_compare == "__MATCH_OR__":
return ret or ret2
return ret | [
"def",
"__get_match_result",
"(",
"self",
",",
"ret",
",",
"ret2",
")",
":",
"if",
"self",
".",
"another_compare",
"==",
"\"__MATCH_AND__\"",
":",
"return",
"ret",
"and",
"ret2",
"elif",
"self",
".",
"another_compare",
"==",
"\"__MATCH_OR__\"",
":",
"return",
... | Getting match result | [
"Getting",
"match",
"result"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/matcher.py#L77-L85 |
note35/sinon | sinon/lib/matcher.py | SinonMatcher.typeOf | def typeOf(cls, expected_type): #pylint: disable=no-self-argument,invalid-name,no-self-use
"""
(*Type does NOT consider inherited class)
Matcher.mtest(...) will return True if type(...) == expected_type
Return: Matcher
Raise: matcher_type_error
"""
if isinstance(e... | python | def typeOf(cls, expected_type): #pylint: disable=no-self-argument,invalid-name,no-self-use
"""
(*Type does NOT consider inherited class)
Matcher.mtest(...) will return True if type(...) == expected_type
Return: Matcher
Raise: matcher_type_error
"""
if isinstance(e... | [
"def",
"typeOf",
"(",
"cls",
",",
"expected_type",
")",
":",
"#pylint: disable=no-self-argument,invalid-name,no-self-use",
"if",
"isinstance",
"(",
"expected_type",
",",
"type",
")",
":",
"options",
"=",
"{",
"}",
"options",
"[",
"\"target_type\"",
"]",
"=",
"expe... | (*Type does NOT consider inherited class)
Matcher.mtest(...) will return True if type(...) == expected_type
Return: Matcher
Raise: matcher_type_error | [
"(",
"*",
"Type",
"does",
"NOT",
"consider",
"inherited",
"class",
")",
"Matcher",
".",
"mtest",
"(",
"...",
")",
"will",
"return",
"True",
"if",
"type",
"(",
"...",
")",
"==",
"expected_type",
"Return",
":",
"Matcher",
"Raise",
":",
"matcher_type_error"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/matcher.py#L210-L221 |
note35/sinon | sinon/lib/matcher.py | SinonMatcher.instanceOf | def instanceOf(cls, expected_instance): #pylint: disable=no-self-argument,invalid-name,no-self-use
"""
(*Instance consider inherited class)
Matcher.mtest(...) will return True if instance(...) == expected_instance
Return: Matcher
Raise: matcher_instance_error
"""
... | python | def instanceOf(cls, expected_instance): #pylint: disable=no-self-argument,invalid-name,no-self-use
"""
(*Instance consider inherited class)
Matcher.mtest(...) will return True if instance(...) == expected_instance
Return: Matcher
Raise: matcher_instance_error
"""
... | [
"def",
"instanceOf",
"(",
"cls",
",",
"expected_instance",
")",
":",
"#pylint: disable=no-self-argument,invalid-name,no-self-use",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"expected_instance",
")",
":",
"options",
"=",
"{",
"}",
"options",
"[",
"\"target_type\"",
... | (*Instance consider inherited class)
Matcher.mtest(...) will return True if instance(...) == expected_instance
Return: Matcher
Raise: matcher_instance_error | [
"(",
"*",
"Instance",
"consider",
"inherited",
"class",
")",
"Matcher",
".",
"mtest",
"(",
"...",
")",
"will",
"return",
"True",
"if",
"instance",
"(",
"...",
")",
"==",
"expected_instance",
"Return",
":",
"Matcher",
"Raise",
":",
"matcher_instance_error"
] | train | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/matcher.py#L224-L235 |
klahnakoski/pyLibrary | jx_python/containers/doc_store.py | DocStore._sort | def _sort(self, short_list, sorts):
"""
TAKE SHORTLIST, RETURN IT SORTED
:param short_list:
:param sorts: LIST OF SORTS TO PERFORM
:return:
"""
sort_values = self._index_columns(sorts)
# RECURSIVE SORTING
output = []
def _sort_more(short_... | python | def _sort(self, short_list, sorts):
"""
TAKE SHORTLIST, RETURN IT SORTED
:param short_list:
:param sorts: LIST OF SORTS TO PERFORM
:return:
"""
sort_values = self._index_columns(sorts)
# RECURSIVE SORTING
output = []
def _sort_more(short_... | [
"def",
"_sort",
"(",
"self",
",",
"short_list",
",",
"sorts",
")",
":",
"sort_values",
"=",
"self",
".",
"_index_columns",
"(",
"sorts",
")",
"# RECURSIVE SORTING",
"output",
"=",
"[",
"]",
"def",
"_sort_more",
"(",
"short_list",
",",
"i",
",",
"sorts",
... | TAKE SHORTLIST, RETURN IT SORTED
:param short_list:
:param sorts: LIST OF SORTS TO PERFORM
:return: | [
"TAKE",
"SHORTLIST",
"RETURN",
"IT",
"SORTED",
":",
"param",
"short_list",
":",
":",
"param",
"sorts",
":",
"LIST",
"OF",
"SORTS",
"TO",
"PERFORM",
":",
"return",
":"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_python/containers/doc_store.py#L144-L174 |
jforman/pybindxml | pybindxml/reader.py | BindXmlReader.gather_xml | def gather_xml(self):
"""Attempt to read the XML, whether from a file on-disk or via host:port.
TODO: handle when you cant gather stats, due to bad hostname
"""
if self.xml_filepath:
with open(self.xml_filepath, "r") as xml_fh:
self.raw_xml = xml_fh.read()
... | python | def gather_xml(self):
"""Attempt to read the XML, whether from a file on-disk or via host:port.
TODO: handle when you cant gather stats, due to bad hostname
"""
if self.xml_filepath:
with open(self.xml_filepath, "r") as xml_fh:
self.raw_xml = xml_fh.read()
... | [
"def",
"gather_xml",
"(",
"self",
")",
":",
"if",
"self",
".",
"xml_filepath",
":",
"with",
"open",
"(",
"self",
".",
"xml_filepath",
",",
"\"r\"",
")",
"as",
"xml_fh",
":",
"self",
".",
"raw_xml",
"=",
"xml_fh",
".",
"read",
"(",
")",
"self",
".",
... | Attempt to read the XML, whether from a file on-disk or via host:port.
TODO: handle when you cant gather stats, due to bad hostname | [
"Attempt",
"to",
"read",
"the",
"XML",
"whether",
"from",
"a",
"file",
"on",
"-",
"disk",
"or",
"via",
"host",
":",
"port",
"."
] | train | https://github.com/jforman/pybindxml/blob/795fd5b1fab85e2debad8655888e2d52ef8dce5f/pybindxml/reader.py#L33-L49 |
jforman/pybindxml | pybindxml/reader.py | BindXmlReader.get_stats | def get_stats(self):
"""Given XML version, parse create XMLAbstract object and sets xml_stats attribute."""
self.gather_xml()
self.xml_version = self.bs_xml.find('statistics')['version']
if self.xml_version is None:
raise XmlError("Unable to determine XML version via 'statis... | python | def get_stats(self):
"""Given XML version, parse create XMLAbstract object and sets xml_stats attribute."""
self.gather_xml()
self.xml_version = self.bs_xml.find('statistics')['version']
if self.xml_version is None:
raise XmlError("Unable to determine XML version via 'statis... | [
"def",
"get_stats",
"(",
"self",
")",
":",
"self",
".",
"gather_xml",
"(",
")",
"self",
".",
"xml_version",
"=",
"self",
".",
"bs_xml",
".",
"find",
"(",
"'statistics'",
")",
"[",
"'version'",
"]",
"if",
"self",
".",
"xml_version",
"is",
"None",
":",
... | Given XML version, parse create XMLAbstract object and sets xml_stats attribute. | [
"Given",
"XML",
"version",
"parse",
"create",
"XMLAbstract",
"object",
"and",
"sets",
"xml_stats",
"attribute",
"."
] | train | https://github.com/jforman/pybindxml/blob/795fd5b1fab85e2debad8655888e2d52ef8dce5f/pybindxml/reader.py#L51-L68 |
klahnakoski/pyLibrary | mo_math/stats.py | median | def median(values, simple=True, mean_weight=0.0):
"""
RETURN MEDIAN VALUE
IF simple=False THEN IN THE EVENT MULTIPLE INSTANCES OF THE
MEDIAN VALUE, THE MEDIAN IS INTERPOLATED BASED ON ITS POSITION
IN THE MEDIAN RANGE
mean_weight IS TO PICK A MEDIAN VALUE IN THE ODD CASE THAT IS
CLOSER TO T... | python | def median(values, simple=True, mean_weight=0.0):
"""
RETURN MEDIAN VALUE
IF simple=False THEN IN THE EVENT MULTIPLE INSTANCES OF THE
MEDIAN VALUE, THE MEDIAN IS INTERPOLATED BASED ON ITS POSITION
IN THE MEDIAN RANGE
mean_weight IS TO PICK A MEDIAN VALUE IN THE ODD CASE THAT IS
CLOSER TO T... | [
"def",
"median",
"(",
"values",
",",
"simple",
"=",
"True",
",",
"mean_weight",
"=",
"0.0",
")",
":",
"if",
"OR",
"(",
"v",
"==",
"None",
"for",
"v",
"in",
"values",
")",
":",
"Log",
".",
"error",
"(",
"\"median is not ready to handle None\"",
")",
"tr... | RETURN MEDIAN VALUE
IF simple=False THEN IN THE EVENT MULTIPLE INSTANCES OF THE
MEDIAN VALUE, THE MEDIAN IS INTERPOLATED BASED ON ITS POSITION
IN THE MEDIAN RANGE
mean_weight IS TO PICK A MEDIAN VALUE IN THE ODD CASE THAT IS
CLOSER TO THE MEAN (PICK A MEDIAN BETWEEN TWO MODES IN BIMODAL CASE) | [
"RETURN",
"MEDIAN",
"VALUE"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/stats.py#L295-L350 |
klahnakoski/pyLibrary | mo_math/stats.py | percentile | def percentile(values, percent):
"""
PERCENTILE WITH INTERPOLATION
RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES
snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/
"""
N = sorted(values)
if not N:
return None
k = (len(N) - 1) * pe... | python | def percentile(values, percent):
"""
PERCENTILE WITH INTERPOLATION
RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES
snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/
"""
N = sorted(values)
if not N:
return None
k = (len(N) - 1) * pe... | [
"def",
"percentile",
"(",
"values",
",",
"percent",
")",
":",
"N",
"=",
"sorted",
"(",
"values",
")",
"if",
"not",
"N",
":",
"return",
"None",
"k",
"=",
"(",
"len",
"(",
"N",
")",
"-",
"1",
")",
"*",
"percent",
"f",
"=",
"int",
"(",
"math",
"... | PERCENTILE WITH INTERPOLATION
RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES
snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/ | [
"PERCENTILE",
"WITH",
"INTERPOLATION",
"RETURN",
"VALUE",
"AT",
"OR",
"ABOVE",
"percentile",
"OF",
"THE",
"VALUES"
] | train | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/stats.py#L353-L370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.