repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
fvdsn/py-xml-escpos | xmlescpos/printer.py | Network.open | def open(self):
""" Open TCP socket and set it as escpos device """
self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.device.connect((self.host, self.port))
if self.device is None:
print "Could not open socket for %s" % self.host | python | def open(self):
""" Open TCP socket and set it as escpos device """
self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.device.connect((self.host, self.port))
if self.device is None:
print "Could not open socket for %s" % self.host | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"device",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"device",
".",
"connect",
"(",
"(",
"self",
".",
"host",
",",
"self",
"."... | Open TCP socket and set it as escpos device | [
"Open",
"TCP",
"socket",
"and",
"set",
"it",
"as",
"escpos",
"device"
] | 7f77e039c960d5773fb919aed02ba392dccbc360 | https://github.com/fvdsn/py-xml-escpos/blob/7f77e039c960d5773fb919aed02ba392dccbc360/xmlescpos/printer.py#L186-L192 | train |
lxyu/pinyin | pinyin/pinyin.py | _pinyin_generator | def _pinyin_generator(chars, format):
"""Generate pinyin for chars, if char is not chinese character,
itself will be returned.
Chars must be unicode list.
"""
for char in chars:
key = "%X" % ord(char)
pinyin = pinyin_dict.get(key, char)
tone = pinyin_tone.get(key, 0)
... | python | def _pinyin_generator(chars, format):
"""Generate pinyin for chars, if char is not chinese character,
itself will be returned.
Chars must be unicode list.
"""
for char in chars:
key = "%X" % ord(char)
pinyin = pinyin_dict.get(key, char)
tone = pinyin_tone.get(key, 0)
... | [
"def",
"_pinyin_generator",
"(",
"chars",
",",
"format",
")",
":",
"for",
"char",
"in",
"chars",
":",
"key",
"=",
"\"%X\"",
"%",
"ord",
"(",
"char",
")",
"pinyin",
"=",
"pinyin_dict",
".",
"get",
"(",
"key",
",",
"char",
")",
"tone",
"=",
"pinyin_ton... | Generate pinyin for chars, if char is not chinese character,
itself will be returned.
Chars must be unicode list. | [
"Generate",
"pinyin",
"for",
"chars",
"if",
"char",
"is",
"not",
"chinese",
"character",
"itself",
"will",
"be",
"returned",
".",
"Chars",
"must",
"be",
"unicode",
"list",
"."
] | f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd | https://github.com/lxyu/pinyin/blob/f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd/pinyin/pinyin.py#L23-L47 | train |
lxyu/pinyin | pinyin/pinyin.py | get | def get(s, delimiter='', format="diacritical"):
"""Return pinyin of string, the string must be unicode
"""
return delimiter.join(_pinyin_generator(u(s), format=format)) | python | def get(s, delimiter='', format="diacritical"):
"""Return pinyin of string, the string must be unicode
"""
return delimiter.join(_pinyin_generator(u(s), format=format)) | [
"def",
"get",
"(",
"s",
",",
"delimiter",
"=",
"''",
",",
"format",
"=",
"\"diacritical\"",
")",
":",
"return",
"delimiter",
".",
"join",
"(",
"_pinyin_generator",
"(",
"u",
"(",
"s",
")",
",",
"format",
"=",
"format",
")",
")"
] | Return pinyin of string, the string must be unicode | [
"Return",
"pinyin",
"of",
"string",
"the",
"string",
"must",
"be",
"unicode"
] | f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd | https://github.com/lxyu/pinyin/blob/f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd/pinyin/pinyin.py#L50-L53 | train |
lxyu/pinyin | pinyin/pinyin.py | get_initial | def get_initial(s, delimiter=' '):
"""Return the 1st char of pinyin of string, the string must be unicode
"""
initials = (p[0] for p in _pinyin_generator(u(s), format="strip"))
return delimiter.join(initials) | python | def get_initial(s, delimiter=' '):
"""Return the 1st char of pinyin of string, the string must be unicode
"""
initials = (p[0] for p in _pinyin_generator(u(s), format="strip"))
return delimiter.join(initials) | [
"def",
"get_initial",
"(",
"s",
",",
"delimiter",
"=",
"' '",
")",
":",
"initials",
"=",
"(",
"p",
"[",
"0",
"]",
"for",
"p",
"in",
"_pinyin_generator",
"(",
"u",
"(",
"s",
")",
",",
"format",
"=",
"\"strip\"",
")",
")",
"return",
"delimiter",
".",... | Return the 1st char of pinyin of string, the string must be unicode | [
"Return",
"the",
"1st",
"char",
"of",
"pinyin",
"of",
"string",
"the",
"string",
"must",
"be",
"unicode"
] | f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd | https://github.com/lxyu/pinyin/blob/f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd/pinyin/pinyin.py#L64-L68 | train |
lxyu/pinyin | pinyin/cedict.py | _add_to_tree | def _add_to_tree(tree, word, meaning):
'''
We build word search trees, where we walk down
the letters of a word. For example:
你 Good
你好 Hello
Would build the tree
你
/ \
You 好
\
Hello
'''
if len(word) == 0:
tree[''] = meaning
... | python | def _add_to_tree(tree, word, meaning):
'''
We build word search trees, where we walk down
the letters of a word. For example:
你 Good
你好 Hello
Would build the tree
你
/ \
You 好
\
Hello
'''
if len(word) == 0:
tree[''] = meaning
... | [
"def",
"_add_to_tree",
"(",
"tree",
",",
"word",
",",
"meaning",
")",
":",
"if",
"len",
"(",
"word",
")",
"==",
"0",
":",
"tree",
"[",
"''",
"]",
"=",
"meaning",
"else",
":",
"_add_to_tree",
"(",
"tree",
"[",
"word",
"[",
"0",
"]",
"]",
",",
"w... | We build word search trees, where we walk down
the letters of a word. For example:
你 Good
你好 Hello
Would build the tree
你
/ \
You 好
\
Hello | [
"We",
"build",
"word",
"search",
"trees",
"where",
"we",
"walk",
"down",
"the",
"letters",
"of",
"a",
"word",
".",
"For",
"example",
":",
"你",
"Good",
"你好",
"Hello",
"Would",
"build",
"the",
"tree",
"你",
"/",
"\\",
"You",
"好",
"\\",
"Hello"
] | f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd | https://github.com/lxyu/pinyin/blob/f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd/pinyin/cedict.py#L36-L52 | train |
lxyu/pinyin | pinyin/cedict.py | init | def init():
'''
Load in the Chinese-English dictionary. This takes 1-2 seconds. It
is done when the other functions are used, but this is public since
preloading sometimes makes sense.
'''
global dictionaries, trees
dictionaries = {
'traditional': {},
'simplified': {}
}
... | python | def init():
'''
Load in the Chinese-English dictionary. This takes 1-2 seconds. It
is done when the other functions are used, but this is public since
preloading sometimes makes sense.
'''
global dictionaries, trees
dictionaries = {
'traditional': {},
'simplified': {}
}
... | [
"def",
"init",
"(",
")",
":",
"global",
"dictionaries",
",",
"trees",
"dictionaries",
"=",
"{",
"'traditional'",
":",
"{",
"}",
",",
"'simplified'",
":",
"{",
"}",
"}",
"trees",
"=",
"{",
"'traditional'",
":",
"Tree",
"(",
")",
",",
"'simplified'",
":"... | Load in the Chinese-English dictionary. This takes 1-2 seconds. It
is done when the other functions are used, but this is public since
preloading sometimes makes sense. | [
"Load",
"in",
"the",
"Chinese",
"-",
"English",
"dictionary",
".",
"This",
"takes",
"1",
"-",
"2",
"seconds",
".",
"It",
"is",
"done",
"when",
"the",
"other",
"functions",
"are",
"used",
"but",
"this",
"is",
"public",
"since",
"preloading",
"sometimes",
... | f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd | https://github.com/lxyu/pinyin/blob/f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd/pinyin/cedict.py#L55-L88 | train |
lxyu/pinyin | pinyin/cedict.py | translate_word | def translate_word(word, dictionary=['simplified']):
'''
Return the set of translations for a single character or word, if
available.
'''
if not dictionaries:
init()
for d in dictionary:
if word in dictionaries[d]:
return dictionaries[d][word]
return None | python | def translate_word(word, dictionary=['simplified']):
'''
Return the set of translations for a single character or word, if
available.
'''
if not dictionaries:
init()
for d in dictionary:
if word in dictionaries[d]:
return dictionaries[d][word]
return None | [
"def",
"translate_word",
"(",
"word",
",",
"dictionary",
"=",
"[",
"'simplified'",
"]",
")",
":",
"if",
"not",
"dictionaries",
":",
"init",
"(",
")",
"for",
"d",
"in",
"dictionary",
":",
"if",
"word",
"in",
"dictionaries",
"[",
"d",
"]",
":",
"return",... | Return the set of translations for a single character or word, if
available. | [
"Return",
"the",
"set",
"of",
"translations",
"for",
"a",
"single",
"character",
"or",
"word",
"if",
"available",
"."
] | f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd | https://github.com/lxyu/pinyin/blob/f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd/pinyin/cedict.py#L91-L101 | train |
lxyu/pinyin | pinyin/cedict.py | _words_at_the_beginning | def _words_at_the_beginning(word, tree, prefix=""):
'''
We return all portions of the tree corresponding to the beginning
of `word`. This is used recursively, so we pass the prefix so we
can return meaningful words+translations.
'''
l = []
if "" in tree:
l.append([prefix, tree[""]])
... | python | def _words_at_the_beginning(word, tree, prefix=""):
'''
We return all portions of the tree corresponding to the beginning
of `word`. This is used recursively, so we pass the prefix so we
can return meaningful words+translations.
'''
l = []
if "" in tree:
l.append([prefix, tree[""]])
... | [
"def",
"_words_at_the_beginning",
"(",
"word",
",",
"tree",
",",
"prefix",
"=",
"\"\"",
")",
":",
"l",
"=",
"[",
"]",
"if",
"\"\"",
"in",
"tree",
":",
"l",
".",
"append",
"(",
"[",
"prefix",
",",
"tree",
"[",
"\"\"",
"]",
"]",
")",
"if",
"len",
... | We return all portions of the tree corresponding to the beginning
of `word`. This is used recursively, so we pass the prefix so we
can return meaningful words+translations. | [
"We",
"return",
"all",
"portions",
"of",
"the",
"tree",
"corresponding",
"to",
"the",
"beginning",
"of",
"word",
".",
"This",
"is",
"used",
"recursively",
"so",
"we",
"pass",
"the",
"prefix",
"so",
"we",
"can",
"return",
"meaningful",
"words",
"+",
"transl... | f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd | https://github.com/lxyu/pinyin/blob/f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd/pinyin/cedict.py#L104-L119 | train |
lxyu/pinyin | pinyin/cedict.py | all_phrase_translations | def all_phrase_translations(phrase):
'''
Return the set of translations for all possible words in a full
phrase. Chinese is sometimes ambiguous. We do not attempt to
disambiguate, or handle unknown letters especially well. Full
parsing is left to upstream logic.
'''
if not trees:
ini... | python | def all_phrase_translations(phrase):
'''
Return the set of translations for all possible words in a full
phrase. Chinese is sometimes ambiguous. We do not attempt to
disambiguate, or handle unknown letters especially well. Full
parsing is left to upstream logic.
'''
if not trees:
ini... | [
"def",
"all_phrase_translations",
"(",
"phrase",
")",
":",
"if",
"not",
"trees",
":",
"init",
"(",
")",
"phrase",
"=",
"phrase",
".",
"split",
"(",
"string",
".",
"whitespace",
")",
"for",
"word",
"in",
"phrase",
":",
"for",
"x",
"in",
"range",
"(",
... | Return the set of translations for all possible words in a full
phrase. Chinese is sometimes ambiguous. We do not attempt to
disambiguate, or handle unknown letters especially well. Full
parsing is left to upstream logic. | [
"Return",
"the",
"set",
"of",
"translations",
"for",
"all",
"possible",
"words",
"in",
"a",
"full",
"phrase",
".",
"Chinese",
"is",
"sometimes",
"ambiguous",
".",
"We",
"do",
"not",
"attempt",
"to",
"disambiguate",
"or",
"handle",
"unknown",
"letters",
"espe... | f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd | https://github.com/lxyu/pinyin/blob/f9cac5902b0cfaf91d93af633dfc75a51d2bf0cd/pinyin/cedict.py#L122-L138 | train |
lehins/django-smartfields | smartfields/managers.py | FieldManager.process | def process(self, instance, force=False):
"""Processing is triggered by field's pre_save method. It will be
executed if field's value has been changed (known through descriptor and
stashing logic) or if model instance has never been saved before,
i.e. no pk set, because there is a chance... | python | def process(self, instance, force=False):
"""Processing is triggered by field's pre_save method. It will be
executed if field's value has been changed (known through descriptor and
stashing logic) or if model instance has never been saved before,
i.e. no pk set, because there is a chance... | [
"def",
"process",
"(",
"self",
",",
"instance",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"should_process",
"and",
"(",
"force",
"or",
"self",
".",
"has_stashed_value",
")",
":",
"self",
".",
"set_status",
"(",
"instance",
",",
"{",
"'st... | Processing is triggered by field's pre_save method. It will be
executed if field's value has been changed (known through descriptor and
stashing logic) or if model instance has never been saved before,
i.e. no pk set, because there is a chance that field was initialized
through model's `... | [
"Processing",
"is",
"triggered",
"by",
"field",
"s",
"pre_save",
"method",
".",
"It",
"will",
"be",
"executed",
"if",
"field",
"s",
"value",
"has",
"been",
"changed",
"(",
"known",
"through",
"descriptor",
"and",
"stashing",
"logic",
")",
"or",
"if",
"mode... | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/managers.py#L132-L161 | train |
lehins/django-smartfields | smartfields/managers.py | FieldManager.get_status_key | def get_status_key(self, instance):
"""Generates a key used to set a status on a field"""
key_id = "inst_%s" % id(instance) if instance.pk is None else instance.pk
return "%s.%s-%s-%s" % (instance._meta.app_label,
get_model_name(instance),
... | python | def get_status_key(self, instance):
"""Generates a key used to set a status on a field"""
key_id = "inst_%s" % id(instance) if instance.pk is None else instance.pk
return "%s.%s-%s-%s" % (instance._meta.app_label,
get_model_name(instance),
... | [
"def",
"get_status_key",
"(",
"self",
",",
"instance",
")",
":",
"key_id",
"=",
"\"inst_%s\"",
"%",
"id",
"(",
"instance",
")",
"if",
"instance",
".",
"pk",
"is",
"None",
"else",
"instance",
".",
"pk",
"return",
"\"%s.%s-%s-%s\"",
"%",
"(",
"instance",
"... | Generates a key used to set a status on a field | [
"Generates",
"a",
"key",
"used",
"to",
"set",
"a",
"status",
"on",
"a",
"field"
] | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/managers.py#L171-L177 | train |
lehins/django-smartfields | smartfields/managers.py | FieldManager.get_status | def get_status(self, instance):
"""Retrives a status of a field from cache. Fields in state 'error' and
'complete' will not retain the status after the call.
"""
status_key, status = self._get_status(instance)
if status['state'] in ['complete', 'error']:
cache.delete... | python | def get_status(self, instance):
"""Retrives a status of a field from cache. Fields in state 'error' and
'complete' will not retain the status after the call.
"""
status_key, status = self._get_status(instance)
if status['state'] in ['complete', 'error']:
cache.delete... | [
"def",
"get_status",
"(",
"self",
",",
"instance",
")",
":",
"status_key",
",",
"status",
"=",
"self",
".",
"_get_status",
"(",
"instance",
")",
"if",
"status",
"[",
"'state'",
"]",
"in",
"[",
"'complete'",
",",
"'error'",
"]",
":",
"cache",
".",
"dele... | Retrives a status of a field from cache. Fields in state 'error' and
'complete' will not retain the status after the call. | [
"Retrives",
"a",
"status",
"of",
"a",
"field",
"from",
"cache",
".",
"Fields",
"in",
"state",
"error",
"and",
"complete",
"will",
"not",
"retain",
"the",
"status",
"after",
"the",
"call",
"."
] | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/managers.py#L193-L201 | train |
lehins/django-smartfields | smartfields/managers.py | FieldManager.set_status | def set_status(self, instance, status):
"""Sets the field status for up to 5 minutes."""
status_key = self.get_status_key(instance)
cache.set(status_key, status, timeout=300) | python | def set_status(self, instance, status):
"""Sets the field status for up to 5 minutes."""
status_key = self.get_status_key(instance)
cache.set(status_key, status, timeout=300) | [
"def",
"set_status",
"(",
"self",
",",
"instance",
",",
"status",
")",
":",
"status_key",
"=",
"self",
".",
"get_status_key",
"(",
"instance",
")",
"cache",
".",
"set",
"(",
"status_key",
",",
"status",
",",
"timeout",
"=",
"300",
")"
] | Sets the field status for up to 5 minutes. | [
"Sets",
"the",
"field",
"status",
"for",
"up",
"to",
"5",
"minutes",
"."
] | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/managers.py#L203-L206 | train |
lehins/django-smartfields | smartfields/processors/image.py | ImageFormat.get_mode | def get_mode(self, old_mode=None):
"""Returns output mode. If `mode` not set it will try to guess best
mode, or next best mode comparing to old mode
"""
if self.mode is not None:
return self.mode
assert self.can_write, "This format does not have a supported output mo... | python | def get_mode(self, old_mode=None):
"""Returns output mode. If `mode` not set it will try to guess best
mode, or next best mode comparing to old mode
"""
if self.mode is not None:
return self.mode
assert self.can_write, "This format does not have a supported output mo... | [
"def",
"get_mode",
"(",
"self",
",",
"old_mode",
"=",
"None",
")",
":",
"if",
"self",
".",
"mode",
"is",
"not",
"None",
":",
"return",
"self",
".",
"mode",
"assert",
"self",
".",
"can_write",
",",
"\"This format does not have a supported output mode.\"",
"if",... | Returns output mode. If `mode` not set it will try to guess best
mode, or next best mode comparing to old mode | [
"Returns",
"output",
"mode",
".",
"If",
"mode",
"not",
"set",
"it",
"will",
"try",
"to",
"guess",
"best",
"mode",
"or",
"next",
"best",
"mode",
"comparing",
"to",
"old",
"mode"
] | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/processors/image.py#L118-L144 | train |
paulovn/sparql-kernel | sparqlkernel/kernel.py | token_at_cursor | def token_at_cursor(code, pos=0):
"""
Find the token present at the passed position in the code buffer
:return (tuple): a pair (token, start_position)
"""
l = len(code)
end = start = pos
# Go forwards while we get alphanumeric chars
while end < l and code[end].isalpha():
end += ... | python | def token_at_cursor(code, pos=0):
"""
Find the token present at the passed position in the code buffer
:return (tuple): a pair (token, start_position)
"""
l = len(code)
end = start = pos
# Go forwards while we get alphanumeric chars
while end < l and code[end].isalpha():
end += ... | [
"def",
"token_at_cursor",
"(",
"code",
",",
"pos",
"=",
"0",
")",
":",
"l",
"=",
"len",
"(",
"code",
")",
"end",
"=",
"start",
"=",
"pos",
"# Go forwards while we get alphanumeric chars",
"while",
"end",
"<",
"l",
"and",
"code",
"[",
"end",
"]",
".",
"... | Find the token present at the passed position in the code buffer
:return (tuple): a pair (token, start_position) | [
"Find",
"the",
"token",
"present",
"at",
"the",
"passed",
"position",
"in",
"the",
"code",
"buffer",
":",
"return",
"(",
"tuple",
")",
":",
"a",
"pair",
"(",
"token",
"start_position",
")"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/kernel.py#L33-L49 | train |
paulovn/sparql-kernel | sparqlkernel/kernel.py | SparqlKernel._send | def _send(self, data, msg_type='ok', silent=False):
"""
Send a response to the frontend and return an execute message
@param data: response to send
@param msg_type (str): message type: 'ok', 'raw', 'error', 'multi'
@param silent (bool): suppress output
@return (dict):... | python | def _send(self, data, msg_type='ok', silent=False):
"""
Send a response to the frontend and return an execute message
@param data: response to send
@param msg_type (str): message type: 'ok', 'raw', 'error', 'multi'
@param silent (bool): suppress output
@return (dict):... | [
"def",
"_send",
"(",
"self",
",",
"data",
",",
"msg_type",
"=",
"'ok'",
",",
"silent",
"=",
"False",
")",
":",
"# Data to send back",
"if",
"data",
"is",
"not",
"None",
":",
"# log the message",
"try",
":",
"self",
".",
"_klog",
".",
"debug",
"(",
"u\"... | Send a response to the frontend and return an execute message
@param data: response to send
@param msg_type (str): message type: 'ok', 'raw', 'error', 'multi'
@param silent (bool): suppress output
@return (dict): the return value for the kernel | [
"Send",
"a",
"response",
"to",
"the",
"frontend",
"and",
"return",
"an",
"execute",
"message"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/kernel.py#L106-L133 | train |
paulovn/sparql-kernel | sparqlkernel/kernel.py | SparqlKernel.do_execute | def do_execute(self, code, silent, store_history=True,
user_expressions=None, allow_stdin=False):
"""
Method called to execute a cell
"""
self._klog.info("[%.30s] [%d] [%s]", code, silent, user_expressions)
# Split lines and remove empty lines & comments
... | python | def do_execute(self, code, silent, store_history=True,
user_expressions=None, allow_stdin=False):
"""
Method called to execute a cell
"""
self._klog.info("[%.30s] [%d] [%s]", code, silent, user_expressions)
# Split lines and remove empty lines & comments
... | [
"def",
"do_execute",
"(",
"self",
",",
"code",
",",
"silent",
",",
"store_history",
"=",
"True",
",",
"user_expressions",
"=",
"None",
",",
"allow_stdin",
"=",
"False",
")",
":",
"self",
".",
"_klog",
".",
"info",
"(",
"\"[%.30s] [%d] [%s]\"",
",",
"code",... | Method called to execute a cell | [
"Method",
"called",
"to",
"execute",
"a",
"cell"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/kernel.py#L137-L172 | train |
paulovn/sparql-kernel | sparqlkernel/kernel.py | SparqlKernel.do_inspect | def do_inspect(self, code, cursor_pos, detail_level=0):
"""
Method called on help requests
"""
self._klog.info("{%s}", code[cursor_pos:cursor_pos+10])
# Find the token for which help is requested
token, start = token_at_cursor(code, cursor_pos)
self._klog.debug("... | python | def do_inspect(self, code, cursor_pos, detail_level=0):
"""
Method called on help requests
"""
self._klog.info("{%s}", code[cursor_pos:cursor_pos+10])
# Find the token for which help is requested
token, start = token_at_cursor(code, cursor_pos)
self._klog.debug("... | [
"def",
"do_inspect",
"(",
"self",
",",
"code",
",",
"cursor_pos",
",",
"detail_level",
"=",
"0",
")",
":",
"self",
".",
"_klog",
".",
"info",
"(",
"\"{%s}\"",
",",
"code",
"[",
"cursor_pos",
":",
"cursor_pos",
"+",
"10",
"]",
")",
"# Find the token for w... | Method called on help requests | [
"Method",
"called",
"on",
"help",
"requests"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/kernel.py#L177-L201 | train |
paulovn/sparql-kernel | sparqlkernel/kernel.py | SparqlKernel.do_complete | def do_complete(self, code, cursor_pos):
"""
Method called on autocompletion requests
"""
self._klog.info("{%s}", code[cursor_pos:cursor_pos+10])
token, start = token_at_cursor(code, cursor_pos)
tkn_low = token.lower()
if is_magic(token, start, code):
... | python | def do_complete(self, code, cursor_pos):
"""
Method called on autocompletion requests
"""
self._klog.info("{%s}", code[cursor_pos:cursor_pos+10])
token, start = token_at_cursor(code, cursor_pos)
tkn_low = token.lower()
if is_magic(token, start, code):
... | [
"def",
"do_complete",
"(",
"self",
",",
"code",
",",
"cursor_pos",
")",
":",
"self",
".",
"_klog",
".",
"info",
"(",
"\"{%s}\"",
",",
"code",
"[",
"cursor_pos",
":",
"cursor_pos",
"+",
"10",
"]",
")",
"token",
",",
"start",
"=",
"token_at_cursor",
"(",... | Method called on autocompletion requests | [
"Method",
"called",
"on",
"autocompletion",
"requests"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/kernel.py#L205-L224 | train |
lehins/django-smartfields | smartfields/utils.py | AsynchronousFileReader.run | def run(self):
'''The body of the tread: read lines and put them on the queue.'''
for line in iter(self._fd.readline, ''):
self._queue.put(line) | python | def run(self):
'''The body of the tread: read lines and put them on the queue.'''
for line in iter(self._fd.readline, ''):
self._queue.put(line) | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"line",
"in",
"iter",
"(",
"self",
".",
"_fd",
".",
"readline",
",",
"''",
")",
":",
"self",
".",
"_queue",
".",
"put",
"(",
"line",
")"
] | The body of the tread: read lines and put them on the queue. | [
"The",
"body",
"of",
"the",
"tread",
":",
"read",
"lines",
"and",
"put",
"them",
"on",
"the",
"queue",
"."
] | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/utils.py#L224-L227 | train |
paulovn/sparql-kernel | sparqlkernel/utils.py | escape | def escape( x, lb=False ):
"""
Ensure a string does not contain HTML-reserved characters (including
double quotes)
Optionally also insert a linebreak if the string is too long
"""
# Insert a linebreak? Roughly around the middle of the string,
if lb:
l = len(x)
if l >= 10:
... | python | def escape( x, lb=False ):
"""
Ensure a string does not contain HTML-reserved characters (including
double quotes)
Optionally also insert a linebreak if the string is too long
"""
# Insert a linebreak? Roughly around the middle of the string,
if lb:
l = len(x)
if l >= 10:
... | [
"def",
"escape",
"(",
"x",
",",
"lb",
"=",
"False",
")",
":",
"# Insert a linebreak? Roughly around the middle of the string,",
"if",
"lb",
":",
"l",
"=",
"len",
"(",
"x",
")",
"if",
"l",
">=",
"10",
":",
"l",
">>=",
"1",
"# middle of the string",
"s1",
"=... | Ensure a string does not contain HTML-reserved characters (including
double quotes)
Optionally also insert a linebreak if the string is too long | [
"Ensure",
"a",
"string",
"does",
"not",
"contain",
"HTML",
"-",
"reserved",
"characters",
"(",
"including",
"double",
"quotes",
")",
"Optionally",
"also",
"insert",
"a",
"linebreak",
"if",
"the",
"string",
"is",
"too",
"long"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/utils.py#L28-L47 | train |
paulovn/sparql-kernel | sparqlkernel/utils.py | div | def div( txt, *args, **kwargs ):
"""
Create & return an HTML <div> element by wrapping the passed text buffer.
@param txt (basestring): the text buffer to use
@param *args (list): if present, \c txt is considered a Python format
string, and the arguments are formatted into it
@param kw... | python | def div( txt, *args, **kwargs ):
"""
Create & return an HTML <div> element by wrapping the passed text buffer.
@param txt (basestring): the text buffer to use
@param *args (list): if present, \c txt is considered a Python format
string, and the arguments are formatted into it
@param kw... | [
"def",
"div",
"(",
"txt",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"txt",
"=",
"txt",
".",
"format",
"(",
"*",
"args",
")",
"css",
"=",
"kwargs",
".",
"get",
"(",
"'css'",
",",
"HTML_DIV_CLASS",
")",
"return",
"u'... | Create & return an HTML <div> element by wrapping the passed text buffer.
@param txt (basestring): the text buffer to use
@param *args (list): if present, \c txt is considered a Python format
string, and the arguments are formatted into it
@param kwargs (dict): the \c css field can contain the... | [
"Create",
"&",
"return",
"an",
"HTML",
"<div",
">",
"element",
"by",
"wrapping",
"the",
"passed",
"text",
"buffer",
"."
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/utils.py#L52-L64 | train |
paulovn/sparql-kernel | sparqlkernel/utils.py | data_msglist | def data_msglist( msglist ):
"""
Return a Jupyter display_data message, in both HTML & text formats, by
joining together all passed messages.
@param msglist (iterable): an iterable containing a list of tuples
(message, css_style)
Each message is either a text string, or a list. In... | python | def data_msglist( msglist ):
"""
Return a Jupyter display_data message, in both HTML & text formats, by
joining together all passed messages.
@param msglist (iterable): an iterable containing a list of tuples
(message, css_style)
Each message is either a text string, or a list. In... | [
"def",
"data_msglist",
"(",
"msglist",
")",
":",
"txt",
"=",
"html",
"=",
"u''",
"for",
"msg",
",",
"css",
"in",
"msglist",
":",
"if",
"is_collection",
"(",
"msg",
")",
":",
"msg",
"=",
"msg",
"[",
"0",
"]",
".",
"format",
"(",
"*",
"msg",
"[",
... | Return a Jupyter display_data message, in both HTML & text formats, by
joining together all passed messages.
@param msglist (iterable): an iterable containing a list of tuples
(message, css_style)
Each message is either a text string, or a list. In the latter case it is
assumed to be ... | [
"Return",
"a",
"Jupyter",
"display_data",
"message",
"in",
"both",
"HTML",
"&",
"text",
"formats",
"by",
"joining",
"together",
"all",
"passed",
"messages",
"."
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/utils.py#L67-L86 | train |
paulovn/sparql-kernel | sparqlkernel/utils.py | data_msg | def data_msg( msg, mtype=None ):
"""
Return a Jupyter display_data message, in both HTML & text formats, by
formatting a given single message. The passed message may be:
* An exception (including a KrnlException): will generate an error message
* A list of messages (with \c mtype equal to \c mu... | python | def data_msg( msg, mtype=None ):
"""
Return a Jupyter display_data message, in both HTML & text formats, by
formatting a given single message. The passed message may be:
* An exception (including a KrnlException): will generate an error message
* A list of messages (with \c mtype equal to \c mu... | [
"def",
"data_msg",
"(",
"msg",
",",
"mtype",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"KrnlException",
")",
":",
"return",
"msg",
"(",
")",
"# a KrnlException knows how to format itself",
"elif",
"isinstance",
"(",
"msg",
",",
"Exception",
... | Return a Jupyter display_data message, in both HTML & text formats, by
formatting a given single message. The passed message may be:
* An exception (including a KrnlException): will generate an error message
* A list of messages (with \c mtype equal to \c multi)
* A single message
@param m... | [
"Return",
"a",
"Jupyter",
"display_data",
"message",
"in",
"both",
"HTML",
"&",
"text",
"formats",
"by",
"formatting",
"a",
"given",
"single",
"message",
".",
"The",
"passed",
"message",
"may",
"be",
":",
"*",
"An",
"exception",
"(",
"including",
"a",
"Krn... | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/utils.py#L89-L111 | train |
paulovn/sparql-kernel | sparqlkernel/install.py | copyresource | def copyresource( resource, filename, destdir ):
"""
Copy a resource file to a destination
"""
data = pkgutil.get_data(resource, os.path.join('resources',filename) )
#log.info( "Installing %s", os.path.join(destdir,filename) )
with open( os.path.join(destdir,filename), 'wb' ) as fp:
fp.w... | python | def copyresource( resource, filename, destdir ):
"""
Copy a resource file to a destination
"""
data = pkgutil.get_data(resource, os.path.join('resources',filename) )
#log.info( "Installing %s", os.path.join(destdir,filename) )
with open( os.path.join(destdir,filename), 'wb' ) as fp:
fp.w... | [
"def",
"copyresource",
"(",
"resource",
",",
"filename",
",",
"destdir",
")",
":",
"data",
"=",
"pkgutil",
".",
"get_data",
"(",
"resource",
",",
"os",
".",
"path",
".",
"join",
"(",
"'resources'",
",",
"filename",
")",
")",
"#log.info( \"Installing %s\", os... | Copy a resource file to a destination | [
"Copy",
"a",
"resource",
"file",
"to",
"a",
"destination"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/install.py#L50-L57 | train |
paulovn/sparql-kernel | sparqlkernel/install.py | install_kernel_resources | def install_kernel_resources( destdir, resource=PKGNAME, files=None ):
"""
Copy the resource files to the kernelspec folder.
"""
if files is None:
files = ['logo-64x64.png', 'logo-32x32.png']
for filename in files:
try:
copyresource( resource, filename, destdir )
... | python | def install_kernel_resources( destdir, resource=PKGNAME, files=None ):
"""
Copy the resource files to the kernelspec folder.
"""
if files is None:
files = ['logo-64x64.png', 'logo-32x32.png']
for filename in files:
try:
copyresource( resource, filename, destdir )
... | [
"def",
"install_kernel_resources",
"(",
"destdir",
",",
"resource",
"=",
"PKGNAME",
",",
"files",
"=",
"None",
")",
":",
"if",
"files",
"is",
"None",
":",
"files",
"=",
"[",
"'logo-64x64.png'",
",",
"'logo-32x32.png'",
"]",
"for",
"filename",
"in",
"files",
... | Copy the resource files to the kernelspec folder. | [
"Copy",
"the",
"resource",
"files",
"to",
"the",
"kernelspec",
"folder",
"."
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/install.py#L60-L70 | train |
paulovn/sparql-kernel | sparqlkernel/install.py | install_custom_css | def install_custom_css( destdir, cssfile, resource=PKGNAME ):
"""
Add the kernel CSS to custom.css
"""
ensure_dir_exists( destdir )
custom = os.path.join( destdir, 'custom.css' )
prefix = css_frame_prefix(resource)
# Check if custom.css already includes it. If so, let's remove it first
... | python | def install_custom_css( destdir, cssfile, resource=PKGNAME ):
"""
Add the kernel CSS to custom.css
"""
ensure_dir_exists( destdir )
custom = os.path.join( destdir, 'custom.css' )
prefix = css_frame_prefix(resource)
# Check if custom.css already includes it. If so, let's remove it first
... | [
"def",
"install_custom_css",
"(",
"destdir",
",",
"cssfile",
",",
"resource",
"=",
"PKGNAME",
")",
":",
"ensure_dir_exists",
"(",
"destdir",
")",
"custom",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destdir",
",",
"'custom.css'",
")",
"prefix",
"=",
"css_f... | Add the kernel CSS to custom.css | [
"Add",
"the",
"kernel",
"CSS",
"to",
"custom",
".",
"css"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/install.py#L73-L107 | train |
paulovn/sparql-kernel | sparqlkernel/install.py | remove_custom_css | def remove_custom_css(destdir, resource=PKGNAME ):
"""
Remove the kernel CSS from custom.css
"""
# Remove the inclusion in the main CSS
if not os.path.isdir( destdir ):
return False
custom = os.path.join( destdir, 'custom.css' )
copy = True
found = False
prefix = css_frame_p... | python | def remove_custom_css(destdir, resource=PKGNAME ):
"""
Remove the kernel CSS from custom.css
"""
# Remove the inclusion in the main CSS
if not os.path.isdir( destdir ):
return False
custom = os.path.join( destdir, 'custom.css' )
copy = True
found = False
prefix = css_frame_p... | [
"def",
"remove_custom_css",
"(",
"destdir",
",",
"resource",
"=",
"PKGNAME",
")",
":",
"# Remove the inclusion in the main CSS",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"destdir",
")",
":",
"return",
"False",
"custom",
"=",
"os",
".",
"path",
".",... | Remove the kernel CSS from custom.css | [
"Remove",
"the",
"kernel",
"CSS",
"from",
"custom",
".",
"css"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/install.py#L110-L138 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | html_elem | def html_elem(e, ct, withtype=False):
"""
Format a result element as an HTML table cell.
@param e (list): a pair \c (value,type)
@param ct (str): cell type (th or td)
@param withtype (bool): add an additional cell with the element type
"""
# Header cell
if ct == 'th':
retur... | python | def html_elem(e, ct, withtype=False):
"""
Format a result element as an HTML table cell.
@param e (list): a pair \c (value,type)
@param ct (str): cell type (th or td)
@param withtype (bool): add an additional cell with the element type
"""
# Header cell
if ct == 'th':
retur... | [
"def",
"html_elem",
"(",
"e",
",",
"ct",
",",
"withtype",
"=",
"False",
")",
":",
"# Header cell",
"if",
"ct",
"==",
"'th'",
":",
"return",
"'<th>{0}</th><th>{1}</th>'",
".",
"format",
"(",
"*",
"e",
")",
"if",
"withtype",
"else",
"'<th>{}</th>'",
".",
"... | Format a result element as an HTML table cell.
@param e (list): a pair \c (value,type)
@param ct (str): cell type (th or td)
@param withtype (bool): add an additional cell with the element type | [
"Format",
"a",
"result",
"element",
"as",
"an",
"HTML",
"table",
"cell",
"."
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L84-L102 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | html_table | def html_table(data, header=True, limit=None, withtype=False):
"""
Return a double iterable as an HTML table
@param data (iterable): the data to format
@param header (bool): if the first row is a header row
@param limit (int): maximum number of rows to render (excluding header)
@param wi... | python | def html_table(data, header=True, limit=None, withtype=False):
"""
Return a double iterable as an HTML table
@param data (iterable): the data to format
@param header (bool): if the first row is a header row
@param limit (int): maximum number of rows to render (excluding header)
@param wi... | [
"def",
"html_table",
"(",
"data",
",",
"header",
"=",
"True",
",",
"limit",
"=",
"None",
",",
"withtype",
"=",
"False",
")",
":",
"if",
"header",
"and",
"limit",
":",
"limit",
"+=",
"1",
"ct",
"=",
"'th'",
"if",
"header",
"else",
"'td'",
"rc",
"=",... | Return a double iterable as an HTML table
@param data (iterable): the data to format
@param header (bool): if the first row is a header row
@param limit (int): maximum number of rows to render (excluding header)
@param withtype (bool): if columns are to have an alternating CSS class
(eve... | [
"Return",
"a",
"double",
"iterable",
"as",
"an",
"HTML",
"table"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L105-L141 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | jtype | def jtype(c):
"""
Return the a string with the data type of a value, for JSON data
"""
ct = c['type']
return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang')) | python | def jtype(c):
"""
Return the a string with the data type of a value, for JSON data
"""
ct = c['type']
return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang')) | [
"def",
"jtype",
"(",
"c",
")",
":",
"ct",
"=",
"c",
"[",
"'type'",
"]",
"return",
"ct",
"if",
"ct",
"!=",
"'literal'",
"else",
"'{}, {}'",
".",
"format",
"(",
"ct",
",",
"c",
".",
"get",
"(",
"'xml:lang'",
")",
")"
] | Return the a string with the data type of a value, for JSON data | [
"Return",
"the",
"a",
"string",
"with",
"the",
"data",
"type",
"of",
"a",
"value",
"for",
"JSON",
"data"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L146-L151 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | gtype | def gtype(n):
"""
Return the a string with the data type of a value, for Graph data
"""
t = type(n).__name__
return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language) | python | def gtype(n):
"""
Return the a string with the data type of a value, for Graph data
"""
t = type(n).__name__
return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language) | [
"def",
"gtype",
"(",
"n",
")",
":",
"t",
"=",
"type",
"(",
"n",
")",
".",
"__name__",
"return",
"str",
"(",
"t",
")",
"if",
"t",
"!=",
"'Literal'",
"else",
"'Literal, {}'",
".",
"format",
"(",
"n",
".",
"language",
")"
] | Return the a string with the data type of a value, for Graph data | [
"Return",
"the",
"a",
"string",
"with",
"the",
"data",
"type",
"of",
"a",
"value",
"for",
"Graph",
"data"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L154-L159 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | lang_match_json | def lang_match_json(row, hdr, accepted_languages):
'''Find if the JSON row contains acceptable language data'''
if not accepted_languages:
return True
languages = set([row[c].get('xml:lang') for c in hdr
if c in row and row[c]['type'] == 'literal'])
return (not languages) or... | python | def lang_match_json(row, hdr, accepted_languages):
'''Find if the JSON row contains acceptable language data'''
if not accepted_languages:
return True
languages = set([row[c].get('xml:lang') for c in hdr
if c in row and row[c]['type'] == 'literal'])
return (not languages) or... | [
"def",
"lang_match_json",
"(",
"row",
",",
"hdr",
",",
"accepted_languages",
")",
":",
"if",
"not",
"accepted_languages",
":",
"return",
"True",
"languages",
"=",
"set",
"(",
"[",
"row",
"[",
"c",
"]",
".",
"get",
"(",
"'xml:lang'",
")",
"for",
"c",
"i... | Find if the JSON row contains acceptable language data | [
"Find",
"if",
"the",
"JSON",
"row",
"contains",
"acceptable",
"language",
"data"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L162-L168 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | lang_match_rdf | def lang_match_rdf(triple, accepted_languages):
'''Find if the RDF triple contains acceptable language data'''
if not accepted_languages:
return True
languages = set([n.language for n in triple if isinstance(n, Literal)])
return (not languages) or (languages & accepted_languages) | python | def lang_match_rdf(triple, accepted_languages):
'''Find if the RDF triple contains acceptable language data'''
if not accepted_languages:
return True
languages = set([n.language for n in triple if isinstance(n, Literal)])
return (not languages) or (languages & accepted_languages) | [
"def",
"lang_match_rdf",
"(",
"triple",
",",
"accepted_languages",
")",
":",
"if",
"not",
"accepted_languages",
":",
"return",
"True",
"languages",
"=",
"set",
"(",
"[",
"n",
".",
"language",
"for",
"n",
"in",
"triple",
"if",
"isinstance",
"(",
"n",
",",
... | Find if the RDF triple contains acceptable language data | [
"Find",
"if",
"the",
"RDF",
"triple",
"contains",
"acceptable",
"language",
"data"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L171-L176 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | lang_match_xml | def lang_match_xml(row, accepted_languages):
'''Find if the XML row contains acceptable language data'''
if not accepted_languages:
return True
column_languages = set()
for elem in row:
lang = elem[0].attrib.get(XML_LANG, None)
if lang:
column_languages.add(lang)
... | python | def lang_match_xml(row, accepted_languages):
'''Find if the XML row contains acceptable language data'''
if not accepted_languages:
return True
column_languages = set()
for elem in row:
lang = elem[0].attrib.get(XML_LANG, None)
if lang:
column_languages.add(lang)
... | [
"def",
"lang_match_xml",
"(",
"row",
",",
"accepted_languages",
")",
":",
"if",
"not",
"accepted_languages",
":",
"return",
"True",
"column_languages",
"=",
"set",
"(",
")",
"for",
"elem",
"in",
"row",
":",
"lang",
"=",
"elem",
"[",
"0",
"]",
".",
"attri... | Find if the XML row contains acceptable language data | [
"Find",
"if",
"the",
"XML",
"row",
"contains",
"acceptable",
"language",
"data"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L181-L190 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | json_iterator | def json_iterator(hdr, rowlist, lang, add_vtype=False):
"""
Convert a JSON response into a double iterable, by rows and columns
Optionally add element type, and filter triples by language (on literals)
"""
# Return the header row
yield hdr if not add_vtype else ((h, 'type') for h in hdr)
# N... | python | def json_iterator(hdr, rowlist, lang, add_vtype=False):
"""
Convert a JSON response into a double iterable, by rows and columns
Optionally add element type, and filter triples by language (on literals)
"""
# Return the header row
yield hdr if not add_vtype else ((h, 'type') for h in hdr)
# N... | [
"def",
"json_iterator",
"(",
"hdr",
",",
"rowlist",
",",
"lang",
",",
"add_vtype",
"=",
"False",
")",
":",
"# Return the header row",
"yield",
"hdr",
"if",
"not",
"add_vtype",
"else",
"(",
"(",
"h",
",",
"'type'",
")",
"for",
"h",
"in",
"hdr",
")",
"# ... | Convert a JSON response into a double iterable, by rows and columns
Optionally add element type, and filter triples by language (on literals) | [
"Convert",
"a",
"JSON",
"response",
"into",
"a",
"double",
"iterable",
"by",
"rows",
"and",
"columns",
"Optionally",
"add",
"element",
"type",
"and",
"filter",
"triples",
"by",
"language",
"(",
"on",
"literals",
")"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L193-L205 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | rdf_iterator | def rdf_iterator(graph, lang, add_vtype=False):
"""
Convert a Graph response into a double iterable, by triples and elements.
Optionally add element type, and filter triples by language (on literals)
"""
# Return the header row
hdr = ('subject', 'predicate', 'object')
yield hdr if not add_vt... | python | def rdf_iterator(graph, lang, add_vtype=False):
"""
Convert a Graph response into a double iterable, by triples and elements.
Optionally add element type, and filter triples by language (on literals)
"""
# Return the header row
hdr = ('subject', 'predicate', 'object')
yield hdr if not add_vt... | [
"def",
"rdf_iterator",
"(",
"graph",
",",
"lang",
",",
"add_vtype",
"=",
"False",
")",
":",
"# Return the header row",
"hdr",
"=",
"(",
"'subject'",
",",
"'predicate'",
",",
"'object'",
")",
"yield",
"hdr",
"if",
"not",
"add_vtype",
"else",
"(",
"(",
"h",
... | Convert a Graph response into a double iterable, by triples and elements.
Optionally add element type, and filter triples by language (on literals) | [
"Convert",
"a",
"Graph",
"response",
"into",
"a",
"double",
"iterable",
"by",
"triples",
"and",
"elements",
".",
"Optionally",
"add",
"element",
"type",
"and",
"filter",
"triples",
"by",
"language",
"(",
"on",
"literals",
")"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L208-L220 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | render_json | def render_json(result, cfg, **kwargs):
"""
Render to output a result in JSON format
"""
result = json.loads(result.decode('utf-8'))
head = result['head']
if 'results' not in result:
if 'boolean' in result:
r = u'Result: {}'.format(result['boolean'])
else:
... | python | def render_json(result, cfg, **kwargs):
"""
Render to output a result in JSON format
"""
result = json.loads(result.decode('utf-8'))
head = result['head']
if 'results' not in result:
if 'boolean' in result:
r = u'Result: {}'.format(result['boolean'])
else:
... | [
"def",
"render_json",
"(",
"result",
",",
"cfg",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"json",
".",
"loads",
"(",
"result",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"head",
"=",
"result",
"[",
"'head'",
"]",
"if",
"'results'",
"not",
"i... | Render to output a result in JSON format | [
"Render",
"to",
"output",
"a",
"result",
"in",
"JSON",
"format"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L223-L251 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | xml_row | def xml_row(row, lang):
'''
Generator for an XML row
'''
for elem in row:
name = elem.get('name')
child = elem[0]
ftype = re.sub(r'\{[^}]+\}', '', child.tag)
if ftype == 'literal':
ftype = '{}, {}'.format(ftype, child.attrib.get(XML_LANG, 'none'))
yiel... | python | def xml_row(row, lang):
'''
Generator for an XML row
'''
for elem in row:
name = elem.get('name')
child = elem[0]
ftype = re.sub(r'\{[^}]+\}', '', child.tag)
if ftype == 'literal':
ftype = '{}, {}'.format(ftype, child.attrib.get(XML_LANG, 'none'))
yiel... | [
"def",
"xml_row",
"(",
"row",
",",
"lang",
")",
":",
"for",
"elem",
"in",
"row",
":",
"name",
"=",
"elem",
".",
"get",
"(",
"'name'",
")",
"child",
"=",
"elem",
"[",
"0",
"]",
"ftype",
"=",
"re",
".",
"sub",
"(",
"r'\\{[^}]+\\}'",
",",
"''",
",... | Generator for an XML row | [
"Generator",
"for",
"an",
"XML",
"row"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L254-L264 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | xml_iterator | def xml_iterator(columns, rowlist, lang, add_vtype=False):
"""
Convert an XML response into a double iterable, by rows and columns
Options are: filter triples by language (on literals), add element type
"""
# Return the header row
yield columns if not add_vtype else ((h, 'type') for h in columns... | python | def xml_iterator(columns, rowlist, lang, add_vtype=False):
"""
Convert an XML response into a double iterable, by rows and columns
Options are: filter triples by language (on literals), add element type
"""
# Return the header row
yield columns if not add_vtype else ((h, 'type') for h in columns... | [
"def",
"xml_iterator",
"(",
"columns",
",",
"rowlist",
",",
"lang",
",",
"add_vtype",
"=",
"False",
")",
":",
"# Return the header row",
"yield",
"columns",
"if",
"not",
"add_vtype",
"else",
"(",
"(",
"h",
",",
"'type'",
")",
"for",
"h",
"in",
"columns",
... | Convert an XML response into a double iterable, by rows and columns
Options are: filter triples by language (on literals), add element type | [
"Convert",
"an",
"XML",
"response",
"into",
"a",
"double",
"iterable",
"by",
"rows",
"and",
"columns",
"Options",
"are",
":",
"filter",
"triples",
"by",
"language",
"(",
"on",
"literals",
")",
"add",
"element",
"type"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L267-L279 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | render_xml | def render_xml(result, cfg, **kwargs):
"""
Render to output a result in XML format
"""
# Raw mode
if cfg.dis == 'raw':
return {'data': {'text/plain': result.decode('utf-8')},
'metadata': {}}
# Table
try:
import xml.etree.cElementTree as ET
except ImportErr... | python | def render_xml(result, cfg, **kwargs):
"""
Render to output a result in XML format
"""
# Raw mode
if cfg.dis == 'raw':
return {'data': {'text/plain': result.decode('utf-8')},
'metadata': {}}
# Table
try:
import xml.etree.cElementTree as ET
except ImportErr... | [
"def",
"render_xml",
"(",
"result",
",",
"cfg",
",",
"*",
"*",
"kwargs",
")",
":",
"# Raw mode",
"if",
"cfg",
".",
"dis",
"==",
"'raw'",
":",
"return",
"{",
"'data'",
":",
"{",
"'text/plain'",
":",
"result",
".",
"decode",
"(",
"'utf-8'",
")",
"}",
... | Render to output a result in XML format | [
"Render",
"to",
"output",
"a",
"result",
"in",
"XML",
"format"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L282-L307 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | render_graph | def render_graph(result, cfg, **kwargs):
"""
Render to output a result that can be parsed as an RDF graph
"""
# Mapping from MIME types to formats accepted by RDFlib
rdflib_formats = {'text/rdf+n3': 'n3',
'text/turtle': 'turtle',
'application/x-turtle': 't... | python | def render_graph(result, cfg, **kwargs):
"""
Render to output a result that can be parsed as an RDF graph
"""
# Mapping from MIME types to formats accepted by RDFlib
rdflib_formats = {'text/rdf+n3': 'n3',
'text/turtle': 'turtle',
'application/x-turtle': 't... | [
"def",
"render_graph",
"(",
"result",
",",
"cfg",
",",
"*",
"*",
"kwargs",
")",
":",
"# Mapping from MIME types to formats accepted by RDFlib",
"rdflib_formats",
"=",
"{",
"'text/rdf+n3'",
":",
"'n3'",
",",
"'text/turtle'",
":",
"'turtle'",
",",
"'application/x-turtle... | Render to output a result that can be parsed as an RDF graph | [
"Render",
"to",
"output",
"a",
"result",
"that",
"can",
"be",
"parsed",
"as",
"an",
"RDF",
"graph"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L310-L355 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | SparqlConnection.magic | def magic(self, line):
"""
Read and process magics
@param line (str): the full line containing a magic
@return (list): a tuple (output-message,css-class), where
the output message can be a single string or a list (containing
a Python format string and its argu... | python | def magic(self, line):
"""
Read and process magics
@param line (str): the full line containing a magic
@return (list): a tuple (output-message,css-class), where
the output message can be a single string or a list (containing
a Python format string and its argu... | [
"def",
"magic",
"(",
"self",
",",
"line",
")",
":",
"# The %lsmagic has no parameters",
"if",
"line",
".",
"startswith",
"(",
"'%lsmagic'",
")",
":",
"return",
"magic_help",
",",
"'magic-help'",
"# Split line into command & parameters",
"try",
":",
"cmd",
",",
"pa... | Read and process magics
@param line (str): the full line containing a magic
@return (list): a tuple (output-message,css-class), where
the output message can be a single string or a list (containing
a Python format string and its arguments) | [
"Read",
"and",
"process",
"magics"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L383-L539 | train |
paulovn/sparql-kernel | sparqlkernel/connection.py | SparqlConnection.query | def query(self, query, num=0, silent=False):
"""
Launch an SPARQL query, process & convert results and return them
"""
if self.srv is None:
raise KrnlException('no endpoint defined')
# Add to the query all predefined SPARQL prefixes
if self.cfg.pfx:
... | python | def query(self, query, num=0, silent=False):
"""
Launch an SPARQL query, process & convert results and return them
"""
if self.srv is None:
raise KrnlException('no endpoint defined')
# Add to the query all predefined SPARQL prefixes
if self.cfg.pfx:
... | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"num",
"=",
"0",
",",
"silent",
"=",
"False",
")",
":",
"if",
"self",
".",
"srv",
"is",
"None",
":",
"raise",
"KrnlException",
"(",
"'no endpoint defined'",
")",
"# Add to the query all predefined SPARQL prefixes... | Launch an SPARQL query, process & convert results and return them | [
"Launch",
"an",
"SPARQL",
"query",
"process",
"&",
"convert",
"results",
"and",
"return",
"them"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L542-L651 | train |
paulovn/sparql-kernel | sparqlkernel/setlogging.py | set_logging | def set_logging( logfilename=None, level=None ):
"""
Set a logging configuration, with a rolling file appender.
If passed a filename, use it as the logfile, else use a default name.
The default logfile is \c sparqlkernel.log, placed in the directory given
by (in that order) the \c LOGDIR environmen... | python | def set_logging( logfilename=None, level=None ):
"""
Set a logging configuration, with a rolling file appender.
If passed a filename, use it as the logfile, else use a default name.
The default logfile is \c sparqlkernel.log, placed in the directory given
by (in that order) the \c LOGDIR environmen... | [
"def",
"set_logging",
"(",
"logfilename",
"=",
"None",
",",
"level",
"=",
"None",
")",
":",
"if",
"logfilename",
"is",
"None",
":",
"# Find the logging diectory",
"logdir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'LOGDIR'",
")",
"if",
"logdir",
"is",
... | Set a logging configuration, with a rolling file appender.
If passed a filename, use it as the logfile, else use a default name.
The default logfile is \c sparqlkernel.log, placed in the directory given
by (in that order) the \c LOGDIR environment variable, the logdir
specified upon kernel installation... | [
"Set",
"a",
"logging",
"configuration",
"with",
"a",
"rolling",
"file",
"appender",
".",
"If",
"passed",
"a",
"filename",
"use",
"it",
"as",
"the",
"logfile",
"else",
"use",
"a",
"default",
"name",
"."
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/setlogging.py#L50-L72 | train |
lehins/django-smartfields | smartfields/models.py | SmartfieldsModelMixin.smartfields_get_field_status | def smartfields_get_field_status(self, field_name):
"""A way to find out a status of a filed."""
manager = self._smartfields_managers.get(field_name, None)
if manager is not None:
return manager.get_status(self)
return {'state': 'ready'} | python | def smartfields_get_field_status(self, field_name):
"""A way to find out a status of a filed."""
manager = self._smartfields_managers.get(field_name, None)
if manager is not None:
return manager.get_status(self)
return {'state': 'ready'} | [
"def",
"smartfields_get_field_status",
"(",
"self",
",",
"field_name",
")",
":",
"manager",
"=",
"self",
".",
"_smartfields_managers",
".",
"get",
"(",
"field_name",
",",
"None",
")",
"if",
"manager",
"is",
"not",
"None",
":",
"return",
"manager",
".",
"get_... | A way to find out a status of a filed. | [
"A",
"way",
"to",
"find",
"out",
"a",
"status",
"of",
"a",
"filed",
"."
] | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/models.py#L56-L61 | train |
lehins/django-smartfields | smartfields/processors/base.py | BaseFileProcessor.get_ext | def get_ext(self, format=None, **kwargs):
"""Returns new file extension based on a processor's `format` parameter.
Overwrite if different extension should be set ex: `'.txt'` or `None` if this
processor does not change file's extension.
"""
try:
format = format or se... | python | def get_ext(self, format=None, **kwargs):
"""Returns new file extension based on a processor's `format` parameter.
Overwrite if different extension should be set ex: `'.txt'` or `None` if this
processor does not change file's extension.
"""
try:
format = format or se... | [
"def",
"get_ext",
"(",
"self",
",",
"format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"format",
"=",
"format",
"or",
"self",
".",
"default_params",
"[",
"'format'",
"]",
"return",
"\".%s\"",
"%",
"format",
".",
"lower",
"(",
")",
... | Returns new file extension based on a processor's `format` parameter.
Overwrite if different extension should be set ex: `'.txt'` or `None` if this
processor does not change file's extension. | [
"Returns",
"new",
"file",
"extension",
"based",
"on",
"a",
"processor",
"s",
"format",
"parameter",
".",
"Overwrite",
"if",
"different",
"extension",
"should",
"be",
"set",
"ex",
":",
".",
"txt",
"or",
"None",
"if",
"this",
"processor",
"does",
"not",
"cha... | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/processors/base.py#L49-L57 | train |
lehins/django-smartfields | smartfields/processors/base.py | ExternalFileProcessor.get_output_file | def get_output_file(self, in_file, instance, field, **kwargs):
"""Creates a temporary file. With regular `FileSystemStorage` it does not
need to be deleted, instaed file is safely moved over. With other cloud
based storage it is a good idea to set `delete=True`."""
return NamedTemporary... | python | def get_output_file(self, in_file, instance, field, **kwargs):
"""Creates a temporary file. With regular `FileSystemStorage` it does not
need to be deleted, instaed file is safely moved over. With other cloud
based storage it is a good idea to set `delete=True`."""
return NamedTemporary... | [
"def",
"get_output_file",
"(",
"self",
",",
"in_file",
",",
"instance",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'rb'",
",",
"suffix",
"=",
"'_%s_%s%s'",
"%",
"(",
"get_model_name",
"(",
"instance"... | Creates a temporary file. With regular `FileSystemStorage` it does not
need to be deleted, instaed file is safely moved over. With other cloud
based storage it is a good idea to set `delete=True`. | [
"Creates",
"a",
"temporary",
"file",
".",
"With",
"regular",
"FileSystemStorage",
"it",
"does",
"not",
"need",
"to",
"be",
"deleted",
"instaed",
"file",
"is",
"safely",
"moved",
"over",
".",
"With",
"other",
"cloud",
"based",
"storage",
"it",
"is",
"a",
"g... | 23d4b0b18352f4f40ce8c429735e673ba5191502 | https://github.com/lehins/django-smartfields/blob/23d4b0b18352f4f40ce8c429735e673ba5191502/smartfields/processors/base.py#L96-L101 | train |
paulovn/sparql-kernel | sparqlkernel/drawgraph.py | label | def label(x, gr, preferred_languages=None):
"""
@param x : graph entity
@param gr (Graph): RDF graph
@param preferred_languages (iterable)
Return the best available label in the graph for the passed entity.
If a set of preferred languages is given, try them in order. If none is
found,... | python | def label(x, gr, preferred_languages=None):
"""
@param x : graph entity
@param gr (Graph): RDF graph
@param preferred_languages (iterable)
Return the best available label in the graph for the passed entity.
If a set of preferred languages is given, try them in order. If none is
found,... | [
"def",
"label",
"(",
"x",
",",
"gr",
",",
"preferred_languages",
"=",
"None",
")",
":",
"# Find all labels & their language",
"labels",
"=",
"{",
"l",
".",
"language",
":",
"l",
"for",
"labelProp",
"in",
"LABEL_PROPERTIES",
"for",
"l",
"in",
"gr",
".",
"ob... | @param x : graph entity
@param gr (Graph): RDF graph
@param preferred_languages (iterable)
Return the best available label in the graph for the passed entity.
If a set of preferred languages is given, try them in order. If none is
found, an arbitrary language will be chosen | [
"@param",
"x",
":",
"graph",
"entity",
"@param",
"gr",
"(",
"Graph",
")",
":",
"RDF",
"graph",
"@param",
"preferred_languages",
"(",
"iterable",
")"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/drawgraph.py#L130-L159 | train |
paulovn/sparql-kernel | sparqlkernel/drawgraph.py | rdf2dot | def rdf2dot( g, stream, opts={} ):
"""
Convert the RDF graph to DOT
Write the dot output to the stream
"""
accept_lang = set( opts.get('lang',[]) )
do_literal = opts.get('literal')
nodes = {}
links = []
def node_id(x):
if x not in nodes:
nodes[x] = "node%d" % le... | python | def rdf2dot( g, stream, opts={} ):
"""
Convert the RDF graph to DOT
Write the dot output to the stream
"""
accept_lang = set( opts.get('lang',[]) )
do_literal = opts.get('literal')
nodes = {}
links = []
def node_id(x):
if x not in nodes:
nodes[x] = "node%d" % le... | [
"def",
"rdf2dot",
"(",
"g",
",",
"stream",
",",
"opts",
"=",
"{",
"}",
")",
":",
"accept_lang",
"=",
"set",
"(",
"opts",
".",
"get",
"(",
"'lang'",
",",
"[",
"]",
")",
")",
"do_literal",
"=",
"opts",
".",
"get",
"(",
"'literal'",
")",
"nodes",
... | Convert the RDF graph to DOT
Write the dot output to the stream | [
"Convert",
"the",
"RDF",
"graph",
"to",
"DOT",
"Write",
"the",
"dot",
"output",
"to",
"the",
"stream"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/drawgraph.py#L163-L229 | train |
paulovn/sparql-kernel | sparqlkernel/drawgraph.py | draw_graph | def draw_graph( g, fmt='svg', prg='dot', options={} ):
"""
Draw an RDF graph as an image
"""
# Convert RDF to Graphviz
buf = StringIO()
rdf2dot( g, buf, options )
gv_options = options.get('graphviz',[])
if fmt == 'png':
gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ]
meta... | python | def draw_graph( g, fmt='svg', prg='dot', options={} ):
"""
Draw an RDF graph as an image
"""
# Convert RDF to Graphviz
buf = StringIO()
rdf2dot( g, buf, options )
gv_options = options.get('graphviz',[])
if fmt == 'png':
gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ]
meta... | [
"def",
"draw_graph",
"(",
"g",
",",
"fmt",
"=",
"'svg'",
",",
"prg",
"=",
"'dot'",
",",
"options",
"=",
"{",
"}",
")",
":",
"# Convert RDF to Graphviz",
"buf",
"=",
"StringIO",
"(",
")",
"rdf2dot",
"(",
"g",
",",
"buf",
",",
"options",
")",
"gv_optio... | Draw an RDF graph as an image | [
"Draw",
"an",
"RDF",
"graph",
"as",
"an",
"image"
] | 1d2d155ff5da72070cb2a98fae33ea8113fac782 | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/drawgraph.py#L281-L310 | train |
jleinonen/pytmatrix | pytmatrix/psd.py | PSDIntegrator.get_SZ | def get_SZ(self, psd, geometry):
"""
Compute the scattering matrices for the given PSD and geometries.
Returns:
The new amplitude (S) and phase (Z) matrices.
"""
if (self._S_table is None) or (self._Z_table is None):
raise AttributeError(
... | python | def get_SZ(self, psd, geometry):
"""
Compute the scattering matrices for the given PSD and geometries.
Returns:
The new amplitude (S) and phase (Z) matrices.
"""
if (self._S_table is None) or (self._Z_table is None):
raise AttributeError(
... | [
"def",
"get_SZ",
"(",
"self",
",",
"psd",
",",
"geometry",
")",
":",
"if",
"(",
"self",
".",
"_S_table",
"is",
"None",
")",
"or",
"(",
"self",
".",
"_Z_table",
"is",
"None",
")",
":",
"raise",
"AttributeError",
"(",
"\"Initialize or load the scattering tab... | Compute the scattering matrices for the given PSD and geometries.
Returns:
The new amplitude (S) and phase (Z) matrices. | [
"Compute",
"the",
"scattering",
"matrices",
"for",
"the",
"given",
"PSD",
"and",
"geometries",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/psd.py#L310-L334 | train |
jleinonen/pytmatrix | pytmatrix/psd.py | PSDIntegrator.init_scatter_table | def init_scatter_table(self, tm, angular_integration=False, verbose=False):
"""Initialize the scattering lookup tables.
Initialize the scattering lookup tables for the different geometries.
Before calling this, the following attributes must be set:
num_points, m_func, axis_ra... | python | def init_scatter_table(self, tm, angular_integration=False, verbose=False):
"""Initialize the scattering lookup tables.
Initialize the scattering lookup tables for the different geometries.
Before calling this, the following attributes must be set:
num_points, m_func, axis_ra... | [
"def",
"init_scatter_table",
"(",
"self",
",",
"tm",
",",
"angular_integration",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"self",
".",
"_psd_D",
"=",
"np",
".",
"linspace",
"(",
"self",
".",
"D_max",
"/",
"self",
".",
"num_points",
",",
"s... | Initialize the scattering lookup tables.
Initialize the scattering lookup tables for the different geometries.
Before calling this, the following attributes must be set:
num_points, m_func, axis_ratio_func, D_max, geometries
and additionally, all the desired attributes of the... | [
"Initialize",
"the",
"scattering",
"lookup",
"tables",
".",
"Initialize",
"the",
"scattering",
"lookup",
"tables",
"for",
"the",
"different",
"geometries",
".",
"Before",
"calling",
"this",
"the",
"following",
"attributes",
"must",
"be",
"set",
":",
"num_points",
... | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/psd.py#L374-L451 | train |
jleinonen/pytmatrix | pytmatrix/psd.py | PSDIntegrator.save_scatter_table | def save_scatter_table(self, fn, description=""):
"""Save the scattering lookup tables.
Save the state of the scattering lookup tables to a file.
This can be loaded later with load_scatter_table.
Other variables will not be saved, but this does not matter because
the re... | python | def save_scatter_table(self, fn, description=""):
"""Save the scattering lookup tables.
Save the state of the scattering lookup tables to a file.
This can be loaded later with load_scatter_table.
Other variables will not be saved, but this does not matter because
the re... | [
"def",
"save_scatter_table",
"(",
"self",
",",
"fn",
",",
"description",
"=",
"\"\"",
")",
":",
"data",
"=",
"{",
"\"description\"",
":",
"description",
",",
"\"time\"",
":",
"datetime",
".",
"now",
"(",
")",
",",
"\"psd_scatter\"",
":",
"(",
"self",
"."... | Save the scattering lookup tables.
Save the state of the scattering lookup tables to a file.
This can be loaded later with load_scatter_table.
Other variables will not be saved, but this does not matter because
the results of the computations are based only on the contents
... | [
"Save",
"the",
"scattering",
"lookup",
"tables",
".",
"Save",
"the",
"state",
"of",
"the",
"scattering",
"lookup",
"tables",
"to",
"a",
"file",
".",
"This",
"can",
"be",
"loaded",
"later",
"with",
"load_scatter_table",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/psd.py#L455-L477 | train |
jleinonen/pytmatrix | pytmatrix/psd.py | PSDIntegrator.load_scatter_table | def load_scatter_table(self, fn):
"""Load the scattering lookup tables.
Load the scattering lookup tables saved with save_scatter_table.
Args:
fn: The name of the scattering table file.
"""
data = pickle.load(file(fn))
if ("version" not ... | python | def load_scatter_table(self, fn):
"""Load the scattering lookup tables.
Load the scattering lookup tables saved with save_scatter_table.
Args:
fn: The name of the scattering table file.
"""
data = pickle.load(file(fn))
if ("version" not ... | [
"def",
"load_scatter_table",
"(",
"self",
",",
"fn",
")",
":",
"data",
"=",
"pickle",
".",
"load",
"(",
"file",
"(",
"fn",
")",
")",
"if",
"(",
"\"version\"",
"not",
"in",
"data",
")",
"or",
"(",
"data",
"[",
"\"version\"",
"]",
"!=",
"tmatrix_aux",
... | Load the scattering lookup tables.
Load the scattering lookup tables saved with save_scatter_table.
Args:
fn: The name of the scattering table file. | [
"Load",
"the",
"scattering",
"lookup",
"tables",
".",
"Load",
"the",
"scattering",
"lookup",
"tables",
"saved",
"with",
"save_scatter_table",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/psd.py#L480-L496 | train |
jleinonen/pytmatrix | pytmatrix/orientation.py | gaussian_pdf | def gaussian_pdf(std=10.0, mean=0.0):
"""Gaussian PDF for orientation averaging.
Args:
std: The standard deviation in degrees of the Gaussian PDF
mean: The mean in degrees of the Gaussian PDF. This should be a number
in the interval [0, 180)
Returns:
pdf(x), a function t... | python | def gaussian_pdf(std=10.0, mean=0.0):
"""Gaussian PDF for orientation averaging.
Args:
std: The standard deviation in degrees of the Gaussian PDF
mean: The mean in degrees of the Gaussian PDF. This should be a number
in the interval [0, 180)
Returns:
pdf(x), a function t... | [
"def",
"gaussian_pdf",
"(",
"std",
"=",
"10.0",
",",
"mean",
"=",
"0.0",
")",
":",
"norm_const",
"=",
"1.0",
"def",
"pdf",
"(",
"x",
")",
":",
"return",
"norm_const",
"*",
"np",
".",
"exp",
"(",
"-",
"0.5",
"*",
"(",
"(",
"x",
"-",
"mean",
")",... | Gaussian PDF for orientation averaging.
Args:
std: The standard deviation in degrees of the Gaussian PDF
mean: The mean in degrees of the Gaussian PDF. This should be a number
in the interval [0, 180)
Returns:
pdf(x), a function that returns the value of the spherical Jacobi... | [
"Gaussian",
"PDF",
"for",
"orientation",
"averaging",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/orientation.py#L27-L47 | train |
jleinonen/pytmatrix | pytmatrix/orientation.py | uniform_pdf | def uniform_pdf():
"""Uniform PDF for orientation averaging.
Returns:
pdf(x), a function that returns the value of the spherical Jacobian-
normalized uniform PDF. It is normalized for the interval [0, 180].
"""
norm_const = 1.0
def pdf(x):
return norm_const * np.sin(np.pi/18... | python | def uniform_pdf():
"""Uniform PDF for orientation averaging.
Returns:
pdf(x), a function that returns the value of the spherical Jacobian-
normalized uniform PDF. It is normalized for the interval [0, 180].
"""
norm_const = 1.0
def pdf(x):
return norm_const * np.sin(np.pi/18... | [
"def",
"uniform_pdf",
"(",
")",
":",
"norm_const",
"=",
"1.0",
"def",
"pdf",
"(",
"x",
")",
":",
"return",
"norm_const",
"*",
"np",
".",
"sin",
"(",
"np",
".",
"pi",
"/",
"180.0",
"*",
"x",
")",
"norm_dev",
"=",
"quad",
"(",
"pdf",
",",
"0.0",
... | Uniform PDF for orientation averaging.
Returns:
pdf(x), a function that returns the value of the spherical Jacobian-
normalized uniform PDF. It is normalized for the interval [0, 180]. | [
"Uniform",
"PDF",
"for",
"orientation",
"averaging",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/orientation.py#L50-L63 | train |
jleinonen/pytmatrix | pytmatrix/orientation.py | orient_averaged_adaptive | def orient_averaged_adaptive(tm):
"""Compute the T-matrix using variable orientation scatterers.
This method uses a very slow adaptive routine and should mainly be used
for reference purposes. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.
Args:
tm: TMat... | python | def orient_averaged_adaptive(tm):
"""Compute the T-matrix using variable orientation scatterers.
This method uses a very slow adaptive routine and should mainly be used
for reference purposes. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.
Args:
tm: TMat... | [
"def",
"orient_averaged_adaptive",
"(",
"tm",
")",
":",
"S",
"=",
"np",
".",
"zeros",
"(",
"(",
"2",
",",
"2",
")",
",",
"dtype",
"=",
"complex",
")",
"Z",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"4",
")",
")",
"def",
"Sfunc",
"(",
"beta... | Compute the T-matrix using variable orientation scatterers.
This method uses a very slow adaptive routine and should mainly be used
for reference purposes. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.
Args:
tm: TMatrix (or descendant) instance
Returns... | [
"Compute",
"the",
"T",
"-",
"matrix",
"using",
"variable",
"orientation",
"scatterers",
".",
"This",
"method",
"uses",
"a",
"very",
"slow",
"adaptive",
"routine",
"and",
"should",
"mainly",
"be",
"used",
"for",
"reference",
"purposes",
".",
"Uses",
"the",
"s... | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/orientation.py#L78-L117 | train |
jleinonen/pytmatrix | pytmatrix/orientation.py | orient_averaged_fixed | def orient_averaged_fixed(tm):
"""Compute the T-matrix using variable orientation scatterers.
This method uses a fast Gaussian quadrature and is suitable
for most use. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.
Args:
tm: TMatrix (or descendant) insta... | python | def orient_averaged_fixed(tm):
"""Compute the T-matrix using variable orientation scatterers.
This method uses a fast Gaussian quadrature and is suitable
for most use. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.
Args:
tm: TMatrix (or descendant) insta... | [
"def",
"orient_averaged_fixed",
"(",
"tm",
")",
":",
"S",
"=",
"np",
".",
"zeros",
"(",
"(",
"2",
",",
"2",
")",
",",
"dtype",
"=",
"complex",
")",
"Z",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"4",
")",
")",
"ap",
"=",
"np",
".",
"lins... | Compute the T-matrix using variable orientation scatterers.
This method uses a fast Gaussian quadrature and is suitable
for most use. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.
Args:
tm: TMatrix (or descendant) instance.
Returns:
The amplitu... | [
"Compute",
"the",
"T",
"-",
"matrix",
"using",
"variable",
"orientation",
"scatterers",
".",
"This",
"method",
"uses",
"a",
"fast",
"Gaussian",
"quadrature",
"and",
"is",
"suitable",
"for",
"most",
"use",
".",
"Uses",
"the",
"set",
"particle",
"orientation",
... | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/orientation.py#L120-L149 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | Scatterer.set_geometry | def set_geometry(self, geom):
"""A convenience function to set the geometry variables.
Args:
geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta).
See the Scatterer class documentation for a description of these
angles.
"""
(self.thet0, self... | python | def set_geometry(self, geom):
"""A convenience function to set the geometry variables.
Args:
geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta).
See the Scatterer class documentation for a description of these
angles.
"""
(self.thet0, self... | [
"def",
"set_geometry",
"(",
"self",
",",
"geom",
")",
":",
"(",
"self",
".",
"thet0",
",",
"self",
".",
"thet",
",",
"self",
".",
"phi0",
",",
"self",
".",
"phi",
",",
"self",
".",
"alpha",
",",
"self",
".",
"beta",
")",
"=",
"geom"
] | A convenience function to set the geometry variables.
Args:
geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta).
See the Scatterer class documentation for a description of these
angles. | [
"A",
"convenience",
"function",
"to",
"set",
"the",
"geometry",
"variables",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L151-L160 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | Scatterer.get_geometry | def get_geometry(self):
"""A convenience function to get the geometry variables.
Returns:
A tuple containing (thet0, thet, phi0, phi, alpha, beta).
See the Scatterer class documentation for a description of these
angles.
"""
return (self.thet0, self.t... | python | def get_geometry(self):
"""A convenience function to get the geometry variables.
Returns:
A tuple containing (thet0, thet, phi0, phi, alpha, beta).
See the Scatterer class documentation for a description of these
angles.
"""
return (self.thet0, self.t... | [
"def",
"get_geometry",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"thet0",
",",
"self",
".",
"thet",
",",
"self",
".",
"phi0",
",",
"self",
".",
"phi",
",",
"self",
".",
"alpha",
",",
"self",
".",
"beta",
")"
] | A convenience function to get the geometry variables.
Returns:
A tuple containing (thet0, thet, phi0, phi, alpha, beta).
See the Scatterer class documentation for a description of these
angles. | [
"A",
"convenience",
"function",
"to",
"get",
"the",
"geometry",
"variables",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L163-L172 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | Scatterer._init_tmatrix | def _init_tmatrix(self):
"""Initialize the T-matrix.
"""
if self.radius_type == Scatterer.RADIUS_MAXIMUM:
# Maximum radius is not directly supported in the original
# so we convert it to equal volume radius
radius_type = Scatterer.RADIUS_EQUAL_VOLUME
... | python | def _init_tmatrix(self):
"""Initialize the T-matrix.
"""
if self.radius_type == Scatterer.RADIUS_MAXIMUM:
# Maximum radius is not directly supported in the original
# so we convert it to equal volume radius
radius_type = Scatterer.RADIUS_EQUAL_VOLUME
... | [
"def",
"_init_tmatrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"radius_type",
"==",
"Scatterer",
".",
"RADIUS_MAXIMUM",
":",
"# Maximum radius is not directly supported in the original",
"# so we convert it to equal volume radius",
"radius_type",
"=",
"Scatterer",
".",
"... | Initialize the T-matrix. | [
"Initialize",
"the",
"T",
"-",
"matrix",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L202-L219 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | Scatterer._init_orient | def _init_orient(self):
"""Retrieve the quadrature points and weights if needed.
"""
if self.orient == orientation.orient_averaged_fixed:
(self.beta_p, self.beta_w) = quadrature.get_points_and_weights(
self.or_pdf, 0, 180, self.n_beta)
self._set_orient_signatu... | python | def _init_orient(self):
"""Retrieve the quadrature points and weights if needed.
"""
if self.orient == orientation.orient_averaged_fixed:
(self.beta_p, self.beta_w) = quadrature.get_points_and_weights(
self.or_pdf, 0, 180, self.n_beta)
self._set_orient_signatu... | [
"def",
"_init_orient",
"(",
"self",
")",
":",
"if",
"self",
".",
"orient",
"==",
"orientation",
".",
"orient_averaged_fixed",
":",
"(",
"self",
".",
"beta_p",
",",
"self",
".",
"beta_w",
")",
"=",
"quadrature",
".",
"get_points_and_weights",
"(",
"self",
"... | Retrieve the quadrature points and weights if needed. | [
"Retrieve",
"the",
"quadrature",
"points",
"and",
"weights",
"if",
"needed",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L222-L228 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | Scatterer._set_scatter_signature | def _set_scatter_signature(self):
"""Mark the amplitude and scattering matrices as up to date.
"""
self._scatter_signature = (self.thet0, self.thet, self.phi0, self.phi,
self.alpha, self.beta, self.orient) | python | def _set_scatter_signature(self):
"""Mark the amplitude and scattering matrices as up to date.
"""
self._scatter_signature = (self.thet0, self.thet, self.phi0, self.phi,
self.alpha, self.beta, self.orient) | [
"def",
"_set_scatter_signature",
"(",
"self",
")",
":",
"self",
".",
"_scatter_signature",
"=",
"(",
"self",
".",
"thet0",
",",
"self",
".",
"thet",
",",
"self",
".",
"phi0",
",",
"self",
".",
"phi",
",",
"self",
".",
"alpha",
",",
"self",
".",
"beta... | Mark the amplitude and scattering matrices as up to date. | [
"Mark",
"the",
"amplitude",
"and",
"scattering",
"matrices",
"as",
"up",
"to",
"date",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L231-L235 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | Scatterer.get_SZ_single | def get_SZ_single(self, alpha=None, beta=None):
"""Get the S and Z matrices for a single orientation.
"""
if alpha == None:
alpha = self.alpha
if beta == None:
beta = self.beta
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
... | python | def get_SZ_single(self, alpha=None, beta=None):
"""Get the S and Z matrices for a single orientation.
"""
if alpha == None:
alpha = self.alpha
if beta == None:
beta = self.beta
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
... | [
"def",
"get_SZ_single",
"(",
"self",
",",
"alpha",
"=",
"None",
",",
"beta",
"=",
"None",
")",
":",
"if",
"alpha",
"==",
"None",
":",
"alpha",
"=",
"self",
".",
"alpha",
"if",
"beta",
"==",
"None",
":",
"beta",
"=",
"self",
".",
"beta",
"tm_outdate... | Get the S and Z matrices for a single orientation. | [
"Get",
"the",
"S",
"and",
"Z",
"matrices",
"for",
"a",
"single",
"orientation",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L263-L288 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | Scatterer.get_SZ_orient | def get_SZ_orient(self):
"""Get the S and Z matrices using the specified orientation averaging.
"""
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt,
self.ndgs)
scatter_outdated... | python | def get_SZ_orient(self):
"""Get the S and Z matrices using the specified orientation averaging.
"""
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt,
self.ndgs)
scatter_outdated... | [
"def",
"get_SZ_orient",
"(",
"self",
")",
":",
"tm_outdated",
"=",
"self",
".",
"_tm_signature",
"!=",
"(",
"self",
".",
"radius",
",",
"self",
".",
"radius_type",
",",
"self",
".",
"wavelength",
",",
"self",
".",
"m",
",",
"self",
".",
"axis_ratio",
"... | Get the S and Z matrices using the specified orientation averaging. | [
"Get",
"the",
"S",
"and",
"Z",
"matrices",
"using",
"the",
"specified",
"orientation",
"averaging",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L291-L312 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix.py | Scatterer.get_SZ | def get_SZ(self):
"""Get the S and Z matrices using the current parameters.
"""
if self.psd_integrator is None:
(self._S, self._Z) = self.get_SZ_orient()
else:
scatter_outdated = self._scatter_signature != (self.thet0,
self.thet, self.phi0, self.p... | python | def get_SZ(self):
"""Get the S and Z matrices using the current parameters.
"""
if self.psd_integrator is None:
(self._S, self._Z) = self.get_SZ_orient()
else:
scatter_outdated = self._scatter_signature != (self.thet0,
self.thet, self.phi0, self.p... | [
"def",
"get_SZ",
"(",
"self",
")",
":",
"if",
"self",
".",
"psd_integrator",
"is",
"None",
":",
"(",
"self",
".",
"_S",
",",
"self",
".",
"_Z",
")",
"=",
"self",
".",
"get_SZ_orient",
"(",
")",
"else",
":",
"scatter_outdated",
"=",
"self",
".",
"_s... | Get the S and Z matrices using the current parameters. | [
"Get",
"the",
"S",
"and",
"Z",
"matrices",
"using",
"the",
"current",
"parameters",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix.py#L315-L333 | train |
jleinonen/pytmatrix | pytmatrix/quadrature/quadrature.py | get_points_and_weights | def get_points_and_weights(w_func=lambda x : np.ones(x.shape),
left=-1.0, right=1.0, num_points=5, n=4096):
"""Quadratude points and weights for a weighting function.
Points and weights for approximating the integral
I = \int_left^right f(x) w(x) dx
given the weighting function w(x) using the... | python | def get_points_and_weights(w_func=lambda x : np.ones(x.shape),
left=-1.0, right=1.0, num_points=5, n=4096):
"""Quadratude points and weights for a weighting function.
Points and weights for approximating the integral
I = \int_left^right f(x) w(x) dx
given the weighting function w(x) using the... | [
"def",
"get_points_and_weights",
"(",
"w_func",
"=",
"lambda",
"x",
":",
"np",
".",
"ones",
"(",
"x",
".",
"shape",
")",
",",
"left",
"=",
"-",
"1.0",
",",
"right",
"=",
"1.0",
",",
"num_points",
"=",
"5",
",",
"n",
"=",
"4096",
")",
":",
"dx",
... | Quadratude points and weights for a weighting function.
Points and weights for approximating the integral
I = \int_left^right f(x) w(x) dx
given the weighting function w(x) using the approximation
I ~ w_i f(x_i)
Args:
w_func: The weighting function w(x). Must be a function that ta... | [
"Quadratude",
"points",
"and",
"weights",
"for",
"a",
"weighting",
"function",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/quadrature/quadrature.py#L52-L92 | train |
jleinonen/pytmatrix | pytmatrix/scatter.py | sca_intensity | def sca_intensity(scatterer, h_pol=True):
"""Scattering intensity (phase function) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The differential scatter... | python | def sca_intensity(scatterer, h_pol=True):
"""Scattering intensity (phase function) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The differential scatter... | [
"def",
"sca_intensity",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"Z",
"=",
"scatterer",
".",
"get_Z",
"(",
")",
"return",
"(",
"Z",
"[",
"0",
",",
"0",
"]",
"-",
"Z",
"[",
"0",
",",
"1",
"]",
")",
"if",
"h_pol",
"else",
"(",
"Z"... | Scattering intensity (phase function) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The differential scattering cross section. | [
"Scattering",
"intensity",
"(",
"phase",
"function",
")",
"for",
"the",
"current",
"setup",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/scatter.py#L31-L43 | train |
jleinonen/pytmatrix | pytmatrix/scatter.py | ldr | def ldr(scatterer, h_pol=True):
"""
Linear depolarizarion ratio (LDR) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), return LDR_h.
If False, return LDR_v.
Returns:
The LDR.
"""
Z = scatterer.get_Z()
if h_pol:
r... | python | def ldr(scatterer, h_pol=True):
"""
Linear depolarizarion ratio (LDR) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), return LDR_h.
If False, return LDR_v.
Returns:
The LDR.
"""
Z = scatterer.get_Z()
if h_pol:
r... | [
"def",
"ldr",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"Z",
"=",
"scatterer",
".",
"get_Z",
"(",
")",
"if",
"h_pol",
":",
"return",
"(",
"Z",
"[",
"0",
",",
"0",
"]",
"-",
"Z",
"[",
"0",
",",
"1",
"]",
"+",
"Z",
"[",
"1",
",... | Linear depolarizarion ratio (LDR) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), return LDR_h.
If False, return LDR_v.
Returns:
The LDR. | [
"Linear",
"depolarizarion",
"ratio",
"(",
"LDR",
")",
"for",
"the",
"current",
"setup",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/scatter.py#L46-L64 | train |
jleinonen/pytmatrix | pytmatrix/scatter.py | sca_xsect | def sca_xsect(scatterer, h_pol=True):
"""Scattering cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The scattering cross s... | python | def sca_xsect(scatterer, h_pol=True):
"""Scattering cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The scattering cross s... | [
"def",
"sca_xsect",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"if",
"scatterer",
".",
"psd_integrator",
"is",
"not",
"None",
":",
"return",
"scatterer",
".",
"psd_integrator",
".",
"get_angular_integrated",
"(",
"scatterer",
".",
"psd",
",",
"sc... | Scattering cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The scattering cross section. | [
"Scattering",
"cross",
"section",
"for",
"the",
"current",
"setup",
"with",
"polarization",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/scatter.py#L67-L97 | train |
jleinonen/pytmatrix | pytmatrix/scatter.py | ext_xsect | def ext_xsect(scatterer, h_pol=True):
"""Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The extinction cross s... | python | def ext_xsect(scatterer, h_pol=True):
"""Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The extinction cross s... | [
"def",
"ext_xsect",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"if",
"scatterer",
".",
"psd_integrator",
"is",
"not",
"None",
":",
"try",
":",
"return",
"scatterer",
".",
"psd_integrator",
".",
"get_angular_integrated",
"(",
"scatterer",
".",
"ps... | Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The extinction cross section. | [
"Extinction",
"cross",
"section",
"for",
"the",
"current",
"setup",
"with",
"polarization",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/scatter.py#L100-L133 | train |
jleinonen/pytmatrix | pytmatrix/scatter.py | ssa | def ssa(scatterer, h_pol=True):
"""Single-scattering albedo for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The single-scattering albedo... | python | def ssa(scatterer, h_pol=True):
"""Single-scattering albedo for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The single-scattering albedo... | [
"def",
"ssa",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"ext_xs",
"=",
"ext_xsect",
"(",
"scatterer",
",",
"h_pol",
"=",
"h_pol",
")",
"return",
"sca_xsect",
"(",
"scatterer",
",",
"h_pol",
"=",
"h_pol",
")",
"/",
"ext_xs",
"if",
"ext_xs",... | Single-scattering albedo for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The single-scattering albedo. | [
"Single",
"-",
"scattering",
"albedo",
"for",
"the",
"current",
"setup",
"with",
"polarization",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/scatter.py#L136-L149 | train |
jleinonen/pytmatrix | pytmatrix/scatter.py | asym | def asym(scatterer, h_pol=True):
"""Asymmetry parameter for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The asymmetry parameter.
"""... | python | def asym(scatterer, h_pol=True):
"""Asymmetry parameter for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The asymmetry parameter.
"""... | [
"def",
"asym",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"if",
"scatterer",
".",
"psd_integrator",
"is",
"not",
"None",
":",
"return",
"scatterer",
".",
"psd_integrator",
".",
"get_angular_integrated",
"(",
"scatterer",
".",
"psd",
",",
"scatter... | Asymmetry parameter for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The asymmetry parameter. | [
"Asymmetry",
"parameter",
"for",
"the",
"current",
"setup",
"with",
"polarization",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/scatter.py#L152-L186 | train |
jleinonen/pytmatrix | pytmatrix/radar.py | radar_xsect | def radar_xsect(scatterer, h_pol=True):
"""Radar cross section for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The radar cross section.
"""
Z = sca... | python | def radar_xsect(scatterer, h_pol=True):
"""Radar cross section for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The radar cross section.
"""
Z = sca... | [
"def",
"radar_xsect",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"Z",
"=",
"scatterer",
".",
"get_Z",
"(",
")",
"if",
"h_pol",
":",
"return",
"2",
"*",
"np",
".",
"pi",
"*",
"(",
"Z",
"[",
"0",
",",
"0",
"]",
"-",
"Z",
"[",
"0",
... | Radar cross section for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The radar cross section. | [
"Radar",
"cross",
"section",
"for",
"the",
"current",
"setup",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/radar.py#L27-L44 | train |
jleinonen/pytmatrix | pytmatrix/radar.py | refl | def refl(scatterer, h_pol=True):
"""Reflectivity (with number concentration N=1) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The reflectivity.
NOTE: T... | python | def refl(scatterer, h_pol=True):
"""Reflectivity (with number concentration N=1) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The reflectivity.
NOTE: T... | [
"def",
"refl",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"return",
"scatterer",
".",
"wavelength",
"**",
"4",
"/",
"(",
"np",
".",
"pi",
"**",
"5",
"*",
"scatterer",
".",
"Kw_sqr",
")",
"*",
"radar_xsect",
"(",
"scatterer",
",",
"h_pol",... | Reflectivity (with number concentration N=1) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The reflectivity.
NOTE: To compute reflectivity in dBZ, give the ... | [
"Reflectivity",
"(",
"with",
"number",
"concentration",
"N",
"=",
"1",
")",
"for",
"the",
"current",
"setup",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/radar.py#L47-L62 | train |
jleinonen/pytmatrix | pytmatrix/radar.py | delta_hv | def delta_hv(scatterer):
"""
Delta_hv for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
Delta_hv [rad].
"""
Z = scatterer.get_Z()
return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3]) | python | def delta_hv(scatterer):
"""
Delta_hv for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
Delta_hv [rad].
"""
Z = scatterer.get_Z()
return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3]) | [
"def",
"delta_hv",
"(",
"scatterer",
")",
":",
"Z",
"=",
"scatterer",
".",
"get_Z",
"(",
")",
"return",
"np",
".",
"arctan2",
"(",
"Z",
"[",
"2",
",",
"3",
"]",
"-",
"Z",
"[",
"3",
",",
"2",
"]",
",",
"-",
"Z",
"[",
"2",
",",
"2",
"]",
"-... | Delta_hv for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
Delta_hv [rad]. | [
"Delta_hv",
"for",
"the",
"current",
"setup",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/radar.py#L81-L92 | train |
jleinonen/pytmatrix | pytmatrix/radar.py | rho_hv | def rho_hv(scatterer):
"""
Copolarized correlation (rho_hv) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
rho_hv.
"""
Z = scatterer.get_Z()
a = (Z[2,2] + Z[3,3])**2 + (Z[3,2] - Z[2,3])**2
b = (Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1])
c = (Z[0,0] + ... | python | def rho_hv(scatterer):
"""
Copolarized correlation (rho_hv) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
rho_hv.
"""
Z = scatterer.get_Z()
a = (Z[2,2] + Z[3,3])**2 + (Z[3,2] - Z[2,3])**2
b = (Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1])
c = (Z[0,0] + ... | [
"def",
"rho_hv",
"(",
"scatterer",
")",
":",
"Z",
"=",
"scatterer",
".",
"get_Z",
"(",
")",
"a",
"=",
"(",
"Z",
"[",
"2",
",",
"2",
"]",
"+",
"Z",
"[",
"3",
",",
"3",
"]",
")",
"**",
"2",
"+",
"(",
"Z",
"[",
"3",
",",
"2",
"]",
"-",
"... | Copolarized correlation (rho_hv) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
rho_hv. | [
"Copolarized",
"correlation",
"(",
"rho_hv",
")",
"for",
"the",
"current",
"setup",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/radar.py#L95-L109 | train |
jleinonen/pytmatrix | pytmatrix/radar.py | Kdp | def Kdp(scatterer):
"""
Specific differential phase (K_dp) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
K_dp [deg/km].
NOTE: This only returns the correct value if the particle diameter and
wavelength are given in [mm]. The scatterer object should be ... | python | def Kdp(scatterer):
"""
Specific differential phase (K_dp) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
K_dp [deg/km].
NOTE: This only returns the correct value if the particle diameter and
wavelength are given in [mm]. The scatterer object should be ... | [
"def",
"Kdp",
"(",
"scatterer",
")",
":",
"if",
"(",
"scatterer",
".",
"thet0",
"!=",
"scatterer",
".",
"thet",
")",
"or",
"(",
"scatterer",
".",
"phi0",
"!=",
"scatterer",
".",
"phi",
")",
":",
"raise",
"ValueError",
"(",
"\"A forward scattering geometry ... | Specific differential phase (K_dp) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
K_dp [deg/km].
NOTE: This only returns the correct value if the particle diameter and
wavelength are given in [mm]. The scatterer object should be set to
forward scattering g... | [
"Specific",
"differential",
"phase",
"(",
"K_dp",
")",
"for",
"the",
"current",
"setup",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/radar.py#L112-L133 | train |
jleinonen/pytmatrix | pytmatrix/refractive.py | mg_refractive | def mg_refractive(m, mix):
"""Maxwell-Garnett EMA for the refractive index.
Args:
m: Tuple of the complex refractive indices of the media.
mix: Tuple of the volume fractions of the media, len(mix)==len(m)
(if sum(mix)!=1, these are taken relative to sum(mix))
Returns:
The ... | python | def mg_refractive(m, mix):
"""Maxwell-Garnett EMA for the refractive index.
Args:
m: Tuple of the complex refractive indices of the media.
mix: Tuple of the volume fractions of the media, len(mix)==len(m)
(if sum(mix)!=1, these are taken relative to sum(mix))
Returns:
The ... | [
"def",
"mg_refractive",
"(",
"m",
",",
"mix",
")",
":",
"if",
"len",
"(",
"m",
")",
"==",
"2",
":",
"cF",
"=",
"float",
"(",
"mix",
"[",
"1",
"]",
")",
"/",
"(",
"mix",
"[",
"0",
"]",
"+",
"mix",
"[",
"1",
"]",
")",
"*",
"(",
"m",
"[",
... | Maxwell-Garnett EMA for the refractive index.
Args:
m: Tuple of the complex refractive indices of the media.
mix: Tuple of the volume fractions of the media, len(mix)==len(m)
(if sum(mix)!=1, these are taken relative to sum(mix))
Returns:
The Maxwell-Garnett approximation for ... | [
"Maxwell",
"-",
"Garnett",
"EMA",
"for",
"the",
"refractive",
"index",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/refractive.py#L29-L57 | train |
jleinonen/pytmatrix | pytmatrix/refractive.py | bruggeman_refractive | def bruggeman_refractive(m, mix):
"""Bruggeman EMA for the refractive index.
For instructions, see mg_refractive in this module, except this routine
only works for two components.
"""
f1 = mix[0]/sum(mix)
f2 = mix[1]/sum(mix)
e1 = m[0]**2
e2 = m[1]**2
a = -2*(f1+f2)
b = (2*f1*e1... | python | def bruggeman_refractive(m, mix):
"""Bruggeman EMA for the refractive index.
For instructions, see mg_refractive in this module, except this routine
only works for two components.
"""
f1 = mix[0]/sum(mix)
f2 = mix[1]/sum(mix)
e1 = m[0]**2
e2 = m[1]**2
a = -2*(f1+f2)
b = (2*f1*e1... | [
"def",
"bruggeman_refractive",
"(",
"m",
",",
"mix",
")",
":",
"f1",
"=",
"mix",
"[",
"0",
"]",
"/",
"sum",
"(",
"mix",
")",
"f2",
"=",
"mix",
"[",
"1",
"]",
"/",
"sum",
"(",
"mix",
")",
"e1",
"=",
"m",
"[",
"0",
"]",
"**",
"2",
"e2",
"="... | Bruggeman EMA for the refractive index.
For instructions, see mg_refractive in this module, except this routine
only works for two components. | [
"Bruggeman",
"EMA",
"for",
"the",
"refractive",
"index",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/refractive.py#L60-L74 | train |
jleinonen/pytmatrix | pytmatrix/refractive.py | ice_refractive | def ice_refractive(file):
"""
Interpolator for the refractive indices of ice.
Inputs:
File to read the refractive index lookup table from.
This is supplied as "ice_refr.dat", retrieved from
http://www.atmos.washington.edu/ice_optical_constants/
Returns:
A callable object th... | python | def ice_refractive(file):
"""
Interpolator for the refractive indices of ice.
Inputs:
File to read the refractive index lookup table from.
This is supplied as "ice_refr.dat", retrieved from
http://www.atmos.washington.edu/ice_optical_constants/
Returns:
A callable object th... | [
"def",
"ice_refractive",
"(",
"file",
")",
":",
"D",
"=",
"np",
".",
"loadtxt",
"(",
"file",
")",
"log_wl",
"=",
"np",
".",
"log10",
"(",
"D",
"[",
":",
",",
"0",
"]",
"/",
"1000",
")",
"re",
"=",
"D",
"[",
":",
",",
"1",
"]",
"log_im",
"="... | Interpolator for the refractive indices of ice.
Inputs:
File to read the refractive index lookup table from.
This is supplied as "ice_refr.dat", retrieved from
http://www.atmos.washington.edu/ice_optical_constants/
Returns:
A callable object that takes as parameters the wavelength ... | [
"Interpolator",
"for",
"the",
"refractive",
"indices",
"of",
"ice",
"."
] | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/refractive.py#L107-L142 | train |
jleinonen/pytmatrix | pytmatrix/tmatrix_aux.py | dsr_thurai_2007 | def dsr_thurai_2007(D_eq):
"""
Drop shape relationship function from Thurai2007
(http://dx.doi.org/10.1175/JTECH2051.1) paper.
Arguments:
D_eq: Drop volume-equivalent diameter (mm)
Returns:
r: The vertical-to-horizontal drop axis ratio. Note: the Scatterer class
expects hori... | python | def dsr_thurai_2007(D_eq):
"""
Drop shape relationship function from Thurai2007
(http://dx.doi.org/10.1175/JTECH2051.1) paper.
Arguments:
D_eq: Drop volume-equivalent diameter (mm)
Returns:
r: The vertical-to-horizontal drop axis ratio. Note: the Scatterer class
expects hori... | [
"def",
"dsr_thurai_2007",
"(",
"D_eq",
")",
":",
"if",
"D_eq",
"<",
"0.7",
":",
"return",
"1.0",
"elif",
"D_eq",
"<",
"1.5",
":",
"return",
"1.173",
"-",
"0.5165",
"*",
"D_eq",
"+",
"0.4698",
"*",
"D_eq",
"**",
"2",
"-",
"0.1317",
"*",
"D_eq",
"**"... | Drop shape relationship function from Thurai2007
(http://dx.doi.org/10.1175/JTECH2051.1) paper.
Arguments:
D_eq: Drop volume-equivalent diameter (mm)
Returns:
r: The vertical-to-horizontal drop axis ratio. Note: the Scatterer class
expects horizontal to vertical, so you should pass ... | [
"Drop",
"shape",
"relationship",
"function",
"from",
"Thurai2007",
"(",
"http",
":",
"//",
"dx",
".",
"doi",
".",
"org",
"/",
"10",
".",
"1175",
"/",
"JTECH2051",
".",
"1",
")",
"paper",
".",
"Arguments",
":",
"D_eq",
":",
"Drop",
"volume",
"-",
"equ... | 8803507fe5332786feab105fa74acf63e7121718 | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/tmatrix_aux.py#L47-L66 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/compute.py | feature_importances | def feature_importances(data, top_n=None, feature_names=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure.
If data is a scikit-learn model with sub-estimators (e.g. RandomForest,
AdaBoost) the function will compute the standard deviation of each
... | python | def feature_importances(data, top_n=None, feature_names=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure.
If data is a scikit-learn model with sub-estimators (e.g. RandomForest,
AdaBoost) the function will compute the standard deviation of each
... | [
"def",
"feature_importances",
"(",
"data",
",",
"top_n",
"=",
"None",
",",
"feature_names",
"=",
"None",
")",
":",
"# data can be either a sklearn estimator or an iterator with",
"# the actual importances values, try to get the values",
"try",
":",
"imp",
"=",
"data",
".",
... | Get and order feature importances from a scikit-learn model
or from an array-like structure.
If data is a scikit-learn model with sub-estimators (e.g. RandomForest,
AdaBoost) the function will compute the standard deviation of each
feature.
Parameters
----------
data : sklearn model or arr... | [
"Get",
"and",
"order",
"feature",
"importances",
"from",
"a",
"scikit",
"-",
"learn",
"model",
"or",
"from",
"an",
"array",
"-",
"like",
"structure",
"."
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/compute.py#L4-L89 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/util.py | _group_by | def _group_by(data, criteria):
"""
Group objects in data using a function or a key
"""
if isinstance(criteria, str):
criteria_str = criteria
def criteria(x):
return x[criteria_str]
res = defaultdict(list)
for element in data:
key = criteria(element)
... | python | def _group_by(data, criteria):
"""
Group objects in data using a function or a key
"""
if isinstance(criteria, str):
criteria_str = criteria
def criteria(x):
return x[criteria_str]
res = defaultdict(list)
for element in data:
key = criteria(element)
... | [
"def",
"_group_by",
"(",
"data",
",",
"criteria",
")",
":",
"if",
"isinstance",
"(",
"criteria",
",",
"str",
")",
":",
"criteria_str",
"=",
"criteria",
"def",
"criteria",
"(",
"x",
")",
":",
"return",
"x",
"[",
"criteria_str",
"]",
"res",
"=",
"default... | Group objects in data using a function or a key | [
"Group",
"objects",
"in",
"data",
"using",
"a",
"function",
"or",
"a",
"key"
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/util.py#L37-L51 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/util.py | _get_params_value | def _get_params_value(params):
"""
Given an iterator (k1, k2), returns a function that when called
with an object obj returns a tuple of the form:
((k1, obj.parameters[k1]), (k2, obj.parameters[k2]))
"""
# sort params for consistency
ord_params = sorted(params)
def fn(obj):
... | python | def _get_params_value(params):
"""
Given an iterator (k1, k2), returns a function that when called
with an object obj returns a tuple of the form:
((k1, obj.parameters[k1]), (k2, obj.parameters[k2]))
"""
# sort params for consistency
ord_params = sorted(params)
def fn(obj):
... | [
"def",
"_get_params_value",
"(",
"params",
")",
":",
"# sort params for consistency",
"ord_params",
"=",
"sorted",
"(",
"params",
")",
"def",
"fn",
"(",
"obj",
")",
":",
"l",
"=",
"[",
"]",
"for",
"p",
"in",
"ord_params",
":",
"try",
":",
"l",
".",
"ap... | Given an iterator (k1, k2), returns a function that when called
with an object obj returns a tuple of the form:
((k1, obj.parameters[k1]), (k2, obj.parameters[k2])) | [
"Given",
"an",
"iterator",
"(",
"k1",
"k2",
")",
"returns",
"a",
"function",
"that",
"when",
"called",
"with",
"an",
"object",
"obj",
"returns",
"a",
"tuple",
"of",
"the",
"form",
":",
"((",
"k1",
"obj",
".",
"parameters",
"[",
"k1",
"]",
")",
"(",
... | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/util.py#L54-L71 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/util.py | _product | def _product(k, v):
"""
Perform the product between two objects
even if they don't support iteration
"""
if not _can_iterate(k):
k = [k]
if not _can_iterate(v):
v = [v]
return list(product(k, v)) | python | def _product(k, v):
"""
Perform the product between two objects
even if they don't support iteration
"""
if not _can_iterate(k):
k = [k]
if not _can_iterate(v):
v = [v]
return list(product(k, v)) | [
"def",
"_product",
"(",
"k",
",",
"v",
")",
":",
"if",
"not",
"_can_iterate",
"(",
"k",
")",
":",
"k",
"=",
"[",
"k",
"]",
"if",
"not",
"_can_iterate",
"(",
"v",
")",
":",
"v",
"=",
"[",
"v",
"]",
"return",
"list",
"(",
"product",
"(",
"k",
... | Perform the product between two objects
even if they don't support iteration | [
"Perform",
"the",
"product",
"between",
"two",
"objects",
"even",
"if",
"they",
"don",
"t",
"support",
"iteration"
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/util.py#L80-L89 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/util.py | _mapping_to_tuple_pairs | def _mapping_to_tuple_pairs(d):
"""
Convert a mapping object (such as a dictionary) to tuple pairs,
using its keys and values to generate the pairs and then generating
all possible combinations between those
e.g. {1: (1,2,3)} -> (((1, 1),), ((1, 2),), ((1, 3),))
"""
# order t... | python | def _mapping_to_tuple_pairs(d):
"""
Convert a mapping object (such as a dictionary) to tuple pairs,
using its keys and values to generate the pairs and then generating
all possible combinations between those
e.g. {1: (1,2,3)} -> (((1, 1),), ((1, 2),), ((1, 3),))
"""
# order t... | [
"def",
"_mapping_to_tuple_pairs",
"(",
"d",
")",
":",
"# order the keys, this will prevent different implementations of Python,",
"# return different results from the same dictionary since the order of",
"# iteration depends on it",
"t",
"=",
"[",
"]",
"ord_keys",
"=",
"sorted",
"(",... | Convert a mapping object (such as a dictionary) to tuple pairs,
using its keys and values to generate the pairs and then generating
all possible combinations between those
e.g. {1: (1,2,3)} -> (((1, 1),), ((1, 2),), ((1, 3),)) | [
"Convert",
"a",
"mapping",
"object",
"(",
"such",
"as",
"a",
"dictionary",
")",
"to",
"tuple",
"pairs",
"using",
"its",
"keys",
"and",
"values",
"to",
"generate",
"the",
"pairs",
"and",
"then",
"generating",
"all",
"possible",
"combinations",
"between",
"tho... | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/util.py#L92-L106 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/plot/learning_curve.py | learning_curve | def learning_curve(train_scores, test_scores, train_sizes, ax=None):
"""Plot a learning curve
Plot a metric vs number of examples for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training set
test_scores : array-like
Scores for the te... | python | def learning_curve(train_scores, test_scores, train_sizes, ax=None):
"""Plot a learning curve
Plot a metric vs number of examples for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training set
test_scores : array-like
Scores for the te... | [
"def",
"learning_curve",
"(",
"train_scores",
",",
"test_scores",
",",
"train_sizes",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"ax",
".",
"grid",
"(",
")",
"ax",
".",
"set_title",
"(",... | Plot a learning curve
Plot a metric vs number of examples for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training set
test_scores : array-like
Scores for the test set
train_sizes : array-like
Relative or absolute numbers of ... | [
"Plot",
"a",
"learning",
"curve"
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/learning_curve.py#L5-L59 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/plot/precision_recall.py | precision_recall | def precision_recall(y_true, y_score, ax=None):
"""
Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary
classification or [n... | python | def precision_recall(y_true, y_score, ax=None):
"""
Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary
classification or [n... | [
"def",
"precision_recall",
"(",
"y_true",
",",
"y_score",
",",
"ax",
"=",
"None",
")",
":",
"if",
"any",
"(",
"(",
"val",
"is",
"None",
"for",
"val",
"in",
"(",
"y_true",
",",
"y_score",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"'y_true and y_... | Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary
classification or [n_samples, n_classes] for multiclass
Target scores (... | [
"Plot",
"precision",
"-",
"recall",
"curve",
"."
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/precision_recall.py#L9-L70 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/plot/precision_recall.py | _precision_recall | def _precision_recall(y_true, y_score, ax=None):
"""
Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples]
Target scores (estimator predictions).
ax : matplo... | python | def _precision_recall(y_true, y_score, ax=None):
"""
Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples]
Target scores (estimator predictions).
ax : matplo... | [
"def",
"_precision_recall",
"(",
"y_true",
",",
"y_score",
",",
"ax",
"=",
"None",
")",
":",
"precision",
",",
"recall",
",",
"_",
"=",
"precision_recall_curve",
"(",
"y_true",
",",
"y_score",
")",
"average_precision",
"=",
"average_precision_score",
"(",
"y_t... | Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples]
Target scores (estimator predictions).
ax : matplotlib Axes
Axes object to draw the plot onto, otherwis... | [
"Plot",
"precision",
"-",
"recall",
"curve",
"."
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/precision_recall.py#L73-L101 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/plot/precision_recall.py | _precision_recall_multi | def _precision_recall_multi(y_true, y_score, ax=None):
"""
Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples, n_classes]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples, n_classes]
Target scores (estimator p... | python | def _precision_recall_multi(y_true, y_score, ax=None):
"""
Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples, n_classes]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples, n_classes]
Target scores (estimator p... | [
"def",
"_precision_recall_multi",
"(",
"y_true",
",",
"y_score",
",",
"ax",
"=",
"None",
")",
":",
"# Compute micro-average ROC curve and ROC area",
"precision",
",",
"recall",
",",
"_",
"=",
"precision_recall_curve",
"(",
"y_true",
".",
"ravel",
"(",
")",
",",
... | Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples, n_classes]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples, n_classes]
Target scores (estimator predictions).
ax : matplotlib Axes
Axes object to draw t... | [
"Plot",
"precision",
"-",
"recall",
"curve",
"."
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/precision_recall.py#L104-L136 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/metrics.py | precision_at | def precision_at(y_true, y_score, proportion, ignore_nas=False):
'''
Calculates precision at a given proportion.
Only supports binary classification.
'''
# Sort scores in descending order
scores_sorted = np.sort(y_score)[::-1]
# Based on the proportion, get the index to split the data
#... | python | def precision_at(y_true, y_score, proportion, ignore_nas=False):
'''
Calculates precision at a given proportion.
Only supports binary classification.
'''
# Sort scores in descending order
scores_sorted = np.sort(y_score)[::-1]
# Based on the proportion, get the index to split the data
#... | [
"def",
"precision_at",
"(",
"y_true",
",",
"y_score",
",",
"proportion",
",",
"ignore_nas",
"=",
"False",
")",
":",
"# Sort scores in descending order",
"scores_sorted",
"=",
"np",
".",
"sort",
"(",
"y_score",
")",
"[",
":",
":",
"-",
"1",
"]",
"# Based on t... | Calculates precision at a given proportion.
Only supports binary classification. | [
"Calculates",
"precision",
"at",
"a",
"given",
"proportion",
".",
"Only",
"supports",
"binary",
"classification",
"."
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/metrics.py#L7-L29 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/metrics.py | __precision | def __precision(y_true, y_pred):
'''
Precision metric tolerant to unlabeled data in y_true,
NA values are ignored for the precision calculation
'''
# make copies of the arrays to avoid modifying the original ones
y_true = np.copy(y_true)
y_pred = np.copy(y_pred)
# precision = tp... | python | def __precision(y_true, y_pred):
'''
Precision metric tolerant to unlabeled data in y_true,
NA values are ignored for the precision calculation
'''
# make copies of the arrays to avoid modifying the original ones
y_true = np.copy(y_true)
y_pred = np.copy(y_pred)
# precision = tp... | [
"def",
"__precision",
"(",
"y_true",
",",
"y_pred",
")",
":",
"# make copies of the arrays to avoid modifying the original ones",
"y_true",
"=",
"np",
".",
"copy",
"(",
"y_true",
")",
"y_pred",
"=",
"np",
".",
"copy",
"(",
"y_pred",
")",
"# precision = tp/(tp+fp)",
... | Precision metric tolerant to unlabeled data in y_true,
NA values are ignored for the precision calculation | [
"Precision",
"metric",
"tolerant",
"to",
"unlabeled",
"data",
"in",
"y_true",
"NA",
"values",
"are",
"ignored",
"for",
"the",
"precision",
"calculation"
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/metrics.py#L51-L68 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/metrics.py | labels_at | def labels_at(y_true, y_score, proportion, normalize=False):
'''
Return the number of labels encountered in the top X proportion
'''
# Get indexes of scores sorted in descending order
indexes = np.argsort(y_score)[::-1]
# Sort true values in the same order
y_true_sorted = y_true[indexe... | python | def labels_at(y_true, y_score, proportion, normalize=False):
'''
Return the number of labels encountered in the top X proportion
'''
# Get indexes of scores sorted in descending order
indexes = np.argsort(y_score)[::-1]
# Sort true values in the same order
y_true_sorted = y_true[indexe... | [
"def",
"labels_at",
"(",
"y_true",
",",
"y_score",
",",
"proportion",
",",
"normalize",
"=",
"False",
")",
":",
"# Get indexes of scores sorted in descending order",
"indexes",
"=",
"np",
".",
"argsort",
"(",
"y_score",
")",
"[",
":",
":",
"-",
"1",
"]",
"# ... | Return the number of labels encountered in the top X proportion | [
"Return",
"the",
"number",
"of",
"labels",
"encountered",
"in",
"the",
"top",
"X",
"proportion"
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/metrics.py#L100-L122 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/plot/validation_curve.py | validation_curve | def validation_curve(train_scores, test_scores, param_range, param_name=None,
semilogx=False, ax=None):
"""Plot a validation curve
Plot a metric vs hyperpameter values for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training... | python | def validation_curve(train_scores, test_scores, param_range, param_name=None,
semilogx=False, ax=None):
"""Plot a validation curve
Plot a metric vs hyperpameter values for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training... | [
"def",
"validation_curve",
"(",
"train_scores",
",",
"test_scores",
",",
"param_range",
",",
"param_name",
"=",
"None",
",",
"semilogx",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
... | Plot a validation curve
Plot a metric vs hyperpameter values for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training set
test_scores : array-like
Scores for the test set
param_range : array-like
Hyperparameter values used to... | [
"Plot",
"a",
"validation",
"curve"
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/validation_curve.py#L5-L66 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/plot/classification.py | confusion_matrix | def confusion_matrix(y_true, y_pred, target_names=None, normalize=False,
cmap=None, ax=None):
"""
Plot confustion matrix.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_pred : array-like, shape = [n_samples]
... | python | def confusion_matrix(y_true, y_pred, target_names=None, normalize=False,
cmap=None, ax=None):
"""
Plot confustion matrix.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_pred : array-like, shape = [n_samples]
... | [
"def",
"confusion_matrix",
"(",
"y_true",
",",
"y_pred",
",",
"target_names",
"=",
"None",
",",
"normalize",
"=",
"False",
",",
"cmap",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"if",
"any",
"(",
"(",
"val",
"is",
"None",
"for",
"val",
"in",
"... | Plot confustion matrix.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_pred : array-like, shape = [n_samples]
Target predicted classes (estimator predictions).
target_names : list
List containing the names of the target... | [
"Plot",
"confustion",
"matrix",
"."
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/classification.py#L13-L105 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/plot/classification.py | feature_importances | def feature_importances(data, top_n=None, feature_names=None, ax=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure. If data is a scikit-learn model with
sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the
standard deviation ... | python | def feature_importances(data, top_n=None, feature_names=None, ax=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure. If data is a scikit-learn model with
sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the
standard deviation ... | [
"def",
"feature_importances",
"(",
"data",
",",
"top_n",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'data is needed to plot feature importances. '",
"'When plott... | Get and order feature importances from a scikit-learn model
or from an array-like structure. If data is a scikit-learn model with
sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the
standard deviation of each feature.
Parameters
----------
data : sklearn model or array-li... | [
"Get",
"and",
"order",
"feature",
"importances",
"from",
"a",
"scikit",
"-",
"learn",
"model",
"or",
"from",
"an",
"array",
"-",
"like",
"structure",
".",
"If",
"data",
"is",
"a",
"scikit",
"-",
"learn",
"model",
"with",
"sub",
"-",
"estimators",
"(",
... | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/classification.py#L113-L166 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/plot/classification.py | precision_at_proportions | def precision_at_proportions(y_true, y_score, ax=None):
"""
Plot precision values at different proportions.
Parameters
----------
y_true : array-like
Correct target values (ground truth).
y_score : array-like
Target scores (estimator predictions).
ax : matplotlib Axes
... | python | def precision_at_proportions(y_true, y_score, ax=None):
"""
Plot precision values at different proportions.
Parameters
----------
y_true : array-like
Correct target values (ground truth).
y_score : array-like
Target scores (estimator predictions).
ax : matplotlib Axes
... | [
"def",
"precision_at_proportions",
"(",
"y_true",
",",
"y_score",
",",
"ax",
"=",
"None",
")",
":",
"if",
"any",
"(",
"(",
"val",
"is",
"None",
"for",
"val",
"in",
"(",
"y_true",
",",
"y_score",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"'y_tru... | Plot precision values at different proportions.
Parameters
----------
y_true : array-like
Correct target values (ground truth).
y_score : array-like
Target scores (estimator predictions).
ax : matplotlib Axes
Axes object to draw the plot onto, otherwise uses current Axes
... | [
"Plot",
"precision",
"values",
"at",
"different",
"proportions",
"."
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/classification.py#L169-L216 | train |
edublancas/sklearn-evaluation | sklearn_evaluation/table.py | feature_importances | def feature_importances(data, top_n=None, feature_names=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure.
If data is a scikit-learn model with sub-estimators (e.g. RandomForest,
AdaBoost) the function will compute the standard deviation of each
... | python | def feature_importances(data, top_n=None, feature_names=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure.
If data is a scikit-learn model with sub-estimators (e.g. RandomForest,
AdaBoost) the function will compute the standard deviation of each
... | [
"def",
"feature_importances",
"(",
"data",
",",
"top_n",
"=",
"None",
",",
"feature_names",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'data is needed to tabulate feature importances. '",
"'When plotting using the evaluator you ... | Get and order feature importances from a scikit-learn model
or from an array-like structure.
If data is a scikit-learn model with sub-estimators (e.g. RandomForest,
AdaBoost) the function will compute the standard deviation of each
feature.
Parameters
----------
data : sklearn model or arr... | [
"Get",
"and",
"order",
"feature",
"importances",
"from",
"a",
"scikit",
"-",
"learn",
"model",
"or",
"from",
"an",
"array",
"-",
"like",
"structure",
"."
] | 79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39 | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/table.py#L30-L62 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.