nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
yt/utilities/cosmology.py
python
Cosmology.lookback_time
(self, z_i, z_f)
return (trapzint(self.age_integrand, z_i, z_f) / self.hubble_constant).in_base( self.unit_system )
r""" The difference in the age of the Universe between the redshift interval z_i to z_f. Parameters ---------- z_i : float The lower redshift of the interval. z_f : float The higher redshift of the interval. Examples -------- >>> from yt.utilities.cosmology import Cosmology >>> co = Cosmology() >>> print(co.lookback_time(0.0, 1.0).in_units("Gyr"))
r""" The difference in the age of the Universe between the redshift interval z_i to z_f.
[ "r", "The", "difference", "in", "the", "age", "of", "the", "Universe", "between", "the", "redshift", "interval", "z_i", "to", "z_f", "." ]
def lookback_time(self, z_i, z_f): r""" The difference in the age of the Universe between the redshift interval z_i to z_f. Parameters ---------- z_i : float The lower redshift of the interval. z_f : float The higher redshift of the interval. Examples -------- >>> from yt.utilities.cosmology import Cosmology >>> co = Cosmology() >>> print(co.lookback_time(0.0, 1.0).in_units("Gyr")) """ return (trapzint(self.age_integrand, z_i, z_f) / self.hubble_constant).in_base( self.unit_system )
[ "def", "lookback_time", "(", "self", ",", "z_i", ",", "z_f", ")", ":", "return", "(", "trapzint", "(", "self", ".", "age_integrand", ",", "z_i", ",", "z_f", ")", "/", "self", ".", "hubble_constant", ")", ".", "in_base", "(", "self", ".", "unit_system",...
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/utilities/cosmology.py#L339-L361
getsentry/sentry-python
f92e9707ea73765eb9fdcf6482dc46aed4221a7a
sentry_sdk/integrations/asgi.py
python
_looks_like_asgi3
(app)
Try to figure out if an application object supports ASGI3. This is how uvicorn figures out the application version as well.
Try to figure out if an application object supports ASGI3.
[ "Try", "to", "figure", "out", "if", "an", "application", "object", "supports", "ASGI3", "." ]
def _looks_like_asgi3(app): # type: (Any) -> bool """ Try to figure out if an application object supports ASGI3. This is how uvicorn figures out the application version as well. """ if inspect.isclass(app): return hasattr(app, "__await__") elif inspect.isfunction(app): return asyncio.iscoroutinefunction(app) else: call = getattr(app, "__call__", None) # noqa return asyncio.iscoroutinefunction(call)
[ "def", "_looks_like_asgi3", "(", "app", ")", ":", "# type: (Any) -> bool", "if", "inspect", ".", "isclass", "(", "app", ")", ":", "return", "hasattr", "(", "app", ",", "\"__await__\"", ")", "elif", "inspect", ".", "isfunction", "(", "app", ")", ":", "retur...
https://github.com/getsentry/sentry-python/blob/f92e9707ea73765eb9fdcf6482dc46aed4221a7a/sentry_sdk/integrations/asgi.py#L53-L66
ozak/georasters
6805570b22829e66a41b97c80e72f0510057011d
georasters/georasters.py
python
GeoRaster.max
(self, *args, **kwargs)
return self.raster.max(*args, **kwargs)
geo.max(axis=None, out=None) Return the maximum along a given axis. Refer to `numpy.amax` for full documentation. See Also -------- numpy.amax : equivalent function
geo.max(axis=None, out=None)
[ "geo", ".", "max", "(", "axis", "=", "None", "out", "=", "None", ")" ]
def max(self, *args, **kwargs): ''' geo.max(axis=None, out=None) Return the maximum along a given axis. Refer to `numpy.amax` for full documentation. See Also -------- numpy.amax : equivalent function ''' return self.raster.max(*args, **kwargs)
[ "def", "max", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "raster", ".", "max", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/ozak/georasters/blob/6805570b22829e66a41b97c80e72f0510057011d/georasters/georasters.py#L605-L617
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/corporate_memberships/utils.py
python
get_corporate_membership_type_choices
(user, corpapp, renew=False)
return cmt_list
[]
def get_corporate_membership_type_choices(user, corpapp, renew=False): cmt_list = [] corporate_membership_types = corpapp.corp_memb_type.all() if not user.profile.is_superuser: corporate_membership_types = corporate_membership_types.filter(admin_only=False) corporate_membership_types = corporate_membership_types.order_by('position') currency_symbol = get_setting("site", "global", "currencysymbol") for cmt in corporate_membership_types: if not renew: price_display = '%s - %s%0.2f' % (cmt.name, currency_symbol, cmt.price) else: indiv_renewal_price = cmt.membership_type.renewal_price if not indiv_renewal_price: indiv_renewal_price = 'Free<span class="type-ind-price"></span>' else: indiv_renewal_price = '%s<span class="type-ind-price">%0.2f</span>' % (currency_symbol, indiv_renewal_price) if not cmt.renewal_price: cmt.renewal_price = 0 price_display = """%s - <b>%s<span class="type-corp-price">%0.2f</span></b> (individual members renewal: <b>%s</b>)""" % (cmt.name, currency_symbol, cmt.renewal_price, indiv_renewal_price) price_display = mark_safe(price_display) cmt_list.append((cmt.id, price_display)) return cmt_list
[ "def", "get_corporate_membership_type_choices", "(", "user", ",", "corpapp", ",", "renew", "=", "False", ")", ":", "cmt_list", "=", "[", "]", "corporate_membership_types", "=", "corpapp", ".", "corp_memb_type", ".", "all", "(", ")", "if", "not", "user", ".", ...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/corporate_memberships/utils.py#L422-L452
sdaps/sdaps
51d1072185223f5e48512661e2c1e8399d63e876
sdaps/report/flowables.py
python
Box.__init__
(self, a, b, c, margin=0)
[]
def __init__(self, a, b, c, margin=0): platypus.Flowable.__init__(self) self.a = float(a) self.b = float(b) self.c = float(c) self.margin = float(margin) self.alpha = 1.0 / 3.0 * math.pi self.cx = math.sin(self.alpha) * self.c self.cy = math.cos(self.alpha) * self.c self.fill = 0 self.transparent = 1 self.fill_color = (255, 255, 255)
[ "def", "__init__", "(", "self", ",", "a", ",", "b", ",", "c", ",", "margin", "=", "0", ")", ":", "platypus", ".", "Flowable", ".", "__init__", "(", "self", ")", "self", ".", "a", "=", "float", "(", "a", ")", "self", ".", "b", "=", "float", "(...
https://github.com/sdaps/sdaps/blob/51d1072185223f5e48512661e2c1e8399d63e876/sdaps/report/flowables.py#L46-L57
zalando-incubator/kopf
4843d84a5883c28be9b25024e795fba1bae99a35
kopf/structs/containers.py
python
ResourceMemories.recall
( self, raw_body: bodies.RawBody, *, noticed_by_listing: bool = False, )
return self._items[key]
Either find a resource's memory, or create and remember a new one. Keep the last-seen body up to date for all the handlers.
Either find a resource's memory, or create and remember a new one.
[ "Either", "find", "a", "resource", "s", "memory", "or", "create", "and", "remember", "a", "new", "one", "." ]
async def recall( self, raw_body: bodies.RawBody, *, noticed_by_listing: bool = False, ) -> ResourceMemory: """ Either find a resource's memory, or create and remember a new one. Keep the last-seen body up to date for all the handlers. """ key = self._build_key(raw_body) if key not in self._items: memory = ResourceMemory(noticed_by_listing=noticed_by_listing) self._items[key] = memory return self._items[key]
[ "async", "def", "recall", "(", "self", ",", "raw_body", ":", "bodies", ".", "RawBody", ",", "*", ",", "noticed_by_listing", ":", "bool", "=", "False", ",", ")", "->", "ResourceMemory", ":", "key", "=", "self", ".", "_build_key", "(", "raw_body", ")", "...
https://github.com/zalando-incubator/kopf/blob/4843d84a5883c28be9b25024e795fba1bae99a35/kopf/structs/containers.py#L102-L117
renerocksai/sublime_zk
f8336c167546bf609d0abc998fc7364795beb18e
sublime_zk.py
python
ZkFollowWikiLinkCommand.select_link
(self, event=None)
return
Select a note-link under the cursor. If it's a tag, follow it by searching for tagged notes. Search: * via find-in-files if ag is not found * results in external search results file if enabled * else present overlay to pick a note
Select a note-link under the cursor. If it's a tag, follow it by searching for tagged notes. Search: * via find-in-files if ag is not found * results in external search results file if enabled * else present overlay to pick a note
[ "Select", "a", "note", "-", "link", "under", "the", "cursor", ".", "If", "it", "s", "a", "tag", "follow", "it", "by", "searching", "for", "tagged", "notes", ".", "Search", ":", "*", "via", "find", "-", "in", "-", "files", "if", "ag", "is", "not", ...
def select_link(self, event=None): """ Select a note-link under the cursor. If it's a tag, follow it by searching for tagged notes. Search: * via find-in-files if ag is not found * results in external search results file if enabled * else present overlay to pick a note """ global F_EXT_SEARCH global PANE_FOR_OPENING_RESULTS linestart_till_cursor_str, link_region = select_link_in( self.view, event) link_text = '' link_is_citekey = False if link_region: link_text = self.view.substr(link_region) link_is_citekey = link_text.startswith( '@') or link_text.startswith('#') if not link_is_citekey: return link_region # test if we are supposed to follow a tag if ZkConstants.TAG_PREFIX in linestart_till_cursor_str or '@' in linestart_till_cursor_str: view = self.view if event is None: region = self.view.sel()[0] cursor_pos = region.begin() else: cursor_pos = self.view.window_to_text((event['x'], event['y'])) line_region = view.line(cursor_pos) line_start = line_region.begin() full_line = view.substr(line_region) cursor_pos_in_line = cursor_pos - line_start tag, (begin, end) = tag_at(full_line, cursor_pos_in_line) if not tag: tag, (begin, end) = pandoc_citekey_at( full_line, cursor_pos_in_line) if not tag: return settings = get_settings() if F_EXT_SEARCH: extension = settings.get('wiki_extension') folder = get_path_for(self.view) if not folder: return self.folder = folder self.tagged_note_files = ExternalSearch.search_tagged_notes( folder, extension, tag) if ExternalSearch.EXTERNALIZE: n = self.view.window().open_file(ExternalSearch.external_file( folder)) self.view.window().set_view_index(n, PANE_FOR_OPENING_RESULTS, 0) else: self.tagged_note_files = [os.path.basename(f) for f in self.tagged_note_files] self.view.window().show_quick_panel(self.tagged_note_files, self.on_done) else: new_tab = settings.get('show_search_results_in_new_tab') # hack for the find in files panel: select tag in view, copy it selection = self.view.sel() selection.clear() line_region = sublime.Region( line_start + begin, line_start + end) selection.add(line_region) self.view.window().run_command("copy") self.view.window().run_command("show_panel", {"panel": "find_in_files", "where": get_path_for(self.view), "use_buffer": new_tab, }) # now paste the tag --> it will land in the "find" field self.view.window().run_command("paste") return
[ "def", "select_link", "(", "self", ",", "event", "=", "None", ")", ":", "global", "F_EXT_SEARCH", "global", "PANE_FOR_OPENING_RESULTS", "linestart_till_cursor_str", ",", "link_region", "=", "select_link_in", "(", "self", ".", "view", ",", "event", ")", "link_text"...
https://github.com/renerocksai/sublime_zk/blob/f8336c167546bf609d0abc998fc7364795beb18e/sublime_zk.py#L1475-L1553
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/gzip.py
python
GzipFile.writable
(self)
return self.mode == WRITE
[]
def writable(self): return self.mode == WRITE
[ "def", "writable", "(", "self", ")", ":", "return", "self", ".", "mode", "==", "WRITE" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/gzip.py#L549-L550
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/graphviz/libOuiParse.py
python
macOUI_lookup.lookup_company
(self,companyLst)
return oui
look up a company name and return their OUI's
look up a company name and return their OUI's
[ "look", "up", "a", "company", "name", "and", "return", "their", "OUI", "s" ]
def lookup_company(self,companyLst): """ look up a company name and return their OUI's """ oui = [] if type(companyLst).__name__ == "list": for name in companyLst: compMatch = re.compile(name,re.I) if self.company_oui.has_key(name): oui.extend(self.company_oui[name]) else: for key in self.company_oui: if compMatch.search(key) is not None: oui.extend(self.company_oui[key]) elif type(companyLst).__name__ == "str": if self.company_oui.has_key(companyLst): oui = self.company_oui[companyLst] else: compMatch = re.compile(companyLst,re.I) for key in self.company_oui: if compMatch.search(key) is not None: oui.extend(self.company_oui[key]) #return the oui for that key return oui
[ "def", "lookup_company", "(", "self", ",", "companyLst", ")", ":", "oui", "=", "[", "]", "if", "type", "(", "companyLst", ")", ".", "__name__", "==", "\"list\"", ":", "for", "name", "in", "companyLst", ":", "compMatch", "=", "re", ".", "compile", "(", ...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/graphviz/libOuiParse.py#L91-L115
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractIndonesianoveltranslatorBlogspotCom.py
python
extractIndonesianoveltranslatorBlogspotCom
(item)
return False
Parser for 'indonesianoveltranslator.blogspot.com'
Parser for 'indonesianoveltranslator.blogspot.com'
[ "Parser", "for", "indonesianoveltranslator", ".", "blogspot", ".", "com" ]
def extractIndonesianoveltranslatorBlogspotCom(item): ''' Parser for 'indonesianoveltranslator.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('the telltaler', 'The Telltaler', 'translated'), ('i am no king', 'I am No King', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractIndonesianoveltranslatorBlogspotCom", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"pr...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractIndonesianoveltranslatorBlogspotCom.py#L1-L22
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py
python
TaskAgentClient.get_agent_clouds
(self)
return self._deserialize('[TaskAgentCloud]', self._unwrap_collection(response))
GetAgentClouds. [Preview API] :rtype: [TaskAgentCloud]
GetAgentClouds. [Preview API] :rtype: [TaskAgentCloud]
[ "GetAgentClouds", ".", "[", "Preview", "API", "]", ":", "rtype", ":", "[", "TaskAgentCloud", "]" ]
def get_agent_clouds(self): """GetAgentClouds. [Preview API] :rtype: [TaskAgentCloud] """ response = self._send(http_method='GET', location_id='bfa72b3d-0fc6-43fb-932b-a7f6559f93b9', version='5.1-preview.1') return self._deserialize('[TaskAgentCloud]', self._unwrap_collection(response))
[ "def", "get_agent_clouds", "(", "self", ")", ":", "response", "=", "self", ".", "_send", "(", "http_method", "=", "'GET'", ",", "location_id", "=", "'bfa72b3d-0fc6-43fb-932b-a7f6559f93b9'", ",", "version", "=", "'5.1-preview.1'", ")", "return", "self", ".", "_de...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py#L71-L79
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/np/npyfuncs.py
python
np_real_exp2_impl
(context, builder, sig, args)
return _dispatch_func_by_name_type(context, builder, sig, args, dispatch_table, 'exp2')
[]
def np_real_exp2_impl(context, builder, sig, args): _check_arity_and_homogeneity(sig, args, 1) dispatch_table = { types.float32: 'npy_exp2f', types.float64: 'npy_exp2', } return _dispatch_func_by_name_type(context, builder, sig, args, dispatch_table, 'exp2')
[ "def", "np_real_exp2_impl", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "_check_arity_and_homogeneity", "(", "sig", ",", "args", ",", "1", ")", "dispatch_table", "=", "{", "types", ".", "float32", ":", "'npy_exp2f'", ",", "types", "....
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/np/npyfuncs.py#L599-L608
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/lib/pyxmpp/jabber/vcard.py
python
VCard.__from_xml
(self,data)
Initialize a VCard object from XML node. :Parameters: - `data`: vcard to parse. :Types: - `data`: `libxml2.xmlNode`
Initialize a VCard object from XML node.
[ "Initialize", "a", "VCard", "object", "from", "XML", "node", "." ]
def __from_xml(self,data): """Initialize a VCard object from XML node. :Parameters: - `data`: vcard to parse. :Types: - `data`: `libxml2.xmlNode`""" ns=get_node_ns(data) if ns and ns.getContent()!=VCARD_NS: raise ValueError, "Not in the %r namespace" % (VCARD_NS,) if data.name.lower()!="vCard".lower(): raise ValueError, "Bad root element name: %r" % (data.name,) n=data.children dns=get_node_ns(data) while n: if n.type!='element': n=n.next continue ns=get_node_ns(n) if (ns and dns and ns.getContent()!=dns.getContent()): n=n.next continue if not self.components.has_key(n.name): n=n.next continue cl,tp=self.components[n.name] if tp in ("required","optional"): if self.content.has_key(n.name): raise ValueError,"Duplicate %s" % (n.name,) try: self.content[n.name]=cl(n.name,n) except Empty: pass elif tp=="multi": if not self.content.has_key(n.name): self.content[n.name]=[] try: self.content[n.name].append(cl(n.name,n)) except Empty: pass n=n.next
[ "def", "__from_xml", "(", "self", ",", "data", ")", ":", "ns", "=", "get_node_ns", "(", "data", ")", "if", "ns", "and", "ns", ".", "getContent", "(", ")", "!=", "VCARD_NS", ":", "raise", "ValueError", ",", "\"Not in the %r namespace\"", "%", "(", "VCARD_...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/lib/pyxmpp/jabber/vcard.py#L1417-L1457
oddt/oddt
8cf555820d97a692ade81c101ebe10e28bcb3722
oddt/toolkits/extras/rdkit/fixer.py
python
SimplifyMol
(mol)
return mol
Change all bonds to single and discharge/dearomatize all atoms. The molecule is modified in-place (no copy is made).
Change all bonds to single and discharge/dearomatize all atoms. The molecule is modified in-place (no copy is made).
[ "Change", "all", "bonds", "to", "single", "and", "discharge", "/", "dearomatize", "all", "atoms", ".", "The", "molecule", "is", "modified", "in", "-", "place", "(", "no", "copy", "is", "made", ")", "." ]
def SimplifyMol(mol): """Change all bonds to single and discharge/dearomatize all atoms. The molecule is modified in-place (no copy is made). """ for b in mol.GetBonds(): b.SetBondType(Chem.BondType.SINGLE) b.SetIsAromatic(False) for a in mol.GetAtoms(): a.SetFormalCharge(0) a.SetIsAromatic(False) return mol
[ "def", "SimplifyMol", "(", "mol", ")", ":", "for", "b", "in", "mol", ".", "GetBonds", "(", ")", ":", "b", ".", "SetBondType", "(", "Chem", ".", "BondType", ".", "SINGLE", ")", "b", ".", "SetIsAromatic", "(", "False", ")", "for", "a", "in", "mol", ...
https://github.com/oddt/oddt/blob/8cf555820d97a692ade81c101ebe10e28bcb3722/oddt/toolkits/extras/rdkit/fixer.py#L73-L83
tdamdouni/Pythonista
3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad
_2016/mysql-connector-pythonista/utils.py
python
read_lc_string_list
(buf)
return tuple(strlst)
Reads all length encoded strings from the given buffer Returns a list of strings
Reads all length encoded strings from the given buffer Returns a list of strings
[ "Reads", "all", "length", "encoded", "strings", "from", "the", "given", "buffer", "Returns", "a", "list", "of", "strings" ]
def read_lc_string_list(buf): """Reads all length encoded strings from the given buffer Returns a list of strings """ strlst = [] while buf: if buf[0] == '\xfb': # NULL value strlst.append(None) buf = buf[1:] continue l = lsize = 0 fst = ord(buf[0]) if fst <= 250: l = fst strlst.append(buf[1:l+1]) buf = buf[1+l:] continue elif fst == 252: lsize = 2 elif fst == 253: lsize = 3 if fst == 254: lsize = 8 l = intread(buf[1:lsize+1]) strlst.append(buf[lsize+1:l+lsize+1]) buf = buf[lsize+l+1:] return tuple(strlst)
[ "def", "read_lc_string_list", "(", "buf", ")", ":", "strlst", "=", "[", "]", "while", "buf", ":", "if", "buf", "[", "0", "]", "==", "'\\xfb'", ":", "# NULL value", "strlst", ".", "append", "(", "None", ")", "buf", "=", "buf", "[", "1", ":", "]", ...
https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/_2016/mysql-connector-pythonista/utils.py#L189-L222
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/encodings/utf_7.py
python
IncrementalEncoder.encode
(self, input, final=False)
return codecs.utf_7_encode(input, self.errors)[0]
[]
def encode(self, input, final=False): return codecs.utf_7_encode(input, self.errors)[0]
[ "def", "encode", "(", "self", ",", "input", ",", "final", "=", "False", ")", ":", "return", "codecs", ".", "utf_7_encode", "(", "input", ",", "self", ".", "errors", ")", "[", "0", "]" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/encodings/utf_7.py#L15-L16
recruit-tech/summpy
b246bd111aa10a8ea11a0aff8c9fce891f52cc58
summpy/tools.py
python
tree_encode
(obj, encoding='utf-8')
[]
def tree_encode(obj, encoding='utf-8'): type_ = type(obj) if type_ == list or type_ == tuple: return [tree_encode(e, encoding) for e in obj] elif type_ == dict: new_obj = dict( (tree_encode(k, encoding), tree_encode(v, encoding)) for k, v in obj.iteritems() ) return new_obj elif type_ == unicode: return obj.encode(encoding) else: return obj
[ "def", "tree_encode", "(", "obj", ",", "encoding", "=", "'utf-8'", ")", ":", "type_", "=", "type", "(", "obj", ")", "if", "type_", "==", "list", "or", "type_", "==", "tuple", ":", "return", "[", "tree_encode", "(", "e", ",", "encoding", ")", "for", ...
https://github.com/recruit-tech/summpy/blob/b246bd111aa10a8ea11a0aff8c9fce891f52cc58/summpy/tools.py#L9-L22
calebstewart/pwncat
d67865bdaac60dd0761d0698062e7b443a62c6db
pwncat/platform/__init__.py
python
Path.is_mount
(self)
return False
Returns True if the path is a mount point.
Returns True if the path is a mount point.
[ "Returns", "True", "if", "the", "path", "is", "a", "mount", "point", "." ]
def is_mount(self) -> bool: """Returns True if the path is a mount point.""" if str(self) == "/": return True if self.parent.stat().st_dev != self.stat().st_dev: return True return False
[ "def", "is_mount", "(", "self", ")", "->", "bool", ":", "if", "str", "(", "self", ")", "==", "\"/\"", ":", "return", "True", "if", "self", ".", "parent", ".", "stat", "(", ")", ".", "st_dev", "!=", "self", ".", "stat", "(", ")", ".", "st_dev", ...
https://github.com/calebstewart/pwncat/blob/d67865bdaac60dd0761d0698062e7b443a62c6db/pwncat/platform/__init__.py#L201-L210
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/mailbox.py
python
MHMessage._explain_to
(self, message)
Copy MH-specific state to message insofar as possible.
Copy MH-specific state to message insofar as possible.
[ "Copy", "MH", "-", "specific", "state", "to", "message", "insofar", "as", "possible", "." ]
def _explain_to(self, message): """Copy MH-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): sequences = set(self.get_sequences()) if 'unseen' in sequences: message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if 'flagged' in sequences: message.add_flag('F') if 'replied' in sequences: message.add_flag('R') elif isinstance(message, _mboxMMDFMessage): sequences = set(self.get_sequences()) if 'unseen' not in sequences: message.add_flag('RO') else: message.add_flag('O') if 'flagged' in sequences: message.add_flag('F') if 'replied' in sequences: message.add_flag('A') elif isinstance(message, MHMessage): for sequence in self.get_sequences(): message.add_sequence(sequence) elif isinstance(message, BabylMessage): sequences = set(self.get_sequences()) if 'unseen' in sequences: message.add_label('unseen') if 'replied' in sequences: message.add_label('answered') elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message))
[ "def", "_explain_to", "(", "self", ",", "message", ")", ":", "if", "isinstance", "(", "message", ",", "MaildirMessage", ")", ":", "sequences", "=", "set", "(", "self", ".", "get_sequences", "(", ")", ")", "if", "'unseen'", "in", "sequences", ":", "messag...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/mailbox.py#L1782-L1818
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/ipaddr/ipaddr/__init__.py
python
_count_righthand_zero_bits
(number, bits)
Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number.
Count the number of zero bits on the right hand side.
[ "Count", "the", "number", "of", "zero", "bits", "on", "the", "right", "hand", "side", "." ]
def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits for i in range(bits): if (number >> i) % 2: return i
[ "def", "_count_righthand_zero_bits", "(", "number", ",", "bits", ")", ":", "if", "number", "==", "0", ":", "return", "bits", "for", "i", "in", "range", "(", "bits", ")", ":", "if", "(", "number", ">>", "i", ")", "%", "2", ":", "return", "i" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/ipaddr/ipaddr/__init__.py#L187-L202
DigitalSlideArchive/HistomicsTK
db2ceb4831bec0efa557cf5b18078ae790253de5
histomicstk/features/compute_intensity_features.py
python
compute_intensity_features
( im_label, im_intensity, num_hist_bins=10, rprops=None, feature_list=None)
return fdata
Calculate intensity features from an intensity image. Parameters ---------- im_label : array_like A labeled mask image wherein intensity of a pixel is the ID of the object it belongs to. Non-zero values are considered to be foreground objects. im_intensity : array_like Intensity image. num_hist_bins: int, optional Number of bins used to computed the intensity histogram of an object. Histogram is used to energy and entropy features. Default is 10. rprops : output of skimage.measure.regionprops, optional rprops = skimage.measure.regionprops( im_label ). If rprops is not passed then it will be computed inside which will increase the computation time. feature_list : list, default is None list of intensity features to return. If none, all intensity features are returned. Returns ------- fdata: pandas.DataFrame A pandas dataframe containing the intensity features listed below for each object/label. Notes ----- List of intensity features computed by this function: Intensity.Min : float Minimum intensity of object pixels. Intensity.Max : float Maximum intensity of object pixels. Intensity.Mean : float Mean intensity of object pixels Intensity.Median : float Median intensity of object pixels Intensity.MeanMedianDiff : float Difference between mean and median intensities of object pixels. Intensity.Std : float Standard deviation of the intensities of object pixels Intensity.IQR: float Inter-quartile range of the intensities of object pixels Intensity.MAD: float Median absolute deviation of the intensities of object pixels Intensity.Skewness : float Skewness of the intensities of object pixels. Value is 0 when all intensity values are equal. Intensity.Kurtosis : float Kurtosis of the intensities of object pixels. Value is -3 when all values are equal. Intensity.HistEnergy : float Energy of the intensity histogram of object pixels Intensity.HistEntropy : float Entropy of the intensity histogram of object pixels. References ---------- .. [#] Daniel Zwillinger and Stephen Kokoska. "CRC standard probability and statistics tables and formulae," Crc Press, 1999.
Calculate intensity features from an intensity image.
[ "Calculate", "intensity", "features", "from", "an", "intensity", "image", "." ]
def compute_intensity_features( im_label, im_intensity, num_hist_bins=10, rprops=None, feature_list=None): """Calculate intensity features from an intensity image. Parameters ---------- im_label : array_like A labeled mask image wherein intensity of a pixel is the ID of the object it belongs to. Non-zero values are considered to be foreground objects. im_intensity : array_like Intensity image. num_hist_bins: int, optional Number of bins used to computed the intensity histogram of an object. Histogram is used to energy and entropy features. Default is 10. rprops : output of skimage.measure.regionprops, optional rprops = skimage.measure.regionprops( im_label ). If rprops is not passed then it will be computed inside which will increase the computation time. feature_list : list, default is None list of intensity features to return. If none, all intensity features are returned. Returns ------- fdata: pandas.DataFrame A pandas dataframe containing the intensity features listed below for each object/label. Notes ----- List of intensity features computed by this function: Intensity.Min : float Minimum intensity of object pixels. Intensity.Max : float Maximum intensity of object pixels. Intensity.Mean : float Mean intensity of object pixels Intensity.Median : float Median intensity of object pixels Intensity.MeanMedianDiff : float Difference between mean and median intensities of object pixels. Intensity.Std : float Standard deviation of the intensities of object pixels Intensity.IQR: float Inter-quartile range of the intensities of object pixels Intensity.MAD: float Median absolute deviation of the intensities of object pixels Intensity.Skewness : float Skewness of the intensities of object pixels. Value is 0 when all intensity values are equal. Intensity.Kurtosis : float Kurtosis of the intensities of object pixels. Value is -3 when all values are equal. Intensity.HistEnergy : float Energy of the intensity histogram of object pixels Intensity.HistEntropy : float Entropy of the intensity histogram of object pixels. References ---------- .. [#] Daniel Zwillinger and Stephen Kokoska. "CRC standard probability and statistics tables and formulae," Crc Press, 1999. """ default_feature_list = [ 'Intensity.Min', 'Intensity.Max', 'Intensity.Mean', 'Intensity.Median', 'Intensity.MeanMedianDiff', 'Intensity.Std', 'Intensity.IQR', 'Intensity.MAD', 'Intensity.Skewness', 'Intensity.Kurtosis', 'Intensity.HistEnergy', 'Intensity.HistEntropy', ] # List of feature names if feature_list is None: feature_list = default_feature_list else: assert all(j in default_feature_list for j in feature_list), \ "Some feature names are not recognized." # compute object properties if not provided if rprops is None: rprops = regionprops(im_label) # create pandas data frame containing the features for each object numFeatures = len(feature_list) numLabels = len(rprops) fdata = pd.DataFrame(np.zeros((numLabels, numFeatures)), columns=feature_list) # conditionally execute calculations if x in the features list def _conditional_execution(feature, func, *args, **kwargs): if feature in feature_list: fdata.at[i, feature] = func(*args, **kwargs) def _return_input(x): return x for i in range(numLabels): # get intensities of object pixels pixelIntensities = np.sort( im_intensity[rprops[i].coords[:, 0], rprops[i].coords[:, 1]] ) # simple descriptors meanIntensity = np.mean(pixelIntensities) medianIntensity = np.median(pixelIntensities) _conditional_execution('Intensity.Min', np.min, pixelIntensities) _conditional_execution('Intensity.Max', np.max, pixelIntensities) _conditional_execution('Intensity.Mean', _return_input, meanIntensity) _conditional_execution( 'Intensity.Median', _return_input, medianIntensity) _conditional_execution( 'Intensity.MeanMedianDiff', _return_input, meanIntensity - medianIntensity) _conditional_execution('Intensity.Std', np.std, pixelIntensities) _conditional_execution( 'Intensity.Skewness', scipy.stats.skew, pixelIntensities) _conditional_execution( 'Intensity.Kurtosis', scipy.stats.kurtosis, pixelIntensities) # inter-quartile range _conditional_execution( 'Intensity.IQR', scipy.stats.iqr, pixelIntensities) # median absolute deviation _conditional_execution( 'Intensity.MAD', np.median, np.abs(pixelIntensities - medianIntensity)) # histogram-based features if any(j in feature_list for j in [ 'Intensity.HistEntropy', 'Intensity.HistEnergy']): # compute intensity histogram hist, bins = np.histogram(pixelIntensities, bins=num_hist_bins) prob = hist/np.sum(hist, dtype=np.float32) # entropy and energy _conditional_execution( 'Intensity.HistEntropy', scipy.stats.entropy, prob) _conditional_execution('Intensity.HistEnergy', np.sum, prob**2) return fdata
[ "def", "compute_intensity_features", "(", "im_label", ",", "im_intensity", ",", "num_hist_bins", "=", "10", ",", "rprops", "=", "None", ",", "feature_list", "=", "None", ")", ":", "default_feature_list", "=", "[", "'Intensity.Min'", ",", "'Intensity.Max'", ",", ...
https://github.com/DigitalSlideArchive/HistomicsTK/blob/db2ceb4831bec0efa557cf5b18078ae790253de5/histomicstk/features/compute_intensity_features.py#L8-L176
astropy/photutils
3caa48e4e4d139976ed7457dc41583fb2c56ba20
photutils/segmentation/catalog.py
python
SourceCatalog.equivalent_radius
(self)
return np.sqrt(self.area / np.pi)
The radius of a circle with the same `area` as the source segment.
The radius of a circle with the same `area` as the source segment.
[ "The", "radius", "of", "a", "circle", "with", "the", "same", "area", "as", "the", "source", "segment", "." ]
def equivalent_radius(self): """ The radius of a circle with the same `area` as the source segment. """ return np.sqrt(self.area / np.pi)
[ "def", "equivalent_radius", "(", "self", ")", ":", "return", "np", ".", "sqrt", "(", "self", ".", "area", "/", "np", ".", "pi", ")" ]
https://github.com/astropy/photutils/blob/3caa48e4e4d139976ed7457dc41583fb2c56ba20/photutils/segmentation/catalog.py#L1611-L1616
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/index.py
python
HTMLPage.clean_link
(self, url)
return self._clean_re.sub( lambda match: '%%%2x' % ord(match.group(0)), url)
Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).
Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).
[ "Makes", "sure", "a", "link", "is", "fully", "encoded", ".", "That", "is", "if", "a", "shows", "up", "in", "the", "link", "it", "will", "be", "rewritten", "to", "%20", "(", "while", "not", "over", "-", "quoting", "%", "or", "other", "characters", ")"...
def clean_link(self, url): """Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).""" return self._clean_re.sub( lambda match: '%%%2x' % ord(match.group(0)), url)
[ "def", "clean_link", "(", "self", ",", "url", ")", ":", "return", "self", ".", "_clean_re", ".", "sub", "(", "lambda", "match", ":", "'%%%2x'", "%", "ord", "(", "match", ".", "group", "(", "0", ")", ")", ",", "url", ")" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/index.py#L1053-L1058
google/personfinder
475f4c0ce916036d39bae2d480cde07126550875
app/importer.py
python
create_note
(repo, fields)
Creates a Note entity in the given repository with the given field values. If 'fields' contains a 'note_record_id', calling put() on the resulting entity will overwrite any existing (original or clone) record with the same note_record_id. Otherwise, a new original note record is created in the given repository.
Creates a Note entity in the given repository with the given field values. If 'fields' contains a 'note_record_id', calling put() on the resulting entity will overwrite any existing (original or clone) record with the same note_record_id. Otherwise, a new original note record is created in the given repository.
[ "Creates", "a", "Note", "entity", "in", "the", "given", "repository", "with", "the", "given", "field", "values", ".", "If", "fields", "contains", "a", "note_record_id", "calling", "put", "()", "on", "the", "resulting", "entity", "will", "overwrite", "any", "...
def create_note(repo, fields): """Creates a Note entity in the given repository with the given field values. If 'fields' contains a 'note_record_id', calling put() on the resulting entity will overwrite any existing (original or clone) record with the same note_record_id. Otherwise, a new original note record is created in the given repository.""" assert strip(fields.get('person_record_id')), 'person_record_id is required' assert strip(fields.get('source_date')), 'source_date is required' note_fields = dict( person_record_id=strip(fields['person_record_id']), linked_person_record_id=strip(fields.get('linked_person_record_id')), author_name=strip(fields.get('author_name')), author_email=strip(fields.get('author_email')), author_phone=strip(fields.get('author_phone')), source_date=validate_datetime(fields.get('source_date')), status=validate_status(fields.get('status')), author_made_contact=validate_boolean(fields.get('author_made_contact')), email_of_found_person=strip(fields.get('email_of_found_person')), phone_of_found_person=strip(fields.get('phone_of_found_person')), last_known_location=strip(fields.get('last_known_location')), text=fields.get('text'), photo_url=fields.get('photo_url'), entry_date=get_utcnow(), ) # TODO(liuhsinwen): Separate existed and non-existed record id and # increment note counter for new records record_id = strip(fields.get('note_record_id')) if record_id: # create a record that might overwrite an existing one if is_clone(repo, record_id): return Note.create_clone(repo, record_id, **note_fields) else: return Note.create_original_with_record_id( repo, record_id, **note_fields) else: # create a new original record # TODO(liuhsinwen): fix performance problem by incrementing the counter # by the number of upload notes # UsageCounter.increment_note_counter(repo) return Note.create_original(repo, **note_fields)
[ "def", "create_note", "(", "repo", ",", "fields", ")", ":", "assert", "strip", "(", "fields", ".", "get", "(", "'person_record_id'", ")", ")", ",", "'person_record_id is required'", "assert", "strip", "(", "fields", ".", "get", "(", "'source_date'", ")", ")"...
https://github.com/google/personfinder/blob/475f4c0ce916036d39bae2d480cde07126550875/app/importer.py#L142-L179
zopefoundation/Zope
ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb
src/Products/PageTemplates/expression.py
python
TrustedBoboAwareZopeTraverse.__call__
(self, base, econtext, call, path_items)
return base
[]
def __call__(self, base, econtext, call, path_items): request = econtext.get('request') base = self.traverse(base, request, path_items) if call is False: return base if getattr(base, '__call__', _marker) is not _marker or \ isinstance(base, type): return base() return base
[ "def", "__call__", "(", "self", ",", "base", ",", "econtext", ",", "call", ",", "path_items", ")", ":", "request", "=", "econtext", ".", "get", "(", "'request'", ")", "base", "=", "self", ".", "traverse", "(", "base", ",", "request", ",", "path_items",...
https://github.com/zopefoundation/Zope/blob/ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb/src/Products/PageTemplates/expression.py#L128-L140
convexengineering/gpkit
3d4dd34ba4e95f1fe58fe9ea45401a6ff2fde1fa
gpkit/solvers/mosek_cli.py
python
remove_read_only
(func, path, exc)
If we can't remove a file/directory, change permissions and try again.
If we can't remove a file/directory, change permissions and try again.
[ "If", "we", "can", "t", "remove", "a", "file", "/", "directory", "change", "permissions", "and", "try", "again", "." ]
def remove_read_only(func, path, exc): # pragma: no cover "If we can't remove a file/directory, change permissions and try again." if func in (os.rmdir, os.remove) and exc[1].errno == errno.EACCES: # change the file to be readable,writable,executable: 0777 os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) func(path)
[ "def", "remove_read_only", "(", "func", ",", "path", ",", "exc", ")", ":", "# pragma: no cover", "if", "func", "in", "(", "os", ".", "rmdir", ",", "os", ".", "remove", ")", "and", "exc", "[", "1", "]", ".", "errno", "==", "errno", ".", "EACCES", ":...
https://github.com/convexengineering/gpkit/blob/3d4dd34ba4e95f1fe58fe9ea45401a6ff2fde1fa/gpkit/solvers/mosek_cli.py#L18-L23
giswqs/whitebox-python
b4df0bbb10a1dee3bd0f6b3482511f7c829b38fe
whitebox/whitebox_tools.py
python
WhiteboxTools.hydrologic_connectivity
(self, dem, output1, output2, exponent=1.0, threshold=None, callback=None)
return self.run_tool('hydrologic_connectivity', args, callback)
This tool evaluates hydrologic connectivity within a DEM. Keyword arguments: dem -- Name of the input DEM raster file; must be depressionless. output1 -- Name of the output downslope unsaturated length (DUL) file. output2 -- Name of the output upslope disconnected saturated area (UDSA) file. exponent -- Optional exponent parameter; default is 1.0. threshold -- Optional convergence threshold parameter, in grid cells; default is inifinity. callback -- Custom function for handling tool text outputs.
This tool evaluates hydrologic connectivity within a DEM.
[ "This", "tool", "evaluates", "hydrologic", "connectivity", "within", "a", "DEM", "." ]
def hydrologic_connectivity(self, dem, output1, output2, exponent=1.0, threshold=None, callback=None): """This tool evaluates hydrologic connectivity within a DEM. Keyword arguments: dem -- Name of the input DEM raster file; must be depressionless. output1 -- Name of the output downslope unsaturated length (DUL) file. output2 -- Name of the output upslope disconnected saturated area (UDSA) file. exponent -- Optional exponent parameter; default is 1.0. threshold -- Optional convergence threshold parameter, in grid cells; default is inifinity. callback -- Custom function for handling tool text outputs. """ args = [] args.append("--dem='{}'".format(dem)) args.append("--output1='{}'".format(output1)) args.append("--output2='{}'".format(output2)) args.append("--exponent={}".format(exponent)) if threshold is not None: args.append("--threshold='{}'".format(threshold)) return self.run_tool('hydrologic_connectivity', args, callback)
[ "def", "hydrologic_connectivity", "(", "self", ",", "dem", ",", "output1", ",", "output2", ",", "exponent", "=", "1.0", ",", "threshold", "=", "None", ",", "callback", "=", "None", ")", ":", "args", "=", "[", "]", "args", ".", "append", "(", "\"--dem='...
https://github.com/giswqs/whitebox-python/blob/b4df0bbb10a1dee3bd0f6b3482511f7c829b38fe/whitebox/whitebox_tools.py#L4503-L4521
landlab/landlab
a5dd80b8ebfd03d1ba87ef6c4368c409485f222c
landlab/components/depression_finder/lake_mapper.py
python
DepressionFinderAndRouter.flood_status
(self)
return self._flood_status
Map of flood status (_PIT, _CURRENT_LAKE, _UNFLOODED, or _FLOODED).
Map of flood status (_PIT, _CURRENT_LAKE, _UNFLOODED, or _FLOODED).
[ "Map", "of", "flood", "status", "(", "_PIT", "_CURRENT_LAKE", "_UNFLOODED", "or", "_FLOODED", ")", "." ]
def flood_status(self): """Map of flood status (_PIT, _CURRENT_LAKE, _UNFLOODED, or _FLOODED).""" return self._flood_status
[ "def", "flood_status", "(", "self", ")", ":", "return", "self", ".", "_flood_status" ]
https://github.com/landlab/landlab/blob/a5dd80b8ebfd03d1ba87ef6c4368c409485f222c/landlab/components/depression_finder/lake_mapper.py#L338-L341
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/tkinter/dnd.py
python
Icon.move
(self, event)
[]
def move(self, event): x, y = self.where(self.canvas, event) self.canvas.coords(self.id, x, y)
[ "def", "move", "(", "self", ",", "event", ")", ":", "x", ",", "y", "=", "self", ".", "where", "(", "self", ".", "canvas", ",", "event", ")", "self", ".", "canvas", ".", "coords", "(", "self", ".", "id", ",", "x", ",", "y", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tkinter/dnd.py#L247-L249
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/utils/feedgenerator.py
python
SyndicationFeed.add_item_elements
(self, handler, item)
Add elements on each item (i.e. item/entry) element.
Add elements on each item (i.e. item/entry) element.
[ "Add", "elements", "on", "each", "item", "(", "i", ".", "e", ".", "item", "/", "entry", ")", "element", "." ]
def add_item_elements(self, handler, item): """ Add elements on each item (i.e. item/entry) element. """ pass
[ "def", "add_item_elements", "(", "self", ",", "handler", ",", "item", ")", ":", "pass" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/utils/feedgenerator.py#L161-L165
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v6_0/gallery/gallery_client.py
python
GalleryClient.unshare_extension
(self, publisher_name, extension_name, account_name)
UnshareExtension. [Preview API] :param str publisher_name: :param str extension_name: :param str account_name:
UnshareExtension. [Preview API] :param str publisher_name: :param str extension_name: :param str account_name:
[ "UnshareExtension", ".", "[", "Preview", "API", "]", ":", "param", "str", "publisher_name", ":", ":", "param", "str", "extension_name", ":", ":", "param", "str", "account_name", ":" ]
def unshare_extension(self, publisher_name, extension_name, account_name): """UnshareExtension. [Preview API] :param str publisher_name: :param str extension_name: :param str account_name: """ route_values = {} if publisher_name is not None: route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str') if extension_name is not None: route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str') if account_name is not None: route_values['accountName'] = self._serialize.url('account_name', account_name, 'str') self._send(http_method='DELETE', location_id='a1e66d8f-f5de-4d16-8309-91a4e015ee46', version='6.0-preview.1', route_values=route_values)
[ "def", "unshare_extension", "(", "self", ",", "publisher_name", ",", "extension_name", ",", "account_name", ")", ":", "route_values", "=", "{", "}", "if", "publisher_name", "is", "not", "None", ":", "route_values", "[", "'publisherName'", "]", "=", "self", "."...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/gallery/gallery_client.py#L79-L96
deepchem/deepchem
054eb4b2b082e3df8e1a8e77f36a52137ae6e375
deepchem/trans/transformers.py
python
LogTransformer.transform_array
( self, X: np.ndarray, y: np.ndarray, w: np.ndarray, ids: np.ndarray)
return (X, y, w, ids)
Transform the data in a set of (X, y, w) arrays. Parameters ---------- X: np.ndarray Array of features y: np.ndarray Array of labels w: np.ndarray Array of weights. ids: np.ndarray Array of weights. Returns ------- Xtrans: np.ndarray Transformed array of features ytrans: np.ndarray Transformed array of labels wtrans: np.ndarray Transformed array of weights idstrans: np.ndarray Transformed array of ids
Transform the data in a set of (X, y, w) arrays.
[ "Transform", "the", "data", "in", "a", "set", "of", "(", "X", "y", "w", ")", "arrays", "." ]
def transform_array( self, X: np.ndarray, y: np.ndarray, w: np.ndarray, ids: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Transform the data in a set of (X, y, w) arrays. Parameters ---------- X: np.ndarray Array of features y: np.ndarray Array of labels w: np.ndarray Array of weights. ids: np.ndarray Array of weights. Returns ------- Xtrans: np.ndarray Transformed array of features ytrans: np.ndarray Transformed array of labels wtrans: np.ndarray Transformed array of weights idstrans: np.ndarray Transformed array of ids """ if self.transform_X: num_features = len(X[0]) if self.features is None: X = np.log(X + 1) else: for j in range(num_features): if j in self.features: X[:, j] = np.log(X[:, j] + 1) else: X[:, j] = X[:, j] if self.transform_y: num_tasks = len(y[0]) if self.tasks is None: y = np.log(y + 1) else: for j in range(num_tasks): if j in self.tasks: y[:, j] = np.log(y[:, j] + 1) else: y[:, j] = y[:, j] return (X, y, w, ids)
[ "def", "transform_array", "(", "self", ",", "X", ":", "np", ".", "ndarray", ",", "y", ":", "np", ".", "ndarray", ",", "w", ":", "np", ".", "ndarray", ",", "ids", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np...
https://github.com/deepchem/deepchem/blob/054eb4b2b082e3df8e1a8e77f36a52137ae6e375/deepchem/trans/transformers.py#L771-L818
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /scripts/sshbackdoors/rpyc/experimental/retunnel.py
python
ReconnectingTunnelStream.close
(self)
[]
def close(self): if self.stream is not None and not self.closed: self.stream.close() self.stream = ClosedFile
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "stream", "is", "not", "None", "and", "not", "self", ".", "closed", ":", "self", ".", "stream", ".", "close", "(", ")", "self", ".", "stream", "=", "ClosedFile" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /scripts/sshbackdoors/rpyc/experimental/retunnel.py#L20-L23
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
is_restype_ptr
(*args)
return _idaapi.is_restype_ptr(*args)
is_restype_ptr(til, type) -> bool
is_restype_ptr(til, type) -> bool
[ "is_restype_ptr", "(", "til", "type", ")", "-", ">", "bool" ]
def is_restype_ptr(*args): """ is_restype_ptr(til, type) -> bool """ return _idaapi.is_restype_ptr(*args)
[ "def", "is_restype_ptr", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "is_restype_ptr", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L28680-L28684
pydata/sparse
a8f5025258189b76d0459134301aa4c494238f98
sparse/_compressed/compressed.py
python
GCXS.maybe_densify
(self, max_size=1000, min_density=0.25)
Converts this :obj:`GCXS` array to a :obj:`numpy.ndarray` if not too costly. Parameters ---------- max_size : int Maximum number of elements in output min_density : float Minimum density of output Returns ------- numpy.ndarray The dense array. See Also -------- sparse.GCXS.todense: Converts to Numpy function without checking the cost. sparse.COO.maybe_densify: The equivalent COO function. Raises ------- ValueError If the returned array would be too large.
Converts this :obj:`GCXS` array to a :obj:`numpy.ndarray` if not too costly. Parameters ---------- max_size : int Maximum number of elements in output min_density : float Minimum density of output Returns ------- numpy.ndarray The dense array. See Also -------- sparse.GCXS.todense: Converts to Numpy function without checking the cost. sparse.COO.maybe_densify: The equivalent COO function. Raises ------- ValueError If the returned array would be too large.
[ "Converts", "this", ":", "obj", ":", "GCXS", "array", "to", "a", ":", "obj", ":", "numpy", ".", "ndarray", "if", "not", "too", "costly", ".", "Parameters", "----------", "max_size", ":", "int", "Maximum", "number", "of", "elements", "in", "output", "min_...
def maybe_densify(self, max_size=1000, min_density=0.25): """ Converts this :obj:`GCXS` array to a :obj:`numpy.ndarray` if not too costly. Parameters ---------- max_size : int Maximum number of elements in output min_density : float Minimum density of output Returns ------- numpy.ndarray The dense array. See Also -------- sparse.GCXS.todense: Converts to Numpy function without checking the cost. sparse.COO.maybe_densify: The equivalent COO function. Raises ------- ValueError If the returned array would be too large. """ if self.size <= max_size or self.density >= min_density: return self.todense() else: raise ValueError( "Operation would require converting " "large sparse array to dense" )
[ "def", "maybe_densify", "(", "self", ",", "max_size", "=", "1000", ",", "min_density", "=", "0.25", ")", ":", "if", "self", ".", "size", "<=", "max_size", "or", "self", ".", "density", ">=", "min_density", ":", "return", "self", ".", "todense", "(", ")...
https://github.com/pydata/sparse/blob/a8f5025258189b76d0459134301aa4c494238f98/sparse/_compressed/compressed.py#L550-L579
eBay/accelerator
218d9a5e4451ac72b9e65df6c5b32e37d25136c8
accelerator/web.py
python
BaseWebHandler._do_req
(self)
[]
def _do_req(self): path = self.path.split("?") cgi_args = {} if len(path) == 2: cgi_args = parse_qs(path[1], keep_blank_values=True) elif len(path) != 1: return self._bad_request() self._do_req2(path[0], cgi_args)
[ "def", "_do_req", "(", "self", ")", ":", "path", "=", "self", ".", "path", ".", "split", "(", "\"?\"", ")", "cgi_args", "=", "{", "}", "if", "len", "(", "path", ")", "==", "2", ":", "cgi_args", "=", "parse_qs", "(", "path", "[", "1", "]", ",", ...
https://github.com/eBay/accelerator/blob/218d9a5e4451ac72b9e65df6c5b32e37d25136c8/accelerator/web.py#L89-L96
adamcharnock/lightbus
5e7069da06cd37a8131e8c592ee957ccb73603d5
lightbus/client/docks/base.py
python
BaseDock.__init__
( self, transport_registry: TransportRegistry, api_registry: ApiRegistry, config: Config, error_queue: ErrorQueueType, consume_from: InternalQueue, produce_to: InternalQueue, )
[]
def __init__( self, transport_registry: TransportRegistry, api_registry: ApiRegistry, config: Config, error_queue: ErrorQueueType, consume_from: InternalQueue, produce_to: InternalQueue, ): self.transport_registry = transport_registry self.api_registry = api_registry self.config = config self.error_queue = error_queue self.producer = InternalProducer(queue=produce_to, error_queue=error_queue) self.consumer = InternalConsumer(queue=consume_from, error_queue=error_queue) self.producer.start() self.consumer.start(self.handle)
[ "def", "__init__", "(", "self", ",", "transport_registry", ":", "TransportRegistry", ",", "api_registry", ":", "ApiRegistry", ",", "config", ":", "Config", ",", "error_queue", ":", "ErrorQueueType", ",", "consume_from", ":", "InternalQueue", ",", "produce_to", ":"...
https://github.com/adamcharnock/lightbus/blob/5e7069da06cd37a8131e8c592ee957ccb73603d5/lightbus/client/docks/base.py#L19-L36
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/datasets/ogb_mag.py
python
OGB_MAG.processed_file_names
(self)
[]
def processed_file_names(self) -> str: if self.preprocess is not None: return f'data_{self.preprocess}.pt' else: return 'data.pt'
[ "def", "processed_file_names", "(", "self", ")", "->", "str", ":", "if", "self", ".", "preprocess", "is", "not", "None", ":", "return", "f'data_{self.preprocess}.pt'", "else", ":", "return", "'data.pt'" ]
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/datasets/ogb_mag.py#L86-L90
Gallopsled/pwntools
1573957cc8b1957399b7cc9bfae0c6f80630d5d4
pwnlib/util/iters.py
python
repeat_func
(func, *args, **kwargs)
repeat_func(func, *args, **kwargs) -> iterator Repeatedly calls `func` with positional arguments `args` and keyword arguments `kwargs`. If no keyword arguments is given the resulting iterator will be computed using only functions from :mod:`itertools` which are very fast. Arguments: func(function): The function to call. args: Positional arguments. kwargs: Keyword arguments. Returns: An iterator whoose elements are the results of calling ``func(*args, **kwargs)`` repeatedly. Examples: >>> def f(x): ... x[0] += 1 ... return x[0] >>> i = repeat_func(f, [0]) >>> take(2, i) [1, 2] >>> take(2, i) [3, 4] >>> def f(**kwargs): ... return kwargs.get('x', 43) >>> i = repeat_func(f, x = 42) >>> take(2, i) [42, 42] >>> i = repeat_func(f, 42) >>> take(2, i) Traceback (most recent call last): ... TypeError: f() takes exactly 0 arguments (1 given)
repeat_func(func, *args, **kwargs) -> iterator
[ "repeat_func", "(", "func", "*", "args", "**", "kwargs", ")", "-", ">", "iterator" ]
def repeat_func(func, *args, **kwargs): """repeat_func(func, *args, **kwargs) -> iterator Repeatedly calls `func` with positional arguments `args` and keyword arguments `kwargs`. If no keyword arguments is given the resulting iterator will be computed using only functions from :mod:`itertools` which are very fast. Arguments: func(function): The function to call. args: Positional arguments. kwargs: Keyword arguments. Returns: An iterator whoose elements are the results of calling ``func(*args, **kwargs)`` repeatedly. Examples: >>> def f(x): ... x[0] += 1 ... return x[0] >>> i = repeat_func(f, [0]) >>> take(2, i) [1, 2] >>> take(2, i) [3, 4] >>> def f(**kwargs): ... return kwargs.get('x', 43) >>> i = repeat_func(f, x = 42) >>> take(2, i) [42, 42] >>> i = repeat_func(f, 42) >>> take(2, i) Traceback (most recent call last): ... TypeError: f() takes exactly 0 arguments (1 given) """ if kwargs: return starmap(lambda args, kwargs: func(*args, **kwargs), repeat((args, kwargs)) ) else: return starmap(func, repeat(args))
[ "def", "repeat_func", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "return", "starmap", "(", "lambda", "args", ",", "kwargs", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ",", "repeat", "(...
https://github.com/Gallopsled/pwntools/blob/1573957cc8b1957399b7cc9bfae0c6f80630d5d4/pwnlib/util/iters.py#L294-L336
NervanaSystems/neon
8c3fb8a93b4a89303467b25817c60536542d08bd
examples/faster-rcnn/objectlocalization.py
python
PASCALVOC
(manifest_file, manifest_root, rois_per_img=256, height=1000, width=1000, inference=False)
return {'manifest_filename': manifest_file, 'manifest_root': manifest_root, 'etl': [image_config, localization_config], 'cache_directory': get_data_cache_or_nothing(subdir='pascalvoc_cache'), 'shuffle_enable': do_transforms, 'shuffle_manifest': do_transforms, 'batch_size': 1, 'block_size': 100, 'augmentation': [augmentation]}
Returns the aeon dataloader configuration for PASCAL VOC dataset.
Returns the aeon dataloader configuration for PASCAL VOC dataset.
[ "Returns", "the", "aeon", "dataloader", "configuration", "for", "PASCAL", "VOC", "dataset", "." ]
def PASCALVOC(manifest_file, manifest_root, rois_per_img=256, height=1000, width=1000, inference=False): """ Returns the aeon dataloader configuration for PASCAL VOC dataset. """ CLASSES = ('__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') # if inference, we do not shuffle or flip do_transforms = not inference image_config = {"type": "image", "height": height, "width": width} localization_config = {"type": "localization_rcnn", "height": height, "width": width, "rois_per_image": rois_per_img, "class_names": CLASSES, "scaling_factor": 1. / 16} augmentation = {"type": "image", "fixed_aspect_ratio": True, "flip_enable": do_transforms, "crop_enable": False} return {'manifest_filename': manifest_file, 'manifest_root': manifest_root, 'etl': [image_config, localization_config], 'cache_directory': get_data_cache_or_nothing(subdir='pascalvoc_cache'), 'shuffle_enable': do_transforms, 'shuffle_manifest': do_transforms, 'batch_size': 1, 'block_size': 100, 'augmentation': [augmentation]}
[ "def", "PASCALVOC", "(", "manifest_file", ",", "manifest_root", ",", "rois_per_img", "=", "256", ",", "height", "=", "1000", ",", "width", "=", "1000", ",", "inference", "=", "False", ")", ":", "CLASSES", "=", "(", "'__background__'", ",", "'aeroplane'", "...
https://github.com/NervanaSystems/neon/blob/8c3fb8a93b4a89303467b25817c60536542d08bd/examples/faster-rcnn/objectlocalization.py#L116-L156
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/multivec/preprocessing/create_training_data.py
python
generate_samples_v2
(queries, passages, neighbors_path, is_training, processor, q_ids, train_eval=False)
Enum. (query, List<passage>, List<passage>, List<label>, List<score>).
Enum. (query, List<passage>, List<passage>, List<label>, List<score>).
[ "Enum", ".", "(", "query", "List<passage", ">", "List<passage", ">", "List<label", ">", "List<score", ">", ")", "." ]
def generate_samples_v2(queries, passages, neighbors_path, is_training, processor, q_ids, train_eval=False): """Enum. (query, List<passage>, List<passage>, List<label>, List<score>).""" n_processed = 0 n_found = 0 seq_qids = set(q_ids) with open(neighbors_path) as fid: neighbors = json.load(fid) for q_id, q_text in queries.items(): # get the retrieved neighbors if q_id not in seq_qids: continue if n_processed % 10000 == 0: print("processed " + str(n_processed) + " found " + str(n_found)) n_processed = n_processed + 1 if not have_neighbors(q_id, neighbors): print("neighbors for " + str(q_id) + " not found.") continue cand_list_ids, cand_list_labels, cand_list_scores, rand_start \ = augmented_neighbors_list( q_id, neighbors, is_training, processor, train_eval=train_eval) # get the text of the neigbors if not cand_list_ids: continue if 1 in cand_list_labels: n_found = n_found + 1 # sub-select positive, negative = sub_select_examples(cand_list_ids, cand_list_labels, cand_list_scores, rand_start, is_training) # get information for the positive passages passage_infos_positive = wrap_with_passage_texts(positive, passages) passage_infos_negative = wrap_with_passage_texts(negative, passages) yield QueryInfo(q_id, q_text), passage_infos_positive, \ passage_infos_negative
[ "def", "generate_samples_v2", "(", "queries", ",", "passages", ",", "neighbors_path", ",", "is_training", ",", "processor", ",", "q_ids", ",", "train_eval", "=", "False", ")", ":", "n_processed", "=", "0", "n_found", "=", "0", "seq_qids", "=", "set", "(", ...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/multivec/preprocessing/create_training_data.py#L271-L315
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_13/ecdsa/util.py
python
sigencode_strings
(r, s, order)
return (r_str, s_str)
[]
def sigencode_strings(r, s, order): r_str = number_to_string(r, order) s_str = number_to_string(s, order) return (r_str, s_str)
[ "def", "sigencode_strings", "(", "r", ",", "s", ",", "order", ")", ":", "r_str", "=", "number_to_string", "(", "r", ",", "order", ")", "s_str", "=", "number_to_string", "(", "s", ",", "order", ")", "return", "(", "r_str", ",", "s_str", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_13/ecdsa/util.py#L186-L189
ArduPilot/pymavlink
9d6ea618e8d0622bee95fa902b6251882e225afb
mavutil.py
python
mavfile.post_message
(self, msg)
default post message call
default post message call
[ "default", "post", "message", "call" ]
def post_message(self, msg): '''default post message call''' if '_posted' in msg.__dict__: return msg._posted = True msg._timestamp = time.time() type = msg.get_type() if 'usec' in msg.__dict__: self.uptime = msg.usec * 1.0e-6 if 'time_boot_ms' in msg.__dict__: self.uptime = msg.time_boot_ms * 1.0e-3 if self._timestamp is not None: if self.notimestamps: msg._timestamp = self.uptime else: msg._timestamp = self._timestamp src_system = msg.get_srcSystem() src_component = msg.get_srcComponent() src_tuple = (src_system, src_component) radio_tuple = (ord('3'), ord('D')) if not src_system in self.sysid_state: # we've seen a new system self.sysid_state[src_system] = mavfile_state() add_message(self.sysid_state[src_system].messages, type, msg) if src_tuple == radio_tuple: # as a special case radio msgs are added for all sysids for s in self.sysid_state.keys(): self.sysid_state[s].messages[type] = msg if not (src_tuple == radio_tuple or msg.get_type() == 'BAD_DATA'): if not src_tuple in self.last_seq: last_seq = -1 else: last_seq = self.last_seq[src_tuple] seq = (last_seq+1) % 256 seq2 = msg.get_seq() if seq != seq2 and last_seq != -1: diff = (seq2 - seq) % 256 self.mav_loss += diff #print("lost %u seq=%u seq2=%u last_seq=%u src_tupe=%s %s" % (diff, seq, seq2, last_seq, str(src_tuple), msg.get_type())) self.last_seq[src_tuple] = seq2 self.mav_count += 1 self.timestamp = msg._timestamp if type == 'HEARTBEAT' and self.probably_vehicle_heartbeat(msg): if self.sysid == 0: # lock onto id tuple of first vehicle heartbeat self.sysid = src_system if float(mavlink.WIRE_PROTOCOL_VERSION) >= 1: self.flightmode = mode_string_v10(msg) self.mav_type = msg.type self.base_mode = msg.base_mode self.sysid_state[self.sysid].armed = (msg.base_mode & mavlink.MAV_MODE_FLAG_SAFETY_ARMED) self.sysid_state[self.sysid].mav_type = msg.type self.sysid_state[self.sysid].mav_autopilot = msg.autopilot elif type == 'PARAM_VALUE': if not src_tuple in self.param_state: self.param_state[src_tuple] = param_state() self.param_state[src_tuple].params[msg.param_id] = msg.param_value elif type == 'SYS_STATUS' and mavlink.WIRE_PROTOCOL_VERSION == '0.9': self.flightmode = mode_string_v09(msg) elif type == 'GPS_RAW': if self.sysid_state[src_system].messages['HOME'].fix_type < 2: self.sysid_state[src_system].messages['HOME'] = msg elif type == 'GPS_RAW_INT': if self.sysid_state[src_system].messages['HOME'].fix_type < 3: self.sysid_state[src_system].messages['HOME'] = msg for hook in self.message_hooks: hook(self, msg) if (msg.get_signed() and self.mav.signing.link_id == 0 and msg.get_link_id() != 0 and self.target_system == msg.get_srcSystem() and self.target_component == msg.get_srcComponent()): # change to link_id from incoming packet self.mav.signing.link_id = msg.get_link_id()
[ "def", "post_message", "(", "self", ",", "msg", ")", ":", "if", "'_posted'", "in", "msg", ".", "__dict__", ":", "return", "msg", ".", "_posted", "=", "True", "msg", ".", "_timestamp", "=", "time", ".", "time", "(", ")", "type", "=", "msg", ".", "ge...
https://github.com/ArduPilot/pymavlink/blob/9d6ea618e8d0622bee95fa902b6251882e225afb/mavutil.py#L345-L429
pythonzm/Ops
e6fdddad2cd6bc697805a2bdba521a26bacada50
projs/utils/svn_tools.py
python
SVNTools.run_cmd
(self, cmds)
return code
以子shell执行命令
以子shell执行命令
[ "以子shell执行命令" ]
def run_cmd(self, cmds): """以子shell执行命令""" c = 'cd {} && '.format(self.proj_path) for cmd in cmds.split('\n'): if cmd.startswith('#'): continue c += cmd + ' && ' c = c.rstrip(' && ') code, _ = subprocess.getstatusoutput('({})'.format(c)) return code
[ "def", "run_cmd", "(", "self", ",", "cmds", ")", ":", "c", "=", "'cd {} && '", ".", "format", "(", "self", ".", "proj_path", ")", "for", "cmd", "in", "cmds", ".", "split", "(", "'\\n'", ")", ":", "if", "cmd", ".", "startswith", "(", "'#'", ")", "...
https://github.com/pythonzm/Ops/blob/e6fdddad2cd6bc697805a2bdba521a26bacada50/projs/utils/svn_tools.py#L82-L93
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/docutils-0.14/docutils/utils/error_reporting.py
python
ErrorOutput.__init__
(self, stream=None, encoding=None, encoding_errors='backslashreplace', decoding_errors='replace')
:Parameters: - `stream`: a file-like object, a string (path to a file), `None` (write to `sys.stderr`, default), or evaluating to `False` (write() requests are ignored). - `encoding`: `stream` text encoding. Guessed if None. - `encoding_errors`: how to treat encoding errors.
:Parameters: - `stream`: a file-like object, a string (path to a file), `None` (write to `sys.stderr`, default), or evaluating to `False` (write() requests are ignored). - `encoding`: `stream` text encoding. Guessed if None. - `encoding_errors`: how to treat encoding errors.
[ ":", "Parameters", ":", "-", "stream", ":", "a", "file", "-", "like", "object", "a", "string", "(", "path", "to", "a", "file", ")", "None", "(", "write", "to", "sys", ".", "stderr", "default", ")", "or", "evaluating", "to", "False", "(", "write", "...
def __init__(self, stream=None, encoding=None, encoding_errors='backslashreplace', decoding_errors='replace'): """ :Parameters: - `stream`: a file-like object, a string (path to a file), `None` (write to `sys.stderr`, default), or evaluating to `False` (write() requests are ignored). - `encoding`: `stream` text encoding. Guessed if None. - `encoding_errors`: how to treat encoding errors. """ if stream is None: stream = sys.stderr elif not(stream): stream = False # if `stream` is a file name, open it elif isinstance(stream, str): stream = open(stream, 'w') elif isinstance(stream, unicode): stream = open(stream.encode(sys.getfilesystemencoding()), 'w') self.stream = stream """Where warning output is sent.""" self.encoding = (encoding or getattr(stream, 'encoding', None) or locale_encoding or 'ascii') """The output character encoding.""" self.encoding_errors = encoding_errors """Encoding error handler.""" self.decoding_errors = decoding_errors """Decoding error handler."""
[ "def", "__init__", "(", "self", ",", "stream", "=", "None", ",", "encoding", "=", "None", ",", "encoding_errors", "=", "'backslashreplace'", ",", "decoding_errors", "=", "'replace'", ")", ":", "if", "stream", "is", "None", ":", "stream", "=", "sys", ".", ...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/docutils-0.14/docutils/utils/error_reporting.py#L152-L185
gnome-terminator/terminator
ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1
terminatorlib/terminal.py
python
Terminal.switch_to_previous_profile
(self)
[]
def switch_to_previous_profile(self): profilelist = self.config.list_profiles() list_length = len(profilelist) if list_length > 1: if profilelist.index(self.get_profile()) == 0: self.force_set_profile(False, profilelist[list_length - 1]) else: self.force_set_profile(False, profilelist[profilelist.index(self.get_profile()) - 1])
[ "def", "switch_to_previous_profile", "(", "self", ")", ":", "profilelist", "=", "self", ".", "config", ".", "list_profiles", "(", ")", "list_length", "=", "len", "(", "profilelist", ")", "if", "list_length", ">", "1", ":", "if", "profilelist", ".", "index", ...
https://github.com/gnome-terminator/terminator/blob/ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1/terminatorlib/terminal.py#L229-L237
pySTEPS/pysteps
bd9478538249e1d64036a721ceb934085d6e1da9
pysteps/utils/transformation.py
python
sqrt_transform
(R, metadata=None, inverse=False, **kwargs)
return R, metadata
Square-root transform. Parameters ---------- R: array-like Array of any shape to be transformed. metadata: dict, optional Metadata dictionary containing the transform, zerovalue and threshold attributes as described in the documentation of :py:mod:`pysteps.io.importers`. inverse: bool, optional If set to True, it performs the inverse transform. False by default. Returns ------- R: array-like Array of any shape containing the (back-)transformed units. metadata: dict The metadata with updated attributes.
Square-root transform.
[ "Square", "-", "root", "transform", "." ]
def sqrt_transform(R, metadata=None, inverse=False, **kwargs): """Square-root transform. Parameters ---------- R: array-like Array of any shape to be transformed. metadata: dict, optional Metadata dictionary containing the transform, zerovalue and threshold attributes as described in the documentation of :py:mod:`pysteps.io.importers`. inverse: bool, optional If set to True, it performs the inverse transform. False by default. Returns ------- R: array-like Array of any shape containing the (back-)transformed units. metadata: dict The metadata with updated attributes. """ R = R.copy() if metadata is None: if inverse: metadata = {"transform": "sqrt"} else: metadata = {"transform": None} metadata["zerovalue"] = np.nan metadata["threshold"] = np.nan else: metadata = metadata.copy() if not inverse: # sqrt transform R = np.sqrt(R) metadata["transform"] = "sqrt" metadata["zerovalue"] = np.sqrt(metadata["zerovalue"]) metadata["threshold"] = np.sqrt(metadata["threshold"]) else: # inverse sqrt transform R = R ** 2 metadata["transform"] = None metadata["zerovalue"] = metadata["zerovalue"] ** 2 metadata["threshold"] = metadata["threshold"] ** 2 return R, metadata
[ "def", "sqrt_transform", "(", "R", ",", "metadata", "=", "None", ",", "inverse", "=", "False", ",", "*", "*", "kwargs", ")", ":", "R", "=", "R", ".", "copy", "(", ")", "if", "metadata", "is", "None", ":", "if", "inverse", ":", "metadata", "=", "{...
https://github.com/pySTEPS/pysteps/blob/bd9478538249e1d64036a721ceb934085d6e1da9/pysteps/utils/transformation.py#L331-L381
jerryli27/TwinGAN
4e5593445778dfb77af9f815b3f4fcafc35758dc
nets/nasnet/nasnet.py
python
build_nasnet_large
(images, num_classes, is_training=True, final_endpoint=None)
Build NASNet Large model for the ImageNet Dataset.
Build NASNet Large model for the ImageNet Dataset.
[ "Build", "NASNet", "Large", "model", "for", "the", "ImageNet", "Dataset", "." ]
def build_nasnet_large(images, num_classes, is_training=True, final_endpoint=None): """Build NASNet Large model for the ImageNet Dataset.""" hparams = _large_imagenet_config(is_training=is_training) if tf.test.is_gpu_available() and hparams.data_format == 'NHWC': tf.logging.info('A GPU is available on the machine, consider using NCHW ' 'data format for increased speed on GPU.') if hparams.data_format == 'NCHW': images = tf.transpose(images, [0, 3, 1, 2]) # Calculate the total number of cells in the network # Add 2 for the reduction cells total_num_cells = hparams.num_cells + 2 # If ImageNet, then add an additional two for the stem cells total_num_cells += 2 normal_cell = nasnet_utils.NasNetANormalCell( hparams.num_conv_filters, hparams.drop_path_keep_prob, total_num_cells, hparams.total_training_steps) reduction_cell = nasnet_utils.NasNetAReductionCell( hparams.num_conv_filters, hparams.drop_path_keep_prob, total_num_cells, hparams.total_training_steps) with arg_scope([slim.dropout, nasnet_utils.drop_path, slim.batch_norm], is_training=is_training): with arg_scope([slim.avg_pool2d, slim.max_pool2d, slim.conv2d, slim.batch_norm, slim.separable_conv2d, nasnet_utils.factorized_reduction, nasnet_utils.global_avg_pool, nasnet_utils.get_channel_index, nasnet_utils.get_channel_dim], data_format=hparams.data_format): return _build_nasnet_base(images, normal_cell=normal_cell, reduction_cell=reduction_cell, num_classes=num_classes, hparams=hparams, is_training=is_training, stem_type='imagenet', final_endpoint=final_endpoint)
[ "def", "build_nasnet_large", "(", "images", ",", "num_classes", ",", "is_training", "=", "True", ",", "final_endpoint", "=", "None", ")", ":", "hparams", "=", "_large_imagenet_config", "(", "is_training", "=", "is_training", ")", "if", "tf", ".", "test", ".", ...
https://github.com/jerryli27/TwinGAN/blob/4e5593445778dfb77af9f815b3f4fcafc35758dc/nets/nasnet/nasnet.py#L374-L418
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/physics/mechanics/linearize.py
python
permutation_matrix
(orig_vec, per_vec)
return p_matrix
Compute the permutation matrix to change order of orig_vec into order of per_vec. Parameters ---------- orig_vec : array_like Symbols in original ordering. per_vec : array_like Symbols in new ordering. Returns ------- p_matrix : Matrix Permutation matrix such that orig_vec == (p_matrix * per_vec).
Compute the permutation matrix to change order of orig_vec into order of per_vec.
[ "Compute", "the", "permutation", "matrix", "to", "change", "order", "of", "orig_vec", "into", "order", "of", "per_vec", "." ]
def permutation_matrix(orig_vec, per_vec): """Compute the permutation matrix to change order of orig_vec into order of per_vec. Parameters ---------- orig_vec : array_like Symbols in original ordering. per_vec : array_like Symbols in new ordering. Returns ------- p_matrix : Matrix Permutation matrix such that orig_vec == (p_matrix * per_vec). """ if not isinstance(orig_vec, (list, tuple)): orig_vec = flatten(orig_vec) if not isinstance(per_vec, (list, tuple)): per_vec = flatten(per_vec) if set(orig_vec) != set(per_vec): raise ValueError("orig_vec and per_vec must be the same length, " + "and contain the same symbols.") ind_list = [orig_vec.index(i) for i in per_vec] p_matrix = zeros(len(orig_vec)) for i, j in enumerate(ind_list): p_matrix[i, j] = 1 return p_matrix
[ "def", "permutation_matrix", "(", "orig_vec", ",", "per_vec", ")", ":", "if", "not", "isinstance", "(", "orig_vec", ",", "(", "list", ",", "tuple", ")", ")", ":", "orig_vec", "=", "flatten", "(", "orig_vec", ")", "if", "not", "isinstance", "(", "per_vec"...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/physics/mechanics/linearize.py#L401-L428
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/tf/util/data.py
python
Dim.__init__
(self, kind=Types.Unspecified, description=None, dimension=None, vocab=None, dyn_size=None, dyn_size_ext=None, undefined=False, generic=False, special=False, derived_from_tag=None, derived_from_op=None, batch=None, control_flow_ctx=None, src_data=None, src_axis=None)
:param Entity|None kind: :param str|None description: the description should be unique :param int|None dimension: :param returnn.datasets.util.vocabulary.Vocabulary|None vocab: :param tf.Tensor|None dyn_size: e.g. seq_len, (batch,) :param Data|None dyn_size_ext: seq_len or extended :param bool undefined: When this is specified as `None` by the user via `shape`. :param bool generic: This can not be a dim tag of :class:`Data` but it would match to other existing dim tags :func:`Data.get_axis_from_description` and :func:`Dim.is_equal`. :param bool special: Like `generic`, this can not be a dim tag of :class:`Data`. But this dim tag also does not match anything except itself. So it can be used to represent special placeholders with special meanings like ``single_step``. :param Dim|None derived_from_tag: Whether this new tag is reduced, down/up sampled, padded etc from this given other tag. In situations where dim tags are being matched (Data.get_common_data), the behavior is to consider them as equal, and assume that the chain of operations (e.g. padding + valid conv) results in the same dim. :param Dim.Op|None derived_from_op: :param BatchInfo|None batch: for batch-dim, or dynamic dims per batch :param ControlFlowContext|None control_flow_ctx: :param Data|None src_data: :param int|None src_axis:
:param Entity|None kind: :param str|None description: the description should be unique :param int|None dimension: :param returnn.datasets.util.vocabulary.Vocabulary|None vocab: :param tf.Tensor|None dyn_size: e.g. seq_len, (batch,) :param Data|None dyn_size_ext: seq_len or extended :param bool undefined: When this is specified as `None` by the user via `shape`. :param bool generic: This can not be a dim tag of :class:`Data` but it would match to other existing dim tags :func:`Data.get_axis_from_description` and :func:`Dim.is_equal`. :param bool special: Like `generic`, this can not be a dim tag of :class:`Data`. But this dim tag also does not match anything except itself. So it can be used to represent special placeholders with special meanings like ``single_step``. :param Dim|None derived_from_tag: Whether this new tag is reduced, down/up sampled, padded etc from this given other tag. In situations where dim tags are being matched (Data.get_common_data), the behavior is to consider them as equal, and assume that the chain of operations (e.g. padding + valid conv) results in the same dim. :param Dim.Op|None derived_from_op: :param BatchInfo|None batch: for batch-dim, or dynamic dims per batch :param ControlFlowContext|None control_flow_ctx: :param Data|None src_data: :param int|None src_axis:
[ ":", "param", "Entity|None", "kind", ":", ":", "param", "str|None", "description", ":", "the", "description", "should", "be", "unique", ":", "param", "int|None", "dimension", ":", ":", "param", "returnn", ".", "datasets", ".", "util", ".", "vocabulary", ".",...
def __init__(self, kind=Types.Unspecified, description=None, dimension=None, vocab=None, dyn_size=None, dyn_size_ext=None, undefined=False, generic=False, special=False, derived_from_tag=None, derived_from_op=None, batch=None, control_flow_ctx=None, src_data=None, src_axis=None): """ :param Entity|None kind: :param str|None description: the description should be unique :param int|None dimension: :param returnn.datasets.util.vocabulary.Vocabulary|None vocab: :param tf.Tensor|None dyn_size: e.g. seq_len, (batch,) :param Data|None dyn_size_ext: seq_len or extended :param bool undefined: When this is specified as `None` by the user via `shape`. :param bool generic: This can not be a dim tag of :class:`Data` but it would match to other existing dim tags :func:`Data.get_axis_from_description` and :func:`Dim.is_equal`. :param bool special: Like `generic`, this can not be a dim tag of :class:`Data`. But this dim tag also does not match anything except itself. So it can be used to represent special placeholders with special meanings like ``single_step``. :param Dim|None derived_from_tag: Whether this new tag is reduced, down/up sampled, padded etc from this given other tag. In situations where dim tags are being matched (Data.get_common_data), the behavior is to consider them as equal, and assume that the chain of operations (e.g. padding + valid conv) results in the same dim. :param Dim.Op|None derived_from_op: :param BatchInfo|None batch: for batch-dim, or dynamic dims per batch :param ControlFlowContext|None control_flow_ctx: :param Data|None src_data: :param int|None src_axis: """ assert kind is None or (isinstance(kind, Entity) and kind in self.Types.Types) assert dimension is None or isinstance(dimension, int) assert description is None or isinstance(description, str) self.kind = kind self.description = description self.dimension = dimension self._vocab = vocab self.same_as = None # type: typing.Optional[Dim] self._same_as_tb = None # type: typing.Optional[traceback.StackSummary] # for debugging self.derived_from_tag = derived_from_tag self.derived_from_op = derived_from_op if derived_from_op and not derived_from_op.output: derived_from_op.output = self if src_data: assert isinstance(src_data, Data) and isinstance(src_axis, int) if not batch and dyn_size_ext: batch = dyn_size_ext.batch self.batch = batch self.control_flow_ctx = control_flow_ctx self.src_data = src_data self.src_axis = src_axis if dyn_size_ext and not dyn_size_ext.batch and batch: dyn_size_ext.batch = batch if dyn_size_ext: assert batch == dyn_size_ext.batch self.dyn_size_ext = dyn_size_ext # type: typing.Optional[Data] self._dyn_size_same = set() # type: typing.Set[tf.Tensor] self._undefined = undefined self.generic = generic self.special = special # We can have different tag variants per batch info (e.g. with beam), or per control flow ctx. # They each have same_as = self. The same_base should have the base (global) batch info. self._same_for_batch_ctx = {} # type: typing.Dict[typing.Tuple[BatchInfo,typing.Optional[ControlFlowContext]],Dim] # nopep8 if dyn_size is not None: assert not dyn_size_ext self.dyn_size = dyn_size
[ "def", "__init__", "(", "self", ",", "kind", "=", "Types", ".", "Unspecified", ",", "description", "=", "None", ",", "dimension", "=", "None", ",", "vocab", "=", "None", ",", "dyn_size", "=", "None", ",", "dyn_size_ext", "=", "None", ",", "undefined", ...
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/util/data.py#L56-L123
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/ne1_ui/WhatsThisText_for_CommandToolbars.py
python
whatsThisTextForCommandToolbarMoveButton
(button)
return
"What's This" text for the Move button (menu).
"What's This" text for the Move button (menu).
[ "What", "s", "This", "text", "for", "the", "Move", "button", "(", "menu", ")", "." ]
def whatsThisTextForCommandToolbarMoveButton(button): """ "What's This" text for the Move button (menu). """ button.setWhatsThis( """<b>Move</b> <p> <img source=\"ui/actions/Command Toolbar/ControlArea/Move.png\"><br> The <b>Move Command Set</b> which includes specialized rotation and translation commands that operate on the current selection. </p>""") return
[ "def", "whatsThisTextForCommandToolbarMoveButton", "(", "button", ")", ":", "button", ".", "setWhatsThis", "(", "\"\"\"<b>Move</b>\n <p>\n <img source=\\\"ui/actions/Command Toolbar/ControlArea/Move.png\\\"><br>\n The <b>Move Command Set</b> which includes specialized rotati...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/ne1_ui/WhatsThisText_for_CommandToolbars.py#L58-L69
iipeace/guider
880b145ec3a29d838c7be80cc72e4b4150f25c63
guider/guider.py
python
SysMgr.faultHandler
(signum, frame)
SysMgr.releaseResource() sys.stdout.write('terminated by SEGFAULT signal\n')
SysMgr.releaseResource() sys.stdout.write('terminated by SEGFAULT signal\n')
[ "SysMgr", ".", "releaseResource", "()", "sys", ".", "stdout", ".", "write", "(", "terminated", "by", "SEGFAULT", "signal", "\\", "n", ")" ]
def faultHandler(signum, frame): ''' SysMgr.releaseResource() sys.stdout.write('terminated by SEGFAULT signal\n') ''' os._exit(0)
[ "def", "faultHandler", "(", "signum", ",", "frame", ")", ":", "os", ".", "_exit", "(", "0", ")" ]
https://github.com/iipeace/guider/blob/880b145ec3a29d838c7be80cc72e4b4150f25c63/guider/guider.py#L30446-L30451
atlas0fd00m/rfcat
e0583f879236282b6b1f508a597b1dc20c6194c0
rflib/__init__.py
python
RfCat._doSpecAn
(self, centfreq, inc, count)
return freq, delta
store radio config and start sending spectrum analysis data centfreq = Center Frequency
store radio config and start sending spectrum analysis data
[ "store", "radio", "config", "and", "start", "sending", "spectrum", "analysis", "data" ]
def _doSpecAn(self, centfreq, inc, count): ''' store radio config and start sending spectrum analysis data centfreq = Center Frequency ''' if count>255: raise Exception("sorry, only 255 samples per pass... (count)") spectrum = (count * inc) halfspec = spectrum / 2.0 basefreq = centfreq - halfspec if (count * inc) + basefreq > MAX_FREQ: raise Exception("Sorry, %1.3f + (%1.3f * %1.3f) is higher than %1.3f" % (basefreq, count, inc)) self.getRadioConfig() self._specan_backup_radiocfg = self.radiocfg self.setFreq(basefreq) self.setMdmChanSpc(inc) freq, fbytes = self.getFreq() delta = self.getMdmChanSpc() self.send(APP_NIC, RFCAT_START_SPECAN, b"%c" % (count) ) return freq, delta
[ "def", "_doSpecAn", "(", "self", ",", "centfreq", ",", "inc", ",", "count", ")", ":", "if", "count", ">", "255", ":", "raise", "Exception", "(", "\"sorry, only 255 samples per pass... (count)\"", ")", "spectrum", "=", "(", "count", "*", "inc", ")", "halfspec...
https://github.com/atlas0fd00m/rfcat/blob/e0583f879236282b6b1f508a597b1dc20c6194c0/rflib/__init__.py#L66-L91
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/modules/gnome.py
python
_get_girtargets_langs_compilers
(self, girtargets: T.Sequence[build.BuildTarget])
return ret
[]
def _get_girtargets_langs_compilers(self, girtargets: T.Sequence[build.BuildTarget]) -> T.List[T.Tuple[str, 'Compiler']]: ret: T.List[T.Tuple[str, 'Compiler']] = [] for girtarget in girtargets: for lang, compiler in girtarget.compilers.items(): # XXX: Can you use g-i with any other language? if lang in ('c', 'cpp', 'objc', 'objcpp', 'd'): ret.append((lang, compiler)) break return ret
[ "def", "_get_girtargets_langs_compilers", "(", "self", ",", "girtargets", ":", "T", ".", "Sequence", "[", "build", ".", "BuildTarget", "]", ")", "->", "T", ".", "List", "[", "T", ".", "Tuple", "[", "str", ",", "'Compiler'", "]", "]", ":", "ret", ":", ...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/modules/gnome.py#L791-L800
ahmetcemturan/SFACT
7576e29ba72b33e5058049b77b7b558875542747
fabmetheus_utilities/geometry/geometry_utilities/evaluate.py
python
EvaluatorElement.executeFunction
(self, evaluators, evaluatorIndex, nextEvaluator)
Execute the function.
Execute the function.
[ "Execute", "the", "function", "." ]
def executeFunction(self, evaluators, evaluatorIndex, nextEvaluator): 'Execute the function.' executeNextEvaluatorArguments(self, evaluators, evaluatorIndex, nextEvaluator)
[ "def", "executeFunction", "(", "self", ",", "evaluators", ",", "evaluatorIndex", ",", "nextEvaluator", ")", ":", "executeNextEvaluatorArguments", "(", "self", ",", "evaluators", ",", "evaluatorIndex", ",", "nextEvaluator", ")" ]
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/fabmetheus_utilities/geometry/geometry_utilities/evaluate.py#L1554-L1556
ivankorobkov/python-inject
2dcb9624612e2588f9ab984dc3a079c8a35d115c
inject/__init__.py
python
clear
()
Clear an existing injector if present.
Clear an existing injector if present.
[ "Clear", "an", "existing", "injector", "if", "present", "." ]
def clear() -> None: """Clear an existing injector if present.""" global _INJECTOR with _INJECTOR_LOCK: if _INJECTOR is None: return _INJECTOR = None logger.debug('Cleared an injector')
[ "def", "clear", "(", ")", "->", "None", ":", "global", "_INJECTOR", "with", "_INJECTOR_LOCK", ":", "if", "_INJECTOR", "is", "None", ":", "return", "_INJECTOR", "=", "None", "logger", ".", "debug", "(", "'Cleared an injector'", ")" ]
https://github.com/ivankorobkov/python-inject/blob/2dcb9624612e2588f9ab984dc3a079c8a35d115c/inject/__init__.py#L394-L403
Gandi/gandi.cli
5de0605126247e986f8288b467a52710a78e1794
gandi/cli/modules/disk.py
python
Disk._info
(cls, disk_id)
return cls.call('hosting.disk.info', disk_id)
Get information about a disk.
Get information about a disk.
[ "Get", "information", "about", "a", "disk", "." ]
def _info(cls, disk_id): """ Get information about a disk.""" return cls.call('hosting.disk.info', disk_id)
[ "def", "_info", "(", "cls", ",", "disk_id", ")", ":", "return", "cls", ".", "call", "(", "'hosting.disk.info'", ",", "disk_id", ")" ]
https://github.com/Gandi/gandi.cli/blob/5de0605126247e986f8288b467a52710a78e1794/gandi/cli/modules/disk.py#L78-L80
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/data/utils/pythoneditor/editor.py
python
PythonEditor._resetCachedText
(self)
Reset toPlainText() result cache
Reset toPlainText() result cache
[ "Reset", "toPlainText", "()", "result", "cache" ]
def _resetCachedText(self): """Reset toPlainText() result cache """ self._cachedText = None
[ "def", "_resetCachedText", "(", "self", ")", ":", "self", ".", "_cachedText", "=", "None" ]
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/data/utils/pythoneditor/editor.py#L1039-L1042
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/tkinter/__init__.py
python
Canvas.gettags
(self, *args)
return self.tk.splitlist( self.tk.call((self._w, 'gettags') + args))
Return tags associated with the first item specified in ARGS.
Return tags associated with the first item specified in ARGS.
[ "Return", "tags", "associated", "with", "the", "first", "item", "specified", "in", "ARGS", "." ]
def gettags(self, *args): """Return tags associated with the first item specified in ARGS.""" return self.tk.splitlist( self.tk.call((self._w, 'gettags') + args))
[ "def", "gettags", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'gettags'", ")", "+", "args", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/tkinter/__init__.py#L2552-L2555
nltk/nltk_contrib
c9da2c29777ca9df650740145f1f4a375ccac961
nltk_contrib/mit/six863/semantics/chart.py
python
SteppingChartParse.chart
(self)
return self._chart
@return: The chart that is used by this parser.
[]
def chart(self): "@return: The chart that is used by this parser." return self._chart
[ "def", "chart", "(", "self", ")", ":", "return", "self", ".", "_chart" ]
https://github.com/nltk/nltk_contrib/blob/c9da2c29777ca9df650740145f1f4a375ccac961/nltk_contrib/mit/six863/semantics/chart.py#L1483-L1485
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/polynomial/groebner_fan.py
python
GroebnerFan.mixed_volume
(self)
return Integer(self.gfan(cmd='mixedvolume'))
Return the mixed volume of the generators of this ideal. This is not really an ideal property, it can depend on the generators used. The generators must give a square system (as many polynomials as variables). EXAMPLES:: sage: R.<x,y,z> = QQ[] sage: example_ideal = R.ideal([x^2-y-1,y^2-z-1,z^2-x-1]) sage: gf = example_ideal.groebner_fan() sage: mv = gf.mixed_volume() sage: mv 8 sage: R2.<x,y> = QQ[] sage: g1 = 1 - x + x^7*y^3 + 2*x^8*y^4 sage: g2 = 2 + y + 3*x^7*y^3 + x^8*y^4 sage: example2 = R2.ideal([g1,g2]) sage: example2.groebner_fan().mixed_volume() 15
Return the mixed volume of the generators of this ideal.
[ "Return", "the", "mixed", "volume", "of", "the", "generators", "of", "this", "ideal", "." ]
def mixed_volume(self): """ Return the mixed volume of the generators of this ideal. This is not really an ideal property, it can depend on the generators used. The generators must give a square system (as many polynomials as variables). EXAMPLES:: sage: R.<x,y,z> = QQ[] sage: example_ideal = R.ideal([x^2-y-1,y^2-z-1,z^2-x-1]) sage: gf = example_ideal.groebner_fan() sage: mv = gf.mixed_volume() sage: mv 8 sage: R2.<x,y> = QQ[] sage: g1 = 1 - x + x^7*y^3 + 2*x^8*y^4 sage: g2 = 2 + y + 3*x^7*y^3 + x^8*y^4 sage: example2 = R2.ideal([g1,g2]) sage: example2.groebner_fan().mixed_volume() 15 """ if len(self.ring().variable_names()) != self.ideal().ngens(): raise ValueError('not a square system') return Integer(self.gfan(cmd='mixedvolume'))
[ "def", "mixed_volume", "(", "self", ")", ":", "if", "len", "(", "self", ".", "ring", "(", ")", ".", "variable_names", "(", ")", ")", "!=", "self", ".", "ideal", "(", ")", ".", "ngens", "(", ")", ":", "raise", "ValueError", "(", "'not a square system'...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/polynomial/groebner_fan.py#L1736-L1764
pculture/miro
d8e4594441939514dd2ac29812bf37087bb3aea5
tv/lib/frontends/widgets/application.py
python
Application.on_config_changed
(self, obj, key, value)
Any time a preference changes, this gets notified so that we can adjust things.
Any time a preference changes, this gets notified so that we can adjust things.
[ "Any", "time", "a", "preference", "changes", "this", "gets", "notified", "so", "that", "we", "can", "adjust", "things", "." ]
def on_config_changed(self, obj, key, value): """Any time a preference changes, this gets notified so that we can adjust things. """ raise NotImplementedError()
[ "def", "on_config_changed", "(", "self", ",", "obj", ",", "key", ",", "value", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/pculture/miro/blob/d8e4594441939514dd2ac29812bf37087bb3aea5/tv/lib/frontends/widgets/application.py#L188-L192
LordAmit/Brightness
cd8cc615e46fb07d96e8cab7d4d5338a8e87c4e9
src/init.py
python
MyApplication.generate_brightness_sources
(self)
generates assigns display sources to combo boxes
generates assigns display sources to combo boxes
[ "generates", "assigns", "display", "sources", "to", "combo", "boxes" ]
def generate_brightness_sources(self): """ generates assigns display sources to combo boxes """ if self.no_of_connected_dev < 2: self.ui.secondary_combo.addItem("Disabled") self.ui.secondary_combo.setEnabled(False) self.ui.primary_combobox.addItem("Disabled") self.ui.primary_combobox.setEnabled(False) return for display in self.displays: self.ui.secondary_combo.addItem(display) self.ui.primary_combobox.addItem(display)
[ "def", "generate_brightness_sources", "(", "self", ")", ":", "if", "self", ".", "no_of_connected_dev", "<", "2", ":", "self", ".", "ui", ".", "secondary_combo", ".", "addItem", "(", "\"Disabled\"", ")", "self", ".", "ui", ".", "secondary_combo", ".", "setEna...
https://github.com/LordAmit/Brightness/blob/cd8cc615e46fb07d96e8cab7d4d5338a8e87c4e9/src/init.py#L193-L206
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/ipaddress.py
python
IPv6Address.is_private
(self)
return any(self in net for net in self._constants._private_networks)
Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry.
Test if this address is allocated for private networks.
[ "Test", "if", "this", "address", "is", "allocated", "for", "private", "networks", "." ]
def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return any(self in net for net in self._constants._private_networks)
[ "def", "is_private", "(", "self", ")", ":", "return", "any", "(", "self", "in", "net", "for", "net", "in", "self", ".", "_constants", ".", "_private_networks", ")" ]
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/ipaddress.py#L2098-L2106
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/printing/octave.py
python
octave_code
(expr, assign_to=None, **settings)
return OctaveCodePrinter(settings).doprint(expr, assign_to)
r"""Converts `expr` to a string of Octave (or Matlab) code. The string uses a subset of the Octave language for Matlab compatibility. Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. Examples ======== >>> from sympy import octave_code, symbols, sin, pi >>> x = symbols('x') >>> octave_code(sin(x).series(x).removeO()) 'x.^5/120 - x.^3/6 + x' >>> from sympy import Rational, ceiling >>> x, y, tau = symbols("x, y, tau") >>> octave_code((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau.^(7/2)' Note that element-wise (Hadamard) operations are used by default between symbols. This is because its very common in Octave to write "vectorized" code. It is harmless if the values are scalars. >>> octave_code(sin(pi*x*y), assign_to="s") 's = sin(pi*x.*y);' If you need a matrix product "*" or matrix power "^", you can specify the symbol as a ``MatrixSymbol``. >>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> octave_code(3*pi*A**3) '(3*pi)*A^3' This class uses several rules to decide which symbol to use a product. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". A HadamardProduct can be used to specify componentwise multiplication ".*" of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write "(x^2*y)*A^3", we generate: >>> octave_code(x**2*y*A**3) '(x.^2.*y)*A^3' Matrices are supported using Octave inline notation. When using ``assign_to`` with matrices, the name can be specified either as a string or as a ``MatrixSymbol``. The dimensions must align in the latter case. >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 sin(x) ceil(x)];' ``Piecewise`` expressions are implemented with logical masking by default. Alternatively, you can pass "inline=False" to use if-else conditionals. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> octave_code(pw, assign_to=tau) 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));' Note that any expression that can be generated normally can also exist inside a Matrix: >>> mat = Matrix([[x**2, pw, sin(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Octave function. >>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_octave_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> octave_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));'
r"""Converts `expr` to a string of Octave (or Matlab) code.
[ "r", "Converts", "expr", "to", "a", "string", "of", "Octave", "(", "or", "Matlab", ")", "code", "." ]
def octave_code(expr, assign_to=None, **settings): r"""Converts `expr` to a string of Octave (or Matlab) code. The string uses a subset of the Octave language for Matlab compatibility. Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. Examples ======== >>> from sympy import octave_code, symbols, sin, pi >>> x = symbols('x') >>> octave_code(sin(x).series(x).removeO()) 'x.^5/120 - x.^3/6 + x' >>> from sympy import Rational, ceiling >>> x, y, tau = symbols("x, y, tau") >>> octave_code((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau.^(7/2)' Note that element-wise (Hadamard) operations are used by default between symbols. This is because its very common in Octave to write "vectorized" code. It is harmless if the values are scalars. >>> octave_code(sin(pi*x*y), assign_to="s") 's = sin(pi*x.*y);' If you need a matrix product "*" or matrix power "^", you can specify the symbol as a ``MatrixSymbol``. >>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> octave_code(3*pi*A**3) '(3*pi)*A^3' This class uses several rules to decide which symbol to use a product. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". A HadamardProduct can be used to specify componentwise multiplication ".*" of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write "(x^2*y)*A^3", we generate: >>> octave_code(x**2*y*A**3) '(x.^2.*y)*A^3' Matrices are supported using Octave inline notation. When using ``assign_to`` with matrices, the name can be specified either as a string or as a ``MatrixSymbol``. The dimensions must align in the latter case. >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 sin(x) ceil(x)];' ``Piecewise`` expressions are implemented with logical masking by default. Alternatively, you can pass "inline=False" to use if-else conditionals. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> octave_code(pw, assign_to=tau) 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));' Note that any expression that can be generated normally can also exist inside a Matrix: >>> mat = Matrix([[x**2, pw, sin(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Octave function. >>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_octave_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> octave_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));' """ return OctaveCodePrinter(settings).doprint(expr, assign_to)
[ "def", "octave_code", "(", "expr", ",", "assign_to", "=", "None", ",", "*", "*", "settings", ")", ":", "return", "OctaveCodePrinter", "(", "settings", ")", ".", "doprint", "(", "expr", ",", "assign_to", ")" ]
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/printing/octave.py#L573-L709
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_obj.py
python
OCObject.get
(self)
return results
return a kind by name
return a kind by name
[ "return", "a", "kind", "by", "name" ]
def get(self): '''return a kind by name ''' results = self._get(self.kind, name=self.name, selector=self.selector, field_selector=self.field_selector) if (results['returncode'] != 0 and 'stderr' in results and '\"{}\" not found'.format(self.name) in results['stderr']): results['returncode'] = 0 return results
[ "def", "get", "(", "self", ")", ":", "results", "=", "self", ".", "_get", "(", "self", ".", "kind", ",", "name", "=", "self", ".", "name", ",", "selector", "=", "self", ".", "selector", ",", "field_selector", "=", "self", ".", "field_selector", ")", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_obj.py#L1515-L1522
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/yunjing/v20180228/models.py
python
WeeklyReportMalware.__init__
(self)
r""" :param MachineIp: 主机IP。 :type MachineIp: str :param FilePath: 木马文件路径。 :type FilePath: str :param Md5: 木马文件MD5值。 :type Md5: str :param FindTime: 木马发现时间。 :type FindTime: str :param Status: 当前木马状态。 <li>UN_OPERATED:未处理</li> <li>SEGREGATED:已隔离</li> <li>TRUSTED:已信任</li> <li>SEPARATING:隔离中</li> <li>RECOVERING:恢复中</li> :type Status: str
r""" :param MachineIp: 主机IP。 :type MachineIp: str :param FilePath: 木马文件路径。 :type FilePath: str :param Md5: 木马文件MD5值。 :type Md5: str :param FindTime: 木马发现时间。 :type FindTime: str :param Status: 当前木马状态。 <li>UN_OPERATED:未处理</li> <li>SEGREGATED:已隔离</li> <li>TRUSTED:已信任</li> <li>SEPARATING:隔离中</li> <li>RECOVERING:恢复中</li> :type Status: str
[ "r", ":", "param", "MachineIp", ":", "主机IP。", ":", "type", "MachineIp", ":", "str", ":", "param", "FilePath", ":", "木马文件路径。", ":", "type", "FilePath", ":", "str", ":", "param", "Md5", ":", "木马文件MD5值。", ":", "type", "Md5", ":", "str", ":", "param", "F...
def __init__(self): r""" :param MachineIp: 主机IP。 :type MachineIp: str :param FilePath: 木马文件路径。 :type FilePath: str :param Md5: 木马文件MD5值。 :type Md5: str :param FindTime: 木马发现时间。 :type FindTime: str :param Status: 当前木马状态。 <li>UN_OPERATED:未处理</li> <li>SEGREGATED:已隔离</li> <li>TRUSTED:已信任</li> <li>SEPARATING:隔离中</li> <li>RECOVERING:恢复中</li> :type Status: str """ self.MachineIp = None self.FilePath = None self.Md5 = None self.FindTime = None self.Status = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "MachineIp", "=", "None", "self", ".", "FilePath", "=", "None", "self", ".", "Md5", "=", "None", "self", ".", "FindTime", "=", "None", "self", ".", "Status", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/yunjing/v20180228/models.py#L7666-L7688
google/macops
8442745359c0c941cd4e4e7d243e43bd16b40dec
gmacpyutil/gmacpyutil/cocoadialog.py
python
Bubble.GetAlpha
(self)
return self._alpha
[]
def GetAlpha(self): return self._alpha
[ "def", "GetAlpha", "(", "self", ")", ":", "return", "self", ".", "_alpha" ]
https://github.com/google/macops/blob/8442745359c0c941cd4e4e7d243e43bd16b40dec/gmacpyutil/gmacpyutil/cocoadialog.py#L193-L194
florath/rmtoo
6ffe08703451358dca24b232ee4380b1da23bcad
rmtoo/outputs/LatexJinja2.py
python
LatexJinja2.topic_text
(self, text)
Write out the given text.
Write out the given text.
[ "Write", "out", "the", "given", "text", "." ]
def topic_text(self, text): '''Write out the given text.''' req_template = self._template_env.get_template("topicText.tex") template_vars = {'text': text} self.__fd.write(req_template.render(template_vars))
[ "def", "topic_text", "(", "self", ",", "text", ")", ":", "req_template", "=", "self", ".", "_template_env", ".", "get_template", "(", "\"topicText.tex\"", ")", "template_vars", "=", "{", "'text'", ":", "text", "}", "self", ".", "__fd", ".", "write", "(", ...
https://github.com/florath/rmtoo/blob/6ffe08703451358dca24b232ee4380b1da23bcad/rmtoo/outputs/LatexJinja2.py#L194-L198
aouyar/PyMunin
94624d4f56340cb2ed7e96ca3c5d9533a0721306
pysysinfo/freeswitch.py
python
FSinfo._execShowCmd
(self, showcmd)
return result
Execute 'show' command and return result dictionary. @param cmd: Command string. @return: Result dictionary.
Execute 'show' command and return result dictionary.
[ "Execute", "show", "command", "and", "return", "result", "dictionary", "." ]
def _execShowCmd(self, showcmd): """Execute 'show' command and return result dictionary. @param cmd: Command string. @return: Result dictionary. """ result = None lines = self._execCmd("show", showcmd) if lines and len(lines) >= 2 and lines[0] != '' and lines[0][0] != '-': result = {} result['keys'] = lines[0].split(',') items = [] for line in lines[1:]: if line == '': break items.append(line.split(',')) result['items'] = items return result
[ "def", "_execShowCmd", "(", "self", ",", "showcmd", ")", ":", "result", "=", "None", "lines", "=", "self", ".", "_execCmd", "(", "\"show\"", ",", "showcmd", ")", "if", "lines", "and", "len", "(", "lines", ")", ">=", "2", "and", "lines", "[", "0", "...
https://github.com/aouyar/PyMunin/blob/94624d4f56340cb2ed7e96ca3c5d9533a0721306/pysysinfo/freeswitch.py#L89-L107
RDFLib/rdflib
c0bd5eaaa983461445b9469d731be4ae0e0cfc54
rdflib/plugins/sparql/operators.py
python
Builtin_STRBEFORE
(expr, ctx)
http://www.w3.org/TR/sparql11-query/#func-strbefore
http://www.w3.org/TR/sparql11-query/#func-strbefore
[ "http", ":", "//", "www", ".", "w3", ".", "org", "/", "TR", "/", "sparql11", "-", "query", "/", "#func", "-", "strbefore" ]
def Builtin_STRBEFORE(expr, ctx): """ http://www.w3.org/TR/sparql11-query/#func-strbefore """ a = expr.arg1 b = expr.arg2 _compatibleStrings(a, b) i = a.find(b) if i == -1: return Literal("") else: return Literal(a[:i], lang=a.language, datatype=a.datatype)
[ "def", "Builtin_STRBEFORE", "(", "expr", ",", "ctx", ")", ":", "a", "=", "expr", ".", "arg1", "b", "=", "expr", ".", "arg2", "_compatibleStrings", "(", "a", ",", "b", ")", "i", "=", "a", ".", "find", "(", "b", ")", "if", "i", "==", "-", "1", ...
https://github.com/RDFLib/rdflib/blob/c0bd5eaaa983461445b9469d731be4ae0e0cfc54/rdflib/plugins/sparql/operators.py#L344-L357
seemethere/nba_py
f1cd2b0f2702601accf21fef4b721a1564ef4705
nba_py/player.py
python
_PlayerDashboard.overall
(self)
return _api_scrape(self.json, 0)
[]
def overall(self): return _api_scrape(self.json, 0)
[ "def", "overall", "(", "self", ")", ":", "return", "_api_scrape", "(", "self", ".", "json", ",", "0", ")" ]
https://github.com/seemethere/nba_py/blob/f1cd2b0f2702601accf21fef4b721a1564ef4705/nba_py/player.py#L188-L189
whoosh-community/whoosh
5421f1ab3bb802114105b3181b7ce4f44ad7d0bb
src/whoosh/reading.py
python
TermInfo.max_weight
(self)
return self._maxweight
Returns the number of times the term appears in the document in which it appears the most.
Returns the number of times the term appears in the document in which it appears the most.
[ "Returns", "the", "number", "of", "times", "the", "term", "appears", "in", "the", "document", "in", "which", "it", "appears", "the", "most", "." ]
def max_weight(self): """Returns the number of times the term appears in the document in which it appears the most. """ return self._maxweight
[ "def", "max_weight", "(", "self", ")", ":", "return", "self", ".", "_maxweight" ]
https://github.com/whoosh-community/whoosh/blob/5421f1ab3bb802114105b3181b7ce4f44ad7d0bb/src/whoosh/reading.py#L119-L124
blawar/nut
2cf351400418399a70164987e28670309f6c9cb5
Fs/IndexedFile.py
python
IndexedFile.move
(self, forceNsp=False)
return True
[]
def move(self, forceNsp=False): if not self.path: Print.error('no path set') return False if os.path.abspath(self.path).startswith(os.path.abspath(Config.paths.nspOut)) and not self.path.endswith('.nsz') and not self.path.endswith('.xcz') and Config.compression.auto: nszFile = nut.compress(self.path, Config.compression.level, os.path.abspath(Config.paths.nspOut)) if nszFile: nsp = Nsps.registerFile(nszFile) nsp.hasValidTicket = True nsp.move(forceNsp=True) newPath = self.fileName(forceNsp=forceNsp) if not newPath: Print.error('could not get filename for ' + self.path) return False newPath = os.path.abspath(newPath) if newPath.lower().replace('\\', '/') == self.path.lower().replace('\\', '/'): return False if os.path.isfile(newPath): Print.info('\nduplicate title: ') Print.info(os.path.abspath(self.path)) Print.info(newPath) Print.info('\n') return False if self.isOpen(): if not self.verifyNcaHeaders(): Print.error('verification failed: could not move title for ' + str(self.titleId) + ' or ' + str(Title.getBaseId(self.titleId))) return False else: try: self.open(self.path) if not self.verifyNcaHeaders(): Print.error('verification failed: could not move title for ' + str(self.titleId) + ' or ' + str(Title.getBaseId(self.titleId))) return False finally: self.close() try: Print.info(self.path + ' -> ' + newPath) if not Config.dryRun: os.makedirs(os.path.dirname(newPath), exist_ok=True) #newPath = self.fileName(forceNsp = forceNsp) if not Config.dryRun: if self.isOpen(): self.close() shutil.move(self.path, newPath) Nsps.moveFile(self.path, newPath) #Nsps.files[newPath] = self self.path = newPath except BaseException as e: Print.error('failed to rename file! %s -> %s : %s' % (self.path, newPath, e)) if not Config.dryRun: self.moveDupe() return True
[ "def", "move", "(", "self", ",", "forceNsp", "=", "False", ")", ":", "if", "not", "self", ".", "path", ":", "Print", ".", "error", "(", "'no path set'", ")", "return", "False", "if", "os", ".", "path", ".", "abspath", "(", "self", ".", "path", ")",...
https://github.com/blawar/nut/blob/2cf351400418399a70164987e28670309f6c9cb5/Fs/IndexedFile.py#L127-L191
holoviz/panel
5e25cb09447d8edf0b316f130ee1318a2aeb880f
panel/io/reload.py
python
autoreload_watcher
()
Installs a periodic callback which checks for changes in watched files and sys.modules.
Installs a periodic callback which checks for changes in watched files and sys.modules.
[ "Installs", "a", "periodic", "callback", "which", "checks", "for", "changes", "in", "watched", "files", "and", "sys", ".", "modules", "." ]
def autoreload_watcher(): """ Installs a periodic callback which checks for changes in watched files and sys.modules. """ cb = partial(_reload_on_update, {}) _callbacks[state.curdoc] = pcb = PeriodicCallback(callback=cb) pcb.start()
[ "def", "autoreload_watcher", "(", ")", ":", "cb", "=", "partial", "(", "_reload_on_update", ",", "{", "}", ")", "_callbacks", "[", "state", ".", "curdoc", "]", "=", "pcb", "=", "PeriodicCallback", "(", "callback", "=", "cb", ")", "pcb", ".", "start", "...
https://github.com/holoviz/panel/blob/5e25cb09447d8edf0b316f130ee1318a2aeb880f/panel/io/reload.py#L67-L74
curtacircuitos/pcb-tools
0b6ccc3d268ed85617590c2a9080c9b999369a7e
gerber/rs274x.py
python
GerberParser._split_commands
(self, data)
Split the data into commands. Commands end with * (and also newline to help with some badly formatted files)
Split the data into commands. Commands end with * (and also newline to help with some badly formatted files)
[ "Split", "the", "data", "into", "commands", ".", "Commands", "end", "with", "*", "(", "and", "also", "newline", "to", "help", "with", "some", "badly", "formatted", "files", ")" ]
def _split_commands(self, data): """ Split the data into commands. Commands end with * (and also newline to help with some badly formatted files) """ length = len(data) start = 0 in_header = True for cur in range(0, length): val = data[cur] if val == '%' and start == cur: in_header = True continue if val == '\r' or val == '\n': if start != cur: yield data[start:cur] start = cur + 1 elif not in_header and val == '*': yield data[start:cur + 1] start = cur + 1 elif in_header and val == '%': yield data[start:cur + 1] start = cur + 1 in_header = False
[ "def", "_split_commands", "(", "self", ",", "data", ")", ":", "length", "=", "len", "(", "data", ")", "start", "=", "0", "in_header", "=", "True", "for", "cur", "in", "range", "(", "0", ",", "length", ")", ":", "val", "=", "data", "[", "cur", "]"...
https://github.com/curtacircuitos/pcb-tools/blob/0b6ccc3d268ed85617590c2a9080c9b999369a7e/gerber/rs274x.py#L279-L308
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/volvooncall/lock.py
python
VolvoLock.async_unlock
(self, **kwargs)
Unlock the car.
Unlock the car.
[ "Unlock", "the", "car", "." ]
async def async_unlock(self, **kwargs): """Unlock the car.""" await self.instrument.unlock()
[ "async", "def", "async_unlock", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "instrument", ".", "unlock", "(", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/volvooncall/lock.py#L37-L39
SpaceNetChallenge/SpaceNet_Off_Nadir_Solutions
014c4ca27a70b5907a183e942228004c989dcbe4
XD_XD/main.py
python
__filecheck
(path, max_length=80)
[]
def __filecheck(path, max_length=80): print(path, end='') if len(str(path)) > max_length - 6: print('\t', end='') else: space_size = max_length - 6 - len(str(path)) print(space_size * ' ', end='') if path.exists(): print('[ \x1b[6;32;40m' + 'OK' + '\x1b[0m ]') return True else: print('[ \x1b[6;31;40m' + 'NG' + '\x1b[0m ]') return False
[ "def", "__filecheck", "(", "path", ",", "max_length", "=", "80", ")", ":", "print", "(", "path", ",", "end", "=", "''", ")", "if", "len", "(", "str", "(", "path", ")", ")", ">", "max_length", "-", "6", ":", "print", "(", "'\\t'", ",", "end", "=...
https://github.com/SpaceNetChallenge/SpaceNet_Off_Nadir_Solutions/blob/014c4ca27a70b5907a183e942228004c989dcbe4/XD_XD/main.py#L935-L948
opencobra/cobrapy
0b9ea70cb0ffe78568d445ce3361ad10ec6b02a2
src/cobra/flux_analysis/deletion.py
python
_init_worker
(model: Model)
Initialize worker process.
Initialize worker process.
[ "Initialize", "worker", "process", "." ]
def _init_worker(model: Model) -> None: """Initialize worker process.""" global _model _model = model
[ "def", "_init_worker", "(", "model", ":", "Model", ")", "->", "None", ":", "global", "_model", "_model", "=", "model" ]
https://github.com/opencobra/cobrapy/blob/0b9ea70cb0ffe78568d445ce3361ad10ec6b02a2/src/cobra/flux_analysis/deletion.py#L140-L144
abakan-zz/ablog
7fb9fcb1bc9651ef5daffbb76a7ed11f3bbe6cd3
ablog/blog.py
python
Post.to_html
(self, pagename, fulltext=False, drop_h1=True)
return html
Return excerpt or *fulltext* as HTML after resolving references with respect to *pagename*. By default, first `<h1>` tag is dropped from the output. More than one can be dropped by setting *drop_h1* to the desired number of tags to be dropped.
Return excerpt or *fulltext* as HTML after resolving references with respect to *pagename*. By default, first `<h1>` tag is dropped from the output. More than one can be dropped by setting *drop_h1* to the desired number of tags to be dropped.
[ "Return", "excerpt", "or", "*", "fulltext", "*", "as", "HTML", "after", "resolving", "references", "with", "respect", "to", "*", "pagename", "*", ".", "By", "default", "first", "<h1", ">", "tag", "is", "dropped", "from", "the", "output", ".", "More", "th...
def to_html(self, pagename, fulltext=False, drop_h1=True): """Return excerpt or *fulltext* as HTML after resolving references with respect to *pagename*. By default, first `<h1>` tag is dropped from the output. More than one can be dropped by setting *drop_h1* to the desired number of tags to be dropped.""" if fulltext: doctree = nodes.document({}, dummy_reporter) deepcopy = self.doctree.deepcopy() if isinstance(deepcopy, nodes.document): doctree.extend(deepcopy.children) else: doctree.append(deepcopy) else: doctree = nodes.document({}, dummy_reporter) for node in self.excerpt: doctree.append(node.deepcopy()) app = self._blog.app revise_pending_xrefs(doctree, pagename) app.env.resolve_references(doctree, pagename, app.builder) add_permalinks, app.builder.add_permalinks = ( app.builder.add_permalinks, False) html = html_builder_write_doc(app.builder, pagename, doctree) app.builder.add_permalinks = add_permalinks if drop_h1: html = re.sub('<h1>(.*?)</h1>', '', html, count=abs(int(drop_h1))) return html
[ "def", "to_html", "(", "self", ",", "pagename", ",", "fulltext", "=", "False", ",", "drop_h1", "=", "True", ")", ":", "if", "fulltext", ":", "doctree", "=", "nodes", ".", "document", "(", "{", "}", ",", "dummy_reporter", ")", "deepcopy", "=", "self", ...
https://github.com/abakan-zz/ablog/blob/7fb9fcb1bc9651ef5daffbb76a7ed11f3bbe6cd3/ablog/blog.py#L377-L408
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/data/table.py
python
Table.to_dense
(self, dense_attributes=True, dense_class=True, dense_metas=True)
return t
[]
def to_dense(self, dense_attributes=True, dense_class=True, dense_metas=True): def densify(features): for f in features: f.sparse = False new_domain = self.domain.copy() if dense_attributes: densify(new_domain.attributes) if dense_class: densify(new_domain.class_vars) if dense_metas: densify(new_domain.metas) t = self.transform(new_domain) t.ids = self.ids # preserve indices return t
[ "def", "to_dense", "(", "self", ",", "dense_attributes", "=", "True", ",", "dense_class", "=", "True", ",", "dense_metas", "=", "True", ")", ":", "def", "densify", "(", "features", ")", ":", "for", "f", "in", "features", ":", "f", ".", "sparse", "=", ...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/data/table.py#L2252-L2268
blackye/lalascan
e35726e6648525eb47493e39ee63a2a906dbb4b2
lalascan/data/information/html.py
python
HTML.javascript_embedded
(self)
return HTMLParser(self.raw_data).javascript_embedded
:return: Embedded JavaScript. :rtype: list(HTMLElement)
:return: Embedded JavaScript. :rtype: list(HTMLElement)
[ ":", "return", ":", "Embedded", "JavaScript", ".", ":", "rtype", ":", "list", "(", "HTMLElement", ")" ]
def javascript_embedded(self): """ :return: Embedded JavaScript. :rtype: list(HTMLElement) """ return HTMLParser(self.raw_data).javascript_embedded
[ "def", "javascript_embedded", "(", "self", ")", ":", "return", "HTMLParser", "(", "self", ".", "raw_data", ")", ".", "javascript_embedded" ]
https://github.com/blackye/lalascan/blob/e35726e6648525eb47493e39ee63a2a906dbb4b2/lalascan/data/information/html.py#L135-L140
lektor/lektor
d5a7f22343572a991f2316c086f24005d0cbf0f8
lektor/builder.py
python
FileInfo.size
(self)
return self._get_stat()[1]
The size of the file in bytes. If the file is actually a dictionary then the size is actually the number of files in it.
The size of the file in bytes. If the file is actually a dictionary then the size is actually the number of files in it.
[ "The", "size", "of", "the", "file", "in", "bytes", ".", "If", "the", "file", "is", "actually", "a", "dictionary", "then", "the", "size", "is", "actually", "the", "number", "of", "files", "in", "it", "." ]
def size(self): """The size of the file in bytes. If the file is actually a dictionary then the size is actually the number of files in it. """ return self._get_stat()[1]
[ "def", "size", "(", "self", ")", ":", "return", "self", ".", "_get_stat", "(", ")", "[", "1", "]" ]
https://github.com/lektor/lektor/blob/d5a7f22343572a991f2316c086f24005d0cbf0f8/lektor/builder.py#L525-L529
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/schemes/elliptic_curves/height.py
python
EllipticCurveCanonicalHeight.tau
(self, v)
return self.E.period_lattice(v).tau()
r""" Return the normalised upper half-plane parameter `\tau` for the period lattice with respect to the embedding `v`. INPUT: - ``v`` (embedding) - a real or complex embedding of the number field. OUTPUT: (Complex) `\tau = \omega_1/\omega_2` in the fundamental region of the upper half-plane. EXAMPLES:: sage: E = EllipticCurve('37a') sage: H = E.height_function() sage: H.tau(QQ.places()[0]) 1.22112736076463*I
r""" Return the normalised upper half-plane parameter `\tau` for the period lattice with respect to the embedding `v`.
[ "r", "Return", "the", "normalised", "upper", "half", "-", "plane", "parameter", "\\", "tau", "for", "the", "period", "lattice", "with", "respect", "to", "the", "embedding", "v", "." ]
def tau(self, v): r""" Return the normalised upper half-plane parameter `\tau` for the period lattice with respect to the embedding `v`. INPUT: - ``v`` (embedding) - a real or complex embedding of the number field. OUTPUT: (Complex) `\tau = \omega_1/\omega_2` in the fundamental region of the upper half-plane. EXAMPLES:: sage: E = EllipticCurve('37a') sage: H = E.height_function() sage: H.tau(QQ.places()[0]) 1.22112736076463*I """ return self.E.period_lattice(v).tau()
[ "def", "tau", "(", "self", ",", "v", ")", ":", "return", "self", ".", "E", ".", "period_lattice", "(", "v", ")", ".", "tau", "(", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/elliptic_curves/height.py#L1337-L1358
rsmusllp/king-phisher
6acbbd856f849d407cc904c075441e0cf13c25cf
king_phisher/utilities.py
python
make_visit_uid
()
return random_string(24)
Creates a random string of characters and numbers to be used as a visit id. :return: String of characters from the random_string function. :rtype: str
Creates a random string of characters and numbers to be used as a visit id.
[ "Creates", "a", "random", "string", "of", "characters", "and", "numbers", "to", "be", "used", "as", "a", "visit", "id", "." ]
def make_visit_uid(): """ Creates a random string of characters and numbers to be used as a visit id. :return: String of characters from the random_string function. :rtype: str """ return random_string(24)
[ "def", "make_visit_uid", "(", ")", ":", "return", "random_string", "(", "24", ")" ]
https://github.com/rsmusllp/king-phisher/blob/6acbbd856f849d407cc904c075441e0cf13c25cf/king_phisher/utilities.py#L413-L420
meliketoy/fine-tuning.pytorch
91b45bbf1287a33603c344d64c06b6b1bf8f226e
networks/resnet.py
python
conv3x3
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "...
https://github.com/meliketoy/fine-tuning.pytorch/blob/91b45bbf1287a33603c344d64c06b6b1bf8f226e/networks/resnet.py#L17-L20
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventDetails.shared_content_change_viewer_info_policy_details
(cls, val)
return cls('shared_content_change_viewer_info_policy_details', val)
Create an instance of this class set to the ``shared_content_change_viewer_info_policy_details`` tag with value ``val``. :param SharedContentChangeViewerInfoPolicyDetails val: :rtype: EventDetails
Create an instance of this class set to the ``shared_content_change_viewer_info_policy_details`` tag with value ``val``.
[ "Create", "an", "instance", "of", "this", "class", "set", "to", "the", "shared_content_change_viewer_info_policy_details", "tag", "with", "value", "val", "." ]
def shared_content_change_viewer_info_policy_details(cls, val): """ Create an instance of this class set to the ``shared_content_change_viewer_info_policy_details`` tag with value ``val``. :param SharedContentChangeViewerInfoPolicyDetails val: :rtype: EventDetails """ return cls('shared_content_change_viewer_info_policy_details', val)
[ "def", "shared_content_change_viewer_info_policy_details", "(", "cls", ",", "val", ")", ":", "return", "cls", "(", "'shared_content_change_viewer_info_policy_details'", ",", "val", ")" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L10980-L10989
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/util/timer.py
python
TimingContext.__exit__
(self, exc_type, exc_val, exc_tb)
[]
def __exit__(self, exc_type, exc_val, exc_tb): self.stop(self.peek().name)
[ "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_val", ",", "exc_tb", ")", ":", "self", ".", "stop", "(", "self", ".", "peek", "(", ")", ".", "name", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/util/timer.py#L170-L171
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/heatmapgl/hoverlabel/_font.py
python
Font.family
(self)
return self["family"]
HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray
HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above
[ "HTML", "font", "family", "-", "the", "typeface", "that", "will", "be", "applied", "by", "the", "web", "browser", ".", "The", "web", "browser", "will", "only", "be", "able", "to", "apply", "a", "font", "if", "it", "is", "available", "on", "the", "syste...
def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["family"]
[ "def", "family", "(", "self", ")", ":", "return", "self", "[", "\"family\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/heatmapgl/hoverlabel/_font.py#L94-L117
celery/django-celery
c679b05b2abc174e6fa3231b120a07b49ec8f911
djcelery/management/commands/celeryd.py
python
Command.handle
(self, *args, **options)
[]
def handle(self, *args, **options): worker.check_args(args) worker.run(**options)
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "worker", ".", "check_args", "(", "args", ")", "worker", ".", "run", "(", "*", "*", "options", ")" ]
https://github.com/celery/django-celery/blob/c679b05b2abc174e6fa3231b120a07b49ec8f911/djcelery/management/commands/celeryd.py#L25-L27
tensorflow/tfx
b4a6b83269815ed12ba9df9e9154c7376fef2ea0
tfx/orchestration/kubeflow/utils.py
python
fix_brackets
(placeholder: str)
Fix the imbalanced brackets in placeholder. When ptype is not null, regex matching might grab a placeholder with } missing. This function fix the missing bracket. Args: placeholder: string placeholder of RuntimeParameter Returns: Placeholder with re-balanced brackets. Raises: RuntimeError: if left brackets are less than right brackets.
Fix the imbalanced brackets in placeholder.
[ "Fix", "the", "imbalanced", "brackets", "in", "placeholder", "." ]
def fix_brackets(placeholder: str) -> str: """Fix the imbalanced brackets in placeholder. When ptype is not null, regex matching might grab a placeholder with } missing. This function fix the missing bracket. Args: placeholder: string placeholder of RuntimeParameter Returns: Placeholder with re-balanced brackets. Raises: RuntimeError: if left brackets are less than right brackets. """ lcount = placeholder.count('{') rcount = placeholder.count('}') if lcount < rcount: raise RuntimeError( 'Unexpected redundant left brackets found in {}'.format(placeholder)) else: patch = ''.join(['}'] * (lcount - rcount)) return placeholder + patch
[ "def", "fix_brackets", "(", "placeholder", ":", "str", ")", "->", "str", ":", "lcount", "=", "placeholder", ".", "count", "(", "'{'", ")", "rcount", "=", "placeholder", ".", "count", "(", "'}'", ")", "if", "lcount", "<", "rcount", ":", "raise", "Runtim...
https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/orchestration/kubeflow/utils.py#L36-L58
microsoft/nni
31f11f51249660930824e888af0d4e022823285c
examples/nas/oneshot/pfld/lib/ops.py
python
choice_blocks
(layers_configs, stage_ops)
return op_list
Create list of layer candidates for NNI one-shot NAS. Parameters ---------- layers_configs : list the layer config: [input_channel, output_channel, stride, height] stage_ops : dict the pairs of op name and layer operator Returns ------- output: list list of layer operators
Create list of layer candidates for NNI one-shot NAS.
[ "Create", "list", "of", "layer", "candidates", "for", "NNI", "one", "-", "shot", "NAS", "." ]
def choice_blocks(layers_configs, stage_ops): """ Create list of layer candidates for NNI one-shot NAS. Parameters ---------- layers_configs : list the layer config: [input_channel, output_channel, stride, height] stage_ops : dict the pairs of op name and layer operator Returns ------- output: list list of layer operators """ ops_names = [op for op in stage_ops] fm = {"fm_size": layers_configs[3]} op_list = [stage_ops[op](*layers_configs[0:3], **fm) for op in ops_names] return op_list
[ "def", "choice_blocks", "(", "layers_configs", ",", "stage_ops", ")", ":", "ops_names", "=", "[", "op", "for", "op", "in", "stage_ops", "]", "fm", "=", "{", "\"fm_size\"", ":", "layers_configs", "[", "3", "]", "}", "op_list", "=", "[", "stage_ops", "[", ...
https://github.com/microsoft/nni/blob/31f11f51249660930824e888af0d4e022823285c/examples/nas/oneshot/pfld/lib/ops.py#L436-L456
AXErunners/electrum-axe
7ef05088c0edaf0688fb167df353d6da619ebf2f
electrum_axe/gui/qt/main_window.py
python
ElectrumWindow.check_send_tab_outputs_and_show_errors
(self, outputs)
return False
Returns whether there are errors with outputs. Also shows error dialog to user if so.
Returns whether there are errors with outputs. Also shows error dialog to user if so.
[ "Returns", "whether", "there", "are", "errors", "with", "outputs", ".", "Also", "shows", "error", "dialog", "to", "user", "if", "so", "." ]
def check_send_tab_outputs_and_show_errors(self, outputs) -> bool: """Returns whether there are errors with outputs. Also shows error dialog to user if so. """ pr = self.payment_request if pr: if pr.has_expired(): self.show_error(_('Payment request has expired')) return True if not pr: errors = self.payto_e.get_errors() if errors: self.show_warning(_("Invalid Lines found:") + "\n\n" + '\n'.join([ _("Line #") + str(x[0]+1) + ": " + x[1] for x in errors])) return True if self.payto_e.is_alias and self.payto_e.validated is False: alias = self.payto_e.toPlainText() msg = _('WARNING: the alias "{}" could not be validated via an additional ' 'security check, DNSSEC, and thus may not be correct.').format(alias) + '\n' msg += _('Do you wish to continue?') if not self.question(msg): return True if not outputs: self.show_error(_('No outputs')) return True for o in outputs: if o.address is None: self.show_error(_('Axe Address is None')) return True if o.type == TYPE_ADDRESS and not bitcoin.is_address(o.address): self.show_error(_('Invalid Axe Address')) return True if o.value is None: self.show_error(_('Invalid Amount')) return True return False
[ "def", "check_send_tab_outputs_and_show_errors", "(", "self", ",", "outputs", ")", "->", "bool", ":", "pr", "=", "self", ".", "payment_request", "if", "pr", ":", "if", "pr", ".", "has_expired", "(", ")", ":", "self", ".", "show_error", "(", "_", "(", "'P...
https://github.com/AXErunners/electrum-axe/blob/7ef05088c0edaf0688fb167df353d6da619ebf2f/electrum_axe/gui/qt/main_window.py#L1903-L1942
GNS3/gns3-gui
da8adbaa18ab60e053af2a619efd468f4c8950f3
gns3/dialogs/snapshots_dialog.py
python
SnapshotsDialog._deleteSnapshotSlot
(self)
Slot to delete a snapshot.
Slot to delete a snapshot.
[ "Slot", "to", "delete", "a", "snapshot", "." ]
def _deleteSnapshotSlot(self): """ Slot to delete a snapshot. """ item = self.uiSnapshotsList.currentItem() if item: snapshot_id = item.data(QtCore.Qt.UserRole) Controller.instance().delete("/projects/{}/snapshots/{}".format(self._project.id(), snapshot_id), self._deleteSnapshotsCallback)
[ "def", "_deleteSnapshotSlot", "(", "self", ")", ":", "item", "=", "self", ".", "uiSnapshotsList", ".", "currentItem", "(", ")", "if", "item", ":", "snapshot_id", "=", "item", ".", "data", "(", "QtCore", ".", "Qt", ".", "UserRole", ")", "Controller", ".",...
https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/dialogs/snapshots_dialog.py#L103-L111
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/relay/op/contrib/tensorrt.py
python
reshape_annotate_fn
(expr)
return True
Check if reshape is supported by TensorRT.
Check if reshape is supported by TensorRT.
[ "Check", "if", "reshape", "is", "supported", "by", "TensorRT", "." ]
def reshape_annotate_fn(expr): # pylint: disable=unused-variable """Check if reshape is supported by TensorRT.""" attrs, args = expr.attrs, expr.args if args[0].checked_type.dtype != "float32": logger.info("Only float32 inputs are supported for TensorRT.") return False if any([x < -1 for x in map(int, attrs.newshape)]): logger.info("reshape: new shape dims must be explicit.") return False if get_tensorrt_use_implicit_batch_mode(): shape = args[0].checked_type.shape new_shape = attrs.newshape if len(new_shape) == 0 or len(shape) == 0: logger.info("reshape: Can't reshape to or from scalar.") return False dynamic_reshape = any([isinstance(x, tvm.tir.expr.Any) for x in shape]) if dynamic_reshape: # Make sure that the batch dim is unmodified. if int(new_shape[0]) < 0: for shape_val, new_shape_val in zip(shape[1:], new_shape[1:]): if not ( isinstance(shape_val, (int, tvm.tir.expr.IntImm)) and isinstance(new_shape_val, (int, tvm.tir.expr.IntImm)) and int(shape_val) == int(new_shape_val) ): return False elif int(new_shape[0]) > 0: # Currently we only allow dim[0] to be Any, so this branch will always be False if not ( isinstance(shape[0], (int, tvm.tir.expr.IntImm)) and isinstance(new_shape[0], (int, tvm.tir.expr.IntImm)) and int(shape[0]) == int(new_shape[0]) ): return False return True shape = list(map(int, shape)) new_shape = list(map(int, new_shape)) # TRT cannot modify batch dimension. original_volume = np.prod(shape) # First, resolve 0. for i, value in enumerate(new_shape): if value == 0: new_shape[i] = shape[i] # Resolve -1. for i, value in enumerate(new_shape): if value == -1: new_shape[i] = original_volume // np.prod([x for x in new_shape if x != -1]) # Remove batch dimension and see if volumes match if shape[0] != new_shape[0]: logger.info("reshape: can't modify batch dimension.") return False return True
[ "def", "reshape_annotate_fn", "(", "expr", ")", ":", "# pylint: disable=unused-variable", "attrs", ",", "args", "=", "expr", ".", "attrs", ",", "expr", ".", "args", "if", "args", "[", "0", "]", ".", "checked_type", ".", "dtype", "!=", "\"float32\"", ":", "...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/relay/op/contrib/tensorrt.py#L679-L732
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/code.py
python
InteractiveConsole.interact
(self, banner=None)
Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!).
Closely emulate the interactive Python console.
[ "Closely", "emulate", "the", "interactive", "Python", "console", "." ]
def interact(self, banner=None): """Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!). """ try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: self.write("Python %s on %s\n%s\n(%s)\n" % (sys.version, sys.platform, cprt, self.__class__.__name__)) else: self.write("%s\n" % str(banner)) more = 0 while 1: try: if more: prompt = sys.ps2 else: prompt = sys.ps1 try: line = self.raw_input(prompt) # Can be None if sys.stdin was redefined encoding = getattr(sys.stdin, "encoding", None) if encoding and not isinstance(line, unicode): line = line.decode(encoding) except EOFError: self.write("\n") break else: more = self.push(line) except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") self.resetbuffer() more = 0
[ "def", "interact", "(", "self", ",", "banner", "=", "None", ")", ":", "try", ":", "sys", ".", "ps1", "except", "AttributeError", ":", "sys", ".", "ps1", "=", "\">>> \"", "try", ":", "sys", ".", "ps2", "except", "AttributeError", ":", "sys", ".", "ps2...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/code.py#L200-L247
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
postgres/datadog_checks/postgres/config_models/defaults.py
python
instance_data_directory
(field, value)
return '/usr/local/pgsql/data'
[]
def instance_data_directory(field, value): return '/usr/local/pgsql/data'
[ "def", "instance_data_directory", "(", "field", ",", "value", ")", ":", "return", "'/usr/local/pgsql/data'" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/postgres/datadog_checks/postgres/config_models/defaults.py#L53-L54
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
python/ray/_private/runtime_env/conda.py
python
_get_conda_dict_with_ray_inserted
( runtime_env: RuntimeEnv, logger: Optional[logging.Logger] = default_logger)
return conda_dict
Returns the conda spec with the Ray and `python` dependency inserted.
Returns the conda spec with the Ray and `python` dependency inserted.
[ "Returns", "the", "conda", "spec", "with", "the", "Ray", "and", "python", "dependency", "inserted", "." ]
def _get_conda_dict_with_ray_inserted( runtime_env: RuntimeEnv, logger: Optional[logging.Logger] = default_logger) -> Dict[str, Any]: """Returns the conda spec with the Ray and `python` dependency inserted.""" conda_dict = json.loads(runtime_env.conda_config()) assert conda_dict is not None ray_pip = current_ray_pip_specifier(logger=logger) if ray_pip: extra_pip_dependencies = [ray_pip, "ray[default]"] elif runtime_env.get_extension("_inject_current_ray") == "True": extra_pip_dependencies = ( _resolve_install_from_source_ray_dependencies()) else: extra_pip_dependencies = [] conda_dict = inject_dependencies(conda_dict, _current_py_version(), extra_pip_dependencies) return conda_dict
[ "def", "_get_conda_dict_with_ray_inserted", "(", "runtime_env", ":", "RuntimeEnv", ",", "logger", ":", "Optional", "[", "logging", ".", "Logger", "]", "=", "default_logger", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "conda_dict", "=", "json", ".",...
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/_private/runtime_env/conda.py#L208-L225
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/idlelib/window.py
python
WindowList.add_windows_to_menu
(self, menu)
[]
def add_windows_to_menu(self, menu): list = [] for key in self.dict: window = self.dict[key] try: title = window.get_title() except TclError: continue list.append((title, key, window)) list.sort() for title, key, window in list: menu.add_command(label=title, command=window.wakeup)
[ "def", "add_windows_to_menu", "(", "self", ",", "menu", ")", ":", "list", "=", "[", "]", "for", "key", "in", "self", ".", "dict", ":", "window", "=", "self", ".", "dict", "[", "key", "]", "try", ":", "title", "=", "window", ".", "get_title", "(", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/idlelib/window.py#L23-L34
Radu-Raicea/Dockerized-Flask
cc7478c70985d5971f2ac983e0e36939ecc2a545
flask/manage.py
python
test_one
(test_file)
Runs the unittest without generating a coverage report. Enter 'docker-compose run --rm flask python manage.py test_one <NAME_OF_FILE>' to run only one test file in the 'tests' directory. It provides no coverage report. Example: 'docker-compose run --rm flask python manage.py test_one test_website' Note that you do not need to put the extension of the test file. :return int: 0 if all tests pass, 1 if not
Runs the unittest without generating a coverage report.
[ "Runs", "the", "unittest", "without", "generating", "a", "coverage", "report", "." ]
def test_one(test_file): """ Runs the unittest without generating a coverage report. Enter 'docker-compose run --rm flask python manage.py test_one <NAME_OF_FILE>' to run only one test file in the 'tests' directory. It provides no coverage report. Example: 'docker-compose run --rm flask python manage.py test_one test_website' Note that you do not need to put the extension of the test file. :return int: 0 if all tests pass, 1 if not """ tests = unittest.TestLoader().discover('tests', pattern=test_file + '.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 else: return 1
[ "def", "test_one", "(", "test_file", ")", ":", "tests", "=", "unittest", ".", "TestLoader", "(", ")", ".", "discover", "(", "'tests'", ",", "pattern", "=", "test_file", "+", "'.py'", ")", "result", "=", "unittest", ".", "TextTestRunner", "(", "verbosity", ...
https://github.com/Radu-Raicea/Dockerized-Flask/blob/cc7478c70985d5971f2ac983e0e36939ecc2a545/flask/manage.py#L88-L106