nwo
stringlengths
5
58
sha
stringlengths
40
40
path
stringlengths
5
172
language
stringclasses
1 value
identifier
stringlengths
1
100
parameters
stringlengths
2
3.5k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
21.5k
docstring
stringlengths
2
17k
docstring_summary
stringlengths
0
6.58k
docstring_tokens
sequence
function
stringlengths
35
55.6k
function_tokens
sequence
url
stringlengths
89
269
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/Sqlmap/thirdparty/odict/odict.py
python
_OrderedDict.clear
(self)
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.clear() >>> d OrderedDict([])
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.clear() >>> d OrderedDict([])
[ ">>>", "d", "=", "OrderedDict", "(((", "1", "3", ")", "(", "3", "2", ")", "(", "2", "1", ")))", ">>>", "d", ".", "clear", "()", ">>>", "d", "OrderedDict", "(", "[]", ")" ]
def clear(self): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.clear() >>> d OrderedDict([]) """ dict.clear(self) self._sequence = []
[ "def", "clear", "(", "self", ")", ":", "dict", ".", "clear", "(", "self", ")", "self", ".", "_sequence", "=", "[", "]" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/thirdparty/odict/odict.py#L583-L591
nprapps/app-template
54c79412d05678b7de0080832cd041a90e4d9112
render_utils.py
python
urlencode_filter
(s)
return Markup(s)
Filter to urlencode strings.
Filter to urlencode strings.
[ "Filter", "to", "urlencode", "strings", "." ]
def urlencode_filter(s): """ Filter to urlencode strings. """ if type(s) == 'Markup': s = s.unescape() # Evaulate COPY elements if type(s) is not unicode: s = unicode(s) s = s.encode('utf8') s = urllib.quote_plus(s) return Markup(s)
[ "def", "urlencode_filter", "(", "s", ")", ":", "if", "type", "(", "s", ")", "==", "'Markup'", ":", "s", "=", "s", ".", "unescape", "(", ")", "# Evaulate COPY elements", "if", "type", "(", "s", ")", "is", "not", "unicode", ":", "s", "=", "unicode", "(", "s", ")", "s", "=", "s", ".", "encode", "(", "'utf8'", ")", "s", "=", "urllib", ".", "quote_plus", "(", "s", ")", "return", "Markup", "(", "s", ")" ]
https://github.com/nprapps/app-template/blob/54c79412d05678b7de0080832cd041a90e4d9112/render_utils.py#L200-L214
openlayers/ol2
ab7a809ebad7055d9ada4170aed582d7be4a7b77
tools/BeautifulSoup.py
python
PageElement.setup
(self, parent=None, previous=None)
Sets up the initial relations between this element and other elements.
Sets up the initial relations between this element and other elements.
[ "Sets", "up", "the", "initial", "relations", "between", "this", "element", "and", "other", "elements", "." ]
def setup(self, parent=None, previous=None): """Sets up the initial relations between this element and other elements.""" self.parent = parent self.previous = previous self.next = None self.previousSibling = None self.nextSibling = None if self.parent and self.parent.contents: self.previousSibling = self.parent.contents[-1] self.previousSibling.nextSibling = self
[ "def", "setup", "(", "self", ",", "parent", "=", "None", ",", "previous", "=", "None", ")", ":", "self", ".", "parent", "=", "parent", "self", ".", "previous", "=", "previous", "self", ".", "next", "=", "None", "self", ".", "previousSibling", "=", "None", "self", ".", "nextSibling", "=", "None", "if", "self", ".", "parent", "and", "self", ".", "parent", ".", "contents", ":", "self", ".", "previousSibling", "=", "self", ".", "parent", ".", "contents", "[", "-", "1", "]", "self", ".", "previousSibling", ".", "nextSibling", "=", "self" ]
https://github.com/openlayers/ol2/blob/ab7a809ebad7055d9ada4170aed582d7be4a7b77/tools/BeautifulSoup.py#L72-L82
facebookarchive/nuclide
2a2a0a642d136768b7d2a6d35a652dc5fb77d70a
modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/jedi/api/classes.py
python
BaseDefinition.get_line_code
(self, before=0, after=0)
return ''.join(lines[start_index:index + after + 1])
Returns the line of code where this object was defined. :param before: Add n lines before the current line to the output. :param after: Add n lines after the current line to the output. :return str: Returns the line(s) of code or an empty string if it's a builtin.
Returns the line of code where this object was defined.
[ "Returns", "the", "line", "of", "code", "where", "this", "object", "was", "defined", "." ]
def get_line_code(self, before=0, after=0): """ Returns the line of code where this object was defined. :param before: Add n lines before the current line to the output. :param after: Add n lines after the current line to the output. :return str: Returns the line(s) of code or an empty string if it's a builtin. """ if self.in_builtin_module(): return '' lines = self._name.get_root_context().code_lines index = self._name.start_pos[0] - 1 start_index = max(index - before, 0) return ''.join(lines[start_index:index + after + 1])
[ "def", "get_line_code", "(", "self", ",", "before", "=", "0", ",", "after", "=", "0", ")", ":", "if", "self", ".", "in_builtin_module", "(", ")", ":", "return", "''", "lines", "=", "self", ".", "_name", ".", "get_root_context", "(", ")", ".", "code_lines", "index", "=", "self", ".", "_name", ".", "start_pos", "[", "0", "]", "-", "1", "start_index", "=", "max", "(", "index", "-", "before", ",", "0", ")", "return", "''", ".", "join", "(", "lines", "[", "start_index", ":", "index", "+", "after", "+", "1", "]", ")" ]
https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/jedi/api/classes.py#L365-L382
nodejs/node-chakracore
770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43
deps/v8/third_party/jinja2/lexer.py
python
get_lexer
(environment)
return lexer
Return a lexer which is probably cached.
Return a lexer which is probably cached.
[ "Return", "a", "lexer", "which", "is", "probably", "cached", "." ]
def get_lexer(environment): """Return a lexer which is probably cached.""" key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_blocks, environment.lstrip_blocks, environment.newline_sequence, environment.keep_trailing_newline) lexer = _lexer_cache.get(key) if lexer is None: lexer = Lexer(environment) _lexer_cache[key] = lexer return lexer
[ "def", "get_lexer", "(", "environment", ")", ":", "key", "=", "(", "environment", ".", "block_start_string", ",", "environment", ".", "block_end_string", ",", "environment", ".", "variable_start_string", ",", "environment", ".", "variable_end_string", ",", "environment", ".", "comment_start_string", ",", "environment", ".", "comment_end_string", ",", "environment", ".", "line_statement_prefix", ",", "environment", ".", "line_comment_prefix", ",", "environment", ".", "trim_blocks", ",", "environment", ".", "lstrip_blocks", ",", "environment", ".", "newline_sequence", ",", "environment", ".", "keep_trailing_newline", ")", "lexer", "=", "_lexer_cache", ".", "get", "(", "key", ")", "if", "lexer", "is", "None", ":", "lexer", "=", "Lexer", "(", "environment", ")", "_lexer_cache", "[", "key", "]", "=", "lexer", "return", "lexer" ]
https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/v8/third_party/jinja2/lexer.py#L391-L409
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
3rd_party/python3/site-packages/cherrypy/_helper.py
python
popargs
(*args, **kwargs)
return decorated
Decorate _cp_dispatch. (cherrypy.dispatch.Dispatcher.dispatch_method_name) Optional keyword argument: handler=(Object or Function) Provides a _cp_dispatch function that pops off path segments into cherrypy.request.params under the names specified. The dispatch is then forwarded on to the next vpath element. Note that any existing (and exposed) member function of the class that popargs is applied to will override that value of the argument. For instance, if you have a method named "list" on the class decorated with popargs, then accessing "/list" will call that function instead of popping it off as the requested parameter. This restriction applies to all _cp_dispatch functions. The only way around this restriction is to create a "blank class" whose only function is to provide _cp_dispatch. If there are path elements after the arguments, or more arguments are requested than are available in the vpath, then the 'handler' keyword argument specifies the next object to handle the parameterized request. If handler is not specified or is None, then self is used. If handler is a function rather than an instance, then that function will be called with the args specified and the return value from that function used as the next object INSTEAD of adding the parameters to cherrypy.request.args. This decorator may be used in one of two ways: As a class decorator: @cherrypy.popargs('year', 'month', 'day') class Blog: def index(self, year=None, month=None, day=None): #Process the parameters here; any url like #/, /2009, /2009/12, or /2009/12/31 #will fill in the appropriate parameters. def create(self): #This link will still be available at /create. Defined functions #take precedence over arguments. Or as a member of a class: class Blog: _cp_dispatch = cherrypy.popargs('year', 'month', 'day') #... The handler argument may be used to mix arguments with built in functions. For instance, the following setup allows different activities at the day, month, and year level: class DayHandler: def index(self, year, month, day): #Do something with this day; probably list entries def delete(self, year, month, day): #Delete all entries for this day @cherrypy.popargs('day', handler=DayHandler()) class MonthHandler: def index(self, year, month): #Do something with this month; probably list entries def delete(self, year, month): #Delete all entries for this month @cherrypy.popargs('month', handler=MonthHandler()) class YearHandler: def index(self, year): #Do something with this year #... @cherrypy.popargs('year', handler=YearHandler()) class Root: def index(self): #...
Decorate _cp_dispatch.
[ "Decorate", "_cp_dispatch", "." ]
def popargs(*args, **kwargs): """Decorate _cp_dispatch. (cherrypy.dispatch.Dispatcher.dispatch_method_name) Optional keyword argument: handler=(Object or Function) Provides a _cp_dispatch function that pops off path segments into cherrypy.request.params under the names specified. The dispatch is then forwarded on to the next vpath element. Note that any existing (and exposed) member function of the class that popargs is applied to will override that value of the argument. For instance, if you have a method named "list" on the class decorated with popargs, then accessing "/list" will call that function instead of popping it off as the requested parameter. This restriction applies to all _cp_dispatch functions. The only way around this restriction is to create a "blank class" whose only function is to provide _cp_dispatch. If there are path elements after the arguments, or more arguments are requested than are available in the vpath, then the 'handler' keyword argument specifies the next object to handle the parameterized request. If handler is not specified or is None, then self is used. If handler is a function rather than an instance, then that function will be called with the args specified and the return value from that function used as the next object INSTEAD of adding the parameters to cherrypy.request.args. This decorator may be used in one of two ways: As a class decorator: @cherrypy.popargs('year', 'month', 'day') class Blog: def index(self, year=None, month=None, day=None): #Process the parameters here; any url like #/, /2009, /2009/12, or /2009/12/31 #will fill in the appropriate parameters. def create(self): #This link will still be available at /create. Defined functions #take precedence over arguments. Or as a member of a class: class Blog: _cp_dispatch = cherrypy.popargs('year', 'month', 'day') #... The handler argument may be used to mix arguments with built in functions. For instance, the following setup allows different activities at the day, month, and year level: class DayHandler: def index(self, year, month, day): #Do something with this day; probably list entries def delete(self, year, month, day): #Delete all entries for this day @cherrypy.popargs('day', handler=DayHandler()) class MonthHandler: def index(self, year, month): #Do something with this month; probably list entries def delete(self, year, month): #Delete all entries for this month @cherrypy.popargs('month', handler=MonthHandler()) class YearHandler: def index(self, year): #Do something with this year #... @cherrypy.popargs('year', handler=YearHandler()) class Root: def index(self): #... """ # Since keyword arg comes after *args, we have to process it ourselves # for lower versions of python. handler = None handler_call = False for k, v in kwargs.items(): if k == 'handler': handler = v else: tm = "cherrypy.popargs() got an unexpected keyword argument '{0}'" raise TypeError(tm.format(k)) import inspect if handler is not None \ and (hasattr(handler, '__call__') or inspect.isclass(handler)): handler_call = True def decorated(cls_or_self=None, vpath=None): if inspect.isclass(cls_or_self): # cherrypy.popargs is a class decorator cls = cls_or_self name = cherrypy.dispatch.Dispatcher.dispatch_method_name setattr(cls, name, decorated) return cls # We're in the actual function self = cls_or_self parms = {} for arg in args: if not vpath: break parms[arg] = vpath.pop(0) if handler is not None: if handler_call: return handler(**parms) else: cherrypy.request.params.update(parms) return handler cherrypy.request.params.update(parms) # If we are the ultimate handler, then to prevent our _cp_dispatch # from being called again, we will resolve remaining elements through # getattr() directly. if vpath: return getattr(self, vpath.pop(0), None) else: return self return decorated
[ "def", "popargs", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Since keyword arg comes after *args, we have to process it ourselves", "# for lower versions of python.", "handler", "=", "None", "handler_call", "=", "False", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "==", "'handler'", ":", "handler", "=", "v", "else", ":", "tm", "=", "\"cherrypy.popargs() got an unexpected keyword argument '{0}'\"", "raise", "TypeError", "(", "tm", ".", "format", "(", "k", ")", ")", "import", "inspect", "if", "handler", "is", "not", "None", "and", "(", "hasattr", "(", "handler", ",", "'__call__'", ")", "or", "inspect", ".", "isclass", "(", "handler", ")", ")", ":", "handler_call", "=", "True", "def", "decorated", "(", "cls_or_self", "=", "None", ",", "vpath", "=", "None", ")", ":", "if", "inspect", ".", "isclass", "(", "cls_or_self", ")", ":", "# cherrypy.popargs is a class decorator", "cls", "=", "cls_or_self", "name", "=", "cherrypy", ".", "dispatch", ".", "Dispatcher", ".", "dispatch_method_name", "setattr", "(", "cls", ",", "name", ",", "decorated", ")", "return", "cls", "# We're in the actual function", "self", "=", "cls_or_self", "parms", "=", "{", "}", "for", "arg", "in", "args", ":", "if", "not", "vpath", ":", "break", "parms", "[", "arg", "]", "=", "vpath", ".", "pop", "(", "0", ")", "if", "handler", "is", "not", "None", ":", "if", "handler_call", ":", "return", "handler", "(", "*", "*", "parms", ")", "else", ":", "cherrypy", ".", "request", ".", "params", ".", "update", "(", "parms", ")", "return", "handler", "cherrypy", ".", "request", ".", "params", ".", "update", "(", "parms", ")", "# If we are the ultimate handler, then to prevent our _cp_dispatch", "# from being called again, we will resolve remaining elements through", "# getattr() directly.", "if", "vpath", ":", "return", "getattr", "(", "self", ",", "vpath", ".", "pop", "(", "0", ")", ",", "None", ")", "else", ":", "return", "self", "return", "decorated" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python3/site-packages/cherrypy/_helper.py#L55-L185
Opentrons/opentrons
466e0567065d8773a81c25cd1b5c7998e00adf2c
api/src/opentrons/hardware_control/api.py
python
API.blow_out
(self, mount: Union[top_types.Mount, PipettePair])
Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette
Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette
[ "Force", "any", "remaining", "liquid", "to", "dispense", ".", "The", "liquid", "will", "be", "dispensed", "at", "the", "current", "location", "of", "pipette" ]
async def blow_out(self, mount: Union[top_types.Mount, PipettePair]): """ Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette """ instruments = self._instruments_for(mount) self._ready_for_tip_action(instruments, HardwareAction.BLOWOUT) plunger_currents = { Axis.of_plunger(instr[1]): instr[0].config.plunger_current for instr in instruments } blow_out = tuple(instr[0].config.blow_out for instr in instruments) self._backend.set_active_current(plunger_currents) speed = max( self._plunger_speed(instr[0], instr[0].blow_out_flow_rate, "dispense") for instr in instruments ) try: await self._move_plunger(mount, blow_out, speed=speed) except Exception: self._log.exception("Blow out failed") raise finally: for instr in instruments: instr[0].set_current_volume(0) instr[0].ready_to_aspirate = False
[ "async", "def", "blow_out", "(", "self", ",", "mount", ":", "Union", "[", "top_types", ".", "Mount", ",", "PipettePair", "]", ")", ":", "instruments", "=", "self", ".", "_instruments_for", "(", "mount", ")", "self", ".", "_ready_for_tip_action", "(", "instruments", ",", "HardwareAction", ".", "BLOWOUT", ")", "plunger_currents", "=", "{", "Axis", ".", "of_plunger", "(", "instr", "[", "1", "]", ")", ":", "instr", "[", "0", "]", ".", "config", ".", "plunger_current", "for", "instr", "in", "instruments", "}", "blow_out", "=", "tuple", "(", "instr", "[", "0", "]", ".", "config", ".", "blow_out", "for", "instr", "in", "instruments", ")", "self", ".", "_backend", ".", "set_active_current", "(", "plunger_currents", ")", "speed", "=", "max", "(", "self", ".", "_plunger_speed", "(", "instr", "[", "0", "]", ",", "instr", "[", "0", "]", ".", "blow_out_flow_rate", ",", "\"dispense\"", ")", "for", "instr", "in", "instruments", ")", "try", ":", "await", "self", ".", "_move_plunger", "(", "mount", ",", "blow_out", ",", "speed", "=", "speed", ")", "except", "Exception", ":", "self", ".", "_log", ".", "exception", "(", "\"Blow out failed\"", ")", "raise", "finally", ":", "for", "instr", "in", "instruments", ":", "instr", "[", "0", "]", ".", "set_current_volume", "(", "0", ")", "instr", "[", "0", "]", ".", "ready_to_aspirate", "=", "False" ]
https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/src/opentrons/hardware_control/api.py#L1585-L1611
IonicChina/ioniclub
208d5298939672ef44076bb8a7e8e6df5278e286
node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/MSVSToolFile.py
python
Writer.WriteIfChanged
(self)
Writes the tool file.
Writes the tool file.
[ "Writes", "the", "tool", "file", "." ]
def WriteIfChanged(self): """Writes the tool file.""" content = ['VisualStudioToolFile', {'Version': '8.00', 'Name': self.name }, self.rules_section ] easy_xml.WriteXmlIfChanged(content, self.tool_file_path, encoding="Windows-1252")
[ "def", "WriteIfChanged", "(", "self", ")", ":", "content", "=", "[", "'VisualStudioToolFile'", ",", "{", "'Version'", ":", "'8.00'", ",", "'Name'", ":", "self", ".", "name", "}", ",", "self", ".", "rules_section", "]", "easy_xml", ".", "WriteXmlIfChanged", "(", "content", ",", "self", ".", "tool_file_path", ",", "encoding", "=", "\"Windows-1252\"", ")" ]
https://github.com/IonicChina/ioniclub/blob/208d5298939672ef44076bb8a7e8e6df5278e286/node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/MSVSToolFile.py#L49-L58
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/Sqlmap/lib/core/common.py
python
hashDBRetrieve
(key, unserialize=False, checkConf=False)
return retVal
Helper function for restoring session data from HashDB
Helper function for restoring session data from HashDB
[ "Helper", "function", "for", "restoring", "session", "data", "from", "HashDB" ]
def hashDBRetrieve(key, unserialize=False, checkConf=False): """ Helper function for restoring session data from HashDB """ _ = "%s%s%s" % (conf.url or "%s%s" % (conf.hostname, conf.port), key, HASHDB_MILESTONE_VALUE) retVal = conf.hashDB.retrieve(_, unserialize) if kb.resumeValues and not (checkConf and any((conf.flushSession, conf.freshQueries))) else None if not kb.inferenceMode and not kb.fileReadMode and any(_ in (retVal or "") for _ in (PARTIAL_VALUE_MARKER, PARTIAL_HEX_VALUE_MARKER)): retVal = None return retVal
[ "def", "hashDBRetrieve", "(", "key", ",", "unserialize", "=", "False", ",", "checkConf", "=", "False", ")", ":", "_", "=", "\"%s%s%s\"", "%", "(", "conf", ".", "url", "or", "\"%s%s\"", "%", "(", "conf", ".", "hostname", ",", "conf", ".", "port", ")", ",", "key", ",", "HASHDB_MILESTONE_VALUE", ")", "retVal", "=", "conf", ".", "hashDB", ".", "retrieve", "(", "_", ",", "unserialize", ")", "if", "kb", ".", "resumeValues", "and", "not", "(", "checkConf", "and", "any", "(", "(", "conf", ".", "flushSession", ",", "conf", ".", "freshQueries", ")", ")", ")", "else", "None", "if", "not", "kb", ".", "inferenceMode", "and", "not", "kb", ".", "fileReadMode", "and", "any", "(", "_", "in", "(", "retVal", "or", "\"\"", ")", "for", "_", "in", "(", "PARTIAL_VALUE_MARKER", ",", "PARTIAL_HEX_VALUE_MARKER", ")", ")", ":", "retVal", "=", "None", "return", "retVal" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/lib/core/common.py#L3740-L3749
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
addons/crm/models/crm_lead.py
python
Lead._merge_dependences_calendar_events
(self, opportunities)
return meetings.write({ 'res_id': self.id, 'opportunity_id': self.id, })
Move calender.event from the given opportunities to the current one. `self` is the crm.lead record destination for event of `opportunities`. :param opportunities: see ``merge_dependences``
Move calender.event from the given opportunities to the current one. `self` is the crm.lead record destination for event of `opportunities`. :param opportunities: see ``merge_dependences``
[ "Move", "calender", ".", "event", "from", "the", "given", "opportunities", "to", "the", "current", "one", ".", "self", "is", "the", "crm", ".", "lead", "record", "destination", "for", "event", "of", "opportunities", ".", ":", "param", "opportunities", ":", "see", "merge_dependences" ]
def _merge_dependences_calendar_events(self, opportunities): """ Move calender.event from the given opportunities to the current one. `self` is the crm.lead record destination for event of `opportunities`. :param opportunities: see ``merge_dependences`` """ self.ensure_one() meetings = self.env['calendar.event'].search([('opportunity_id', 'in', opportunities.ids)]) return meetings.write({ 'res_id': self.id, 'opportunity_id': self.id, })
[ "def", "_merge_dependences_calendar_events", "(", "self", ",", "opportunities", ")", ":", "self", ".", "ensure_one", "(", ")", "meetings", "=", "self", ".", "env", "[", "'calendar.event'", "]", ".", "search", "(", "[", "(", "'opportunity_id'", ",", "'in'", ",", "opportunities", ".", "ids", ")", "]", ")", "return", "meetings", ".", "write", "(", "{", "'res_id'", ":", "self", ".", "id", ",", "'opportunity_id'", ":", "self", ".", "id", ",", "}", ")" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/crm/models/crm_lead.py#L1436-L1446
PiotrDabkowski/Js2Py
b16d7ce90ac9c03358010c1599c3e87698c9993f
js2py/evaljs.py
python
translate_file
(input_path, output_path)
Translates input JS file to python and saves the it to the output path. It appends some convenience code at the end so that it is easy to import JS objects. For example we have a file 'example.js' with: var a = function(x) {return x} translate_file('example.js', 'example.py') Now example.py can be easily importend and used: >>> from example import example >>> example.a(30) 30
Translates input JS file to python and saves the it to the output path. It appends some convenience code at the end so that it is easy to import JS objects.
[ "Translates", "input", "JS", "file", "to", "python", "and", "saves", "the", "it", "to", "the", "output", "path", ".", "It", "appends", "some", "convenience", "code", "at", "the", "end", "so", "that", "it", "is", "easy", "to", "import", "JS", "objects", "." ]
def translate_file(input_path, output_path): ''' Translates input JS file to python and saves the it to the output path. It appends some convenience code at the end so that it is easy to import JS objects. For example we have a file 'example.js' with: var a = function(x) {return x} translate_file('example.js', 'example.py') Now example.py can be easily importend and used: >>> from example import example >>> example.a(30) 30 ''' js = get_file_contents(input_path) py_code = translate_js(js) lib_name = os.path.basename(output_path).split('.')[0] head = '__all__ = [%s]\n\n# Don\'t look below, you will not understand this Python code :) I don\'t.\n\n' % repr( lib_name) tail = '\n\n# Add lib to the module scope\n%s = var.to_python()' % lib_name out = head + py_code + tail write_file_contents(output_path, out)
[ "def", "translate_file", "(", "input_path", ",", "output_path", ")", ":", "js", "=", "get_file_contents", "(", "input_path", ")", "py_code", "=", "translate_js", "(", "js", ")", "lib_name", "=", "os", ".", "path", ".", "basename", "(", "output_path", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "head", "=", "'__all__ = [%s]\\n\\n# Don\\'t look below, you will not understand this Python code :) I don\\'t.\\n\\n'", "%", "repr", "(", "lib_name", ")", "tail", "=", "'\\n\\n# Add lib to the module scope\\n%s = var.to_python()'", "%", "lib_name", "out", "=", "head", "+", "py_code", "+", "tail", "write_file_contents", "(", "output_path", ",", "out", ")" ]
https://github.com/PiotrDabkowski/Js2Py/blob/b16d7ce90ac9c03358010c1599c3e87698c9993f/js2py/evaljs.py#L60-L81
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
3rd_party/python3/site-packages/cherrypy/_cptree.py
python
Application.get_serving
(self, local, remote, scheme, sproto)
return req, resp
Create and return a Request and Response object.
Create and return a Request and Response object.
[ "Create", "and", "return", "a", "Request", "and", "Response", "object", "." ]
def get_serving(self, local, remote, scheme, sproto): """Create and return a Request and Response object.""" req = self.request_class(local, remote, scheme, sproto) req.app = self for name, toolbox in self.toolboxes.items(): req.namespaces[name] = toolbox resp = self.response_class() cherrypy.serving.load(req, resp) cherrypy.engine.publish('acquire_thread') cherrypy.engine.publish('before_request') return req, resp
[ "def", "get_serving", "(", "self", ",", "local", ",", "remote", ",", "scheme", ",", "sproto", ")", ":", "req", "=", "self", ".", "request_class", "(", "local", ",", "remote", ",", "scheme", ",", "sproto", ")", "req", ".", "app", "=", "self", "for", "name", ",", "toolbox", "in", "self", ".", "toolboxes", ".", "items", "(", ")", ":", "req", ".", "namespaces", "[", "name", "]", "=", "toolbox", "resp", "=", "self", ".", "response_class", "(", ")", "cherrypy", ".", "serving", ".", "load", "(", "req", ",", "resp", ")", "cherrypy", ".", "engine", ".", "publish", "(", "'acquire_thread'", ")", "cherrypy", ".", "engine", ".", "publish", "(", "'before_request'", ")", "return", "req", ",", "resp" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python3/site-packages/cherrypy/_cptree.py#L138-L151
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py
python
IsValidTargetForWrapper
(target_extras, executable_target_pattern, spec)
return False
Limit targets for Xcode wrapper. Xcode sometimes performs poorly with too many targets, so only include proper executable targets, with filters to customize. Arguments: target_extras: Regular expression to always add, matching any target. executable_target_pattern: Regular expression limiting executable targets. spec: Specifications for target.
Limit targets for Xcode wrapper.
[ "Limit", "targets", "for", "Xcode", "wrapper", "." ]
def IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): """Limit targets for Xcode wrapper. Xcode sometimes performs poorly with too many targets, so only include proper executable targets, with filters to customize. Arguments: target_extras: Regular expression to always add, matching any target. executable_target_pattern: Regular expression limiting executable targets. spec: Specifications for target. """ target_name = spec.get('target_name') # Always include targets matching target_extras. if target_extras is not None and re.search(target_extras, target_name): return True # Otherwise just show executable targets. if spec.get('type', '') == 'executable' and \ spec.get('product_extension', '') != 'bundle': # If there is a filter and the target does not match, exclude the target. if executable_target_pattern is not None: if not re.search(executable_target_pattern, target_name): return False return True return False
[ "def", "IsValidTargetForWrapper", "(", "target_extras", ",", "executable_target_pattern", ",", "spec", ")", ":", "target_name", "=", "spec", ".", "get", "(", "'target_name'", ")", "# Always include targets matching target_extras.", "if", "target_extras", "is", "not", "None", "and", "re", ".", "search", "(", "target_extras", ",", "target_name", ")", ":", "return", "True", "# Otherwise just show executable targets.", "if", "spec", ".", "get", "(", "'type'", ",", "''", ")", "==", "'executable'", "and", "spec", ".", "get", "(", "'product_extension'", ",", "''", ")", "!=", "'bundle'", ":", "# If there is a filter and the target does not match, exclude the target.", "if", "executable_target_pattern", "is", "not", "None", ":", "if", "not", "re", ".", "search", "(", "executable_target_pattern", ",", "target_name", ")", ":", "return", "False", "return", "True", "return", "False" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py#L126-L150
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/bootstrap/erp5_core/ModuleComponentTemplateItem/portal_components/module.erp5.DateUtils.py
python
getIntervalListBetweenDates
(from_date=None, to_date=None, keys={'year':1, 'month':1, 'week' : 1, 'day':1})
return returned_value_dict
Return the list of years, months and days (if each is equal to 1 in keys) between the both given dates including the current one. If one of the given dates is None, the date used is the current time.
Return the list of years, months and days (if each is equal to 1 in keys) between the both given dates including the current one. If one of the given dates is None, the date used is the current time.
[ "Return", "the", "list", "of", "years", "months", "and", "days", "(", "if", "each", "is", "equal", "to", "1", "in", "keys", ")", "between", "the", "both", "given", "dates", "including", "the", "current", "one", ".", "If", "one", "of", "the", "given", "dates", "is", "None", "the", "date", "used", "is", "the", "current", "time", "." ]
def getIntervalListBetweenDates(from_date=None, to_date=None, keys={'year':1, 'month':1, 'week' : 1, 'day':1}): """ Return the list of years, months and days (if each is equal to 1 in keys) between the both given dates including the current one. If one of the given dates is None, the date used is the current time. """ # key -> format dict format_dict = {'year':'%Y', 'month':'%Y-%m', 'week':'%Y-%V', 'day':'%Y-%m-%d', } if from_date is None: from_date = DateTime() if to_date is None: to_date = DateTime() if from_date - to_date > 0: from_date, to_date = to_date, from_date to_inverse = 1 else: to_inverse = 0 diff_value_dict = {} for current_key in ('year', 'month', 'week', 'day'): if keys.get(current_key, None): new_date = from_date while new_date <= to_date: if current_key == 'day': new_strftime = new_date.ISO() new_strftime = new_strftime[:new_strftime.index(' ')] diff_value_dict.setdefault(current_key, []).append(new_strftime) else: diff_value_dict.setdefault(current_key, []).append(new_date.strftime(format_dict[current_key])) if current_key == "week": new_date = addToDate(new_date, to_add={'day':7}) else: new_date = addToDate(new_date, to_add={current_key:1}) if to_date.strftime(format_dict[current_key]) not in\ diff_value_dict[current_key]: diff_value_dict.setdefault(current_key, []).append(to_date.strftime(format_dict[current_key])) returned_value_dict = {} for key, value in diff_value_dict.iteritems(): if to_inverse: value.reverse() returned_value_dict[key] = value else: returned_value_dict[key] = value return returned_value_dict
[ "def", "getIntervalListBetweenDates", "(", "from_date", "=", "None", ",", "to_date", "=", "None", ",", "keys", "=", "{", "'year'", ":", "1", ",", "'month'", ":", "1", ",", "'week'", ":", "1", ",", "'day'", ":", "1", "}", ")", ":", "# key -> format dict", "format_dict", "=", "{", "'year'", ":", "'%Y'", ",", "'month'", ":", "'%Y-%m'", ",", "'week'", ":", "'%Y-%V'", ",", "'day'", ":", "'%Y-%m-%d'", ",", "}", "if", "from_date", "is", "None", ":", "from_date", "=", "DateTime", "(", ")", "if", "to_date", "is", "None", ":", "to_date", "=", "DateTime", "(", ")", "if", "from_date", "-", "to_date", ">", "0", ":", "from_date", ",", "to_date", "=", "to_date", ",", "from_date", "to_inverse", "=", "1", "else", ":", "to_inverse", "=", "0", "diff_value_dict", "=", "{", "}", "for", "current_key", "in", "(", "'year'", ",", "'month'", ",", "'week'", ",", "'day'", ")", ":", "if", "keys", ".", "get", "(", "current_key", ",", "None", ")", ":", "new_date", "=", "from_date", "while", "new_date", "<=", "to_date", ":", "if", "current_key", "==", "'day'", ":", "new_strftime", "=", "new_date", ".", "ISO", "(", ")", "new_strftime", "=", "new_strftime", "[", ":", "new_strftime", ".", "index", "(", "' '", ")", "]", "diff_value_dict", ".", "setdefault", "(", "current_key", ",", "[", "]", ")", ".", "append", "(", "new_strftime", ")", "else", ":", "diff_value_dict", ".", "setdefault", "(", "current_key", ",", "[", "]", ")", ".", "append", "(", "new_date", ".", "strftime", "(", "format_dict", "[", "current_key", "]", ")", ")", "if", "current_key", "==", "\"week\"", ":", "new_date", "=", "addToDate", "(", "new_date", ",", "to_add", "=", "{", "'day'", ":", "7", "}", ")", "else", ":", "new_date", "=", "addToDate", "(", "new_date", ",", "to_add", "=", "{", "current_key", ":", "1", "}", ")", "if", "to_date", ".", "strftime", "(", "format_dict", "[", "current_key", "]", ")", "not", "in", "diff_value_dict", "[", "current_key", "]", ":", "diff_value_dict", ".", "setdefault", "(", "current_key", ",", "[", "]", ")", ".", "append", "(", "to_date", ".", "strftime", "(", "format_dict", "[", "current_key", "]", ")", ")", "returned_value_dict", "=", "{", "}", "for", "key", ",", "value", "in", "diff_value_dict", ".", "iteritems", "(", ")", ":", "if", "to_inverse", ":", "value", ".", "reverse", "(", ")", "returned_value_dict", "[", "key", "]", "=", "value", "else", ":", "returned_value_dict", "[", "key", "]", "=", "value", "return", "returned_value_dict" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/bootstrap/erp5_core/ModuleComponentTemplateItem/portal_components/module.erp5.DateUtils.py#L224-L277
facebookarchive/nuclide
2a2a0a642d136768b7d2a6d35a652dc5fb77d70a
modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py
python
has_arithmetic_operator
(line)
return False
Return True if line contains any arithmetic operators.
Return True if line contains any arithmetic operators.
[ "Return", "True", "if", "line", "contains", "any", "arithmetic", "operators", "." ]
def has_arithmetic_operator(line): """Return True if line contains any arithmetic operators.""" for operator in pycodestyle.ARITHMETIC_OP: if operator in line: return True return False
[ "def", "has_arithmetic_operator", "(", "line", ")", ":", "for", "operator", "in", "pycodestyle", ".", "ARITHMETIC_OP", ":", "if", "operator", "in", "line", ":", "return", "True", "return", "False" ]
https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py#L3590-L3596
prometheus-ar/vot.ar
72d8fa1ea08fe417b64340b98dff68df8364afdf
msa/core/armve/protocol.py
python
PowerManager._callback_power_source_control
(self, data)
return struct_byte.parse(data)
Callback que se ejecuta cuando se recibe la respuesta del evento representado en CMD_PWR_SOURCE_CONTROL. Argumentos: data -- string con los datos del protocolo que no fueron procesados.
Callback que se ejecuta cuando se recibe la respuesta del evento representado en CMD_PWR_SOURCE_CONTROL.
[ "Callback", "que", "se", "ejecuta", "cuando", "se", "recibe", "la", "respuesta", "del", "evento", "representado", "en", "CMD_PWR_SOURCE_CONTROL", "." ]
def _callback_power_source_control(self, data): """Callback que se ejecuta cuando se recibe la respuesta del evento representado en CMD_PWR_SOURCE_CONTROL. Argumentos: data -- string con los datos del protocolo que no fueron procesados. """ return struct_byte.parse(data)
[ "def", "_callback_power_source_control", "(", "self", ",", "data", ")", ":", "return", "struct_byte", ".", "parse", "(", "data", ")" ]
https://github.com/prometheus-ar/vot.ar/blob/72d8fa1ea08fe417b64340b98dff68df8364afdf/msa/core/armve/protocol.py#L642-L650
crits/crits
6b357daa5c3060cf622d3a3b0c7b41a9ca69c049
crits/core/crits_mongoengine.py
python
CritsActionsDocument.edit_action
(self, type_, active, analyst, begin_date, end_date, performed_date, reason, date=None)
Edit an action for an Indicator. :param type_: The type of action. :type type_: str :param active: Whether this action is active or not. :param active: str ("on", "off") :param analyst: The user editing this action. :type analyst: str :param begin_date: The date this action begins. :type begin_date: datetime.datetime :param end_date: The date this action ends. :type end_date: datetime.datetime :param performed_date: The date this action was performed. :type performed_date: datetime.datetime :param reason: The reason for this action. :type reason: str :param date: The date this action was added to CRITs. :type date: datetime.datetime
Edit an action for an Indicator.
[ "Edit", "an", "action", "for", "an", "Indicator", "." ]
def edit_action(self, type_, active, analyst, begin_date, end_date, performed_date, reason, date=None): """ Edit an action for an Indicator. :param type_: The type of action. :type type_: str :param active: Whether this action is active or not. :param active: str ("on", "off") :param analyst: The user editing this action. :type analyst: str :param begin_date: The date this action begins. :type begin_date: datetime.datetime :param end_date: The date this action ends. :type end_date: datetime.datetime :param performed_date: The date this action was performed. :type performed_date: datetime.datetime :param reason: The reason for this action. :type reason: str :param date: The date this action was added to CRITs. :type date: datetime.datetime """ if not date: return for t in self.actions: if t.date == date and t.action_type == type_: self.actions.remove(t) ea = EmbeddedAction() ea.action_type = type_ ea.active = active ea.analyst = analyst ea.begin_date = begin_date ea.end_date = end_date ea.performed_date = performed_date ea.reason = reason ea.date = date self.actions.append(ea) break
[ "def", "edit_action", "(", "self", ",", "type_", ",", "active", ",", "analyst", ",", "begin_date", ",", "end_date", ",", "performed_date", ",", "reason", ",", "date", "=", "None", ")", ":", "if", "not", "date", ":", "return", "for", "t", "in", "self", ".", "actions", ":", "if", "t", ".", "date", "==", "date", "and", "t", ".", "action_type", "==", "type_", ":", "self", ".", "actions", ".", "remove", "(", "t", ")", "ea", "=", "EmbeddedAction", "(", ")", "ea", ".", "action_type", "=", "type_", "ea", ".", "active", "=", "active", "ea", ".", "analyst", "=", "analyst", "ea", ".", "begin_date", "=", "begin_date", "ea", ".", "end_date", "=", "end_date", "ea", ".", "performed_date", "=", "performed_date", "ea", ".", "reason", "=", "reason", "ea", ".", "date", "=", "date", "self", ".", "actions", ".", "append", "(", "ea", ")", "break" ]
https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/core/crits_mongoengine.py#L823-L861
tain335/tain335
21c08048e6599b5f18d7fd6acfc1e88ece226d09
Lupy-0.2.1/lupy/indexer.py
python
Index.termSearch
(self, field, term)
return q
Search for a single C{term} in a C{field}.
Search for a single C{term} in a C{field}.
[ "Search", "for", "a", "single", "C", "{", "term", "}", "in", "a", "C", "{", "field", "}", "." ]
def termSearch(self, field, term): "Search for a single C{term} in a C{field}." t = Term(field, term) q = TermQuery(t) return q
[ "def", "termSearch", "(", "self", ",", "field", ",", "term", ")", ":", "t", "=", "Term", "(", "field", ",", "term", ")", "q", "=", "TermQuery", "(", "t", ")", "return", "q" ]
https://github.com/tain335/tain335/blob/21c08048e6599b5f18d7fd6acfc1e88ece226d09/Lupy-0.2.1/lupy/indexer.py#L206-L210
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/platform.py
python
python_version_tuple
()
return tuple(string.split(_sys_version()[1], '.'))
Returns the Python version as tuple (major, minor, patchlevel) of strings. Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0).
Returns the Python version as tuple (major, minor, patchlevel) of strings.
[ "Returns", "the", "Python", "version", "as", "tuple", "(", "major", "minor", "patchlevel", ")", "of", "strings", "." ]
def python_version_tuple(): """ Returns the Python version as tuple (major, minor, patchlevel) of strings. Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0). """ return tuple(string.split(_sys_version()[1], '.'))
[ "def", "python_version_tuple", "(", ")", ":", "return", "tuple", "(", "string", ".", "split", "(", "_sys_version", "(", ")", "[", "1", "]", ",", "'.'", ")", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/platform.py#L1469-L1478
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_internal/vcs/git.py
python
Git.get_revision_sha
(cls, dest, rev)
return (sha, False)
Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name.
Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None.
[ "Return", "(", "sha_or_none", "is_branch", ")", "where", "sha_or_none", "is", "a", "commit", "hash", "if", "the", "revision", "names", "a", "remote", "branch", "or", "tag", "otherwise", "None", "." ]
def get_revision_sha(cls, dest, rev): """ Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name. """ # Pass rev to pre-filter the list. output = cls.run_command(['show-ref', rev], cwd=dest, show_stdout=False, on_returncode='ignore') refs = {} for line in output.strip().splitlines(): try: sha, ref = line.split() except ValueError: # Include the offending line to simplify troubleshooting if # this error ever occurs. raise ValueError('unexpected show-ref line: {!r}'.format(line)) refs[ref] = sha branch_ref = 'refs/remotes/origin/{}'.format(rev) tag_ref = 'refs/tags/{}'.format(rev) sha = refs.get(branch_ref) if sha is not None: return (sha, True) sha = refs.get(tag_ref) return (sha, False)
[ "def", "get_revision_sha", "(", "cls", ",", "dest", ",", "rev", ")", ":", "# Pass rev to pre-filter the list.", "output", "=", "cls", ".", "run_command", "(", "[", "'show-ref'", ",", "rev", "]", ",", "cwd", "=", "dest", ",", "show_stdout", "=", "False", ",", "on_returncode", "=", "'ignore'", ")", "refs", "=", "{", "}", "for", "line", "in", "output", ".", "strip", "(", ")", ".", "splitlines", "(", ")", ":", "try", ":", "sha", ",", "ref", "=", "line", ".", "split", "(", ")", "except", "ValueError", ":", "# Include the offending line to simplify troubleshooting if", "# this error ever occurs.", "raise", "ValueError", "(", "'unexpected show-ref line: {!r}'", ".", "format", "(", "line", ")", ")", "refs", "[", "ref", "]", "=", "sha", "branch_ref", "=", "'refs/remotes/origin/{}'", ".", "format", "(", "rev", ")", "tag_ref", "=", "'refs/tags/{}'", ".", "format", "(", "rev", ")", "sha", "=", "refs", ".", "get", "(", "branch_ref", ")", "if", "sha", "is", "not", "None", ":", "return", "(", "sha", ",", "True", ")", "sha", "=", "refs", ".", "get", "(", "tag_ref", ")", "return", "(", "sha", ",", "False", ")" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_internal/vcs/git.py#L96-L128
chromium/hterm
0264cd340ccc21f0321c3a2d70fccadbf0bc377f
bin/vtscope.py
python
VTScope.cmd_help
(self, args)
Display help information to the user.
Display help information to the user.
[ "Display", "help", "information", "to", "the", "user", "." ]
def cmd_help(self, args): """Display help information to the user.""" if args: print('Command takes no arguments') return first = True for method in dir(self): if method.startswith('cmd_'): if not first: print() else: first = False print('%s:' % (method[4:],)) for line in getattr(self, method).__doc__.strip().splitlines(): if line.startswith(' '): line = line[8:] print(' %s' % (line,))
[ "def", "cmd_help", "(", "self", ",", "args", ")", ":", "if", "args", ":", "print", "(", "'Command takes no arguments'", ")", "return", "first", "=", "True", "for", "method", "in", "dir", "(", "self", ")", ":", "if", "method", ".", "startswith", "(", "'cmd_'", ")", ":", "if", "not", "first", ":", "print", "(", ")", "else", ":", "first", "=", "False", "print", "(", "'%s:'", "%", "(", "method", "[", "4", ":", "]", ",", ")", ")", "for", "line", "in", "getattr", "(", "self", ",", "method", ")", ".", "__doc__", ".", "strip", "(", ")", ".", "splitlines", "(", ")", ":", "if", "line", ".", "startswith", "(", "' '", ")", ":", "line", "=", "line", "[", "8", ":", "]", "print", "(", "' %s'", "%", "(", "line", ",", ")", ")" ]
https://github.com/chromium/hterm/blob/0264cd340ccc21f0321c3a2d70fccadbf0bc377f/bin/vtscope.py#L353-L371
frenck/home-assistant-config
91fb77e527bc470b557b6156fd1d60515e0b0be9
custom_components/samsungtv_smart/media_player.py
python
SamsungTVDevice.async_set_art_mode
(self)
Turn the media player on setting in art mode.
Turn the media player on setting in art mode.
[ "Turn", "the", "media", "player", "on", "setting", "in", "art", "mode", "." ]
async def async_set_art_mode(self): """Turn the media player on setting in art mode.""" await self._async_turn_on(True)
[ "async", "def", "async_set_art_mode", "(", "self", ")", ":", "await", "self", ".", "_async_turn_on", "(", "True", ")" ]
https://github.com/frenck/home-assistant-config/blob/91fb77e527bc470b557b6156fd1d60515e0b0be9/custom_components/samsungtv_smart/media_player.py#L1096-L1098
oldj/SwitchHosts
d0eb2321fe36780ec32c914cbc69a818fc1918d3
alfred/workflow/workflow3.py
python
Workflow3.session_id
(self)
return self._session_id
A unique session ID every time the user uses the workflow. .. versionadded:: 1.25 The session ID persists while the user is using this workflow. It expires when the user runs a different workflow or closes Alfred.
A unique session ID every time the user uses the workflow.
[ "A", "unique", "session", "ID", "every", "time", "the", "user", "uses", "the", "workflow", "." ]
def session_id(self): """A unique session ID every time the user uses the workflow. .. versionadded:: 1.25 The session ID persists while the user is using this workflow. It expires when the user runs a different workflow or closes Alfred. """ if not self._session_id: from uuid import uuid4 self._session_id = uuid4().hex self.setvar('_WF_SESSION_ID', self._session_id) return self._session_id
[ "def", "session_id", "(", "self", ")", ":", "if", "not", "self", ".", "_session_id", ":", "from", "uuid", "import", "uuid4", "self", ".", "_session_id", "=", "uuid4", "(", ")", ".", "hex", "self", ".", "setvar", "(", "'_WF_SESSION_ID'", ",", "self", ".", "_session_id", ")", "return", "self", ".", "_session_id" ]
https://github.com/oldj/SwitchHosts/blob/d0eb2321fe36780ec32c914cbc69a818fc1918d3/alfred/workflow/workflow3.py#L508-L523
crits/crits
6b357daa5c3060cf622d3a3b0c7b41a9ca69c049
crits/domains/handlers.py
python
add_new_domain
(data, request, errors, rowData=None, is_validate_only=False, cache={})
return result, errors, retVal
Add a new domain to CRITs. :param data: The data about the domain. :type data: dict :param request: The Django request. :type request: :class:`django.http.HttpRequest` :param errors: A list of current errors to append to. :type errors: list :param rowData: Any objects that need to be added to the domain. :type rowData: dict :param is_validate_only: Only validate the data and return any errors. :type is_validate_only: boolean :param cache: Cached data, typically for performance enhancements during bulk operations. :type cache: dict :returns: tuple (<result>, <errors>, <retVal>)
Add a new domain to CRITs.
[ "Add", "a", "new", "domain", "to", "CRITs", "." ]
def add_new_domain(data, request, errors, rowData=None, is_validate_only=False, cache={}): """ Add a new domain to CRITs. :param data: The data about the domain. :type data: dict :param request: The Django request. :type request: :class:`django.http.HttpRequest` :param errors: A list of current errors to append to. :type errors: list :param rowData: Any objects that need to be added to the domain. :type rowData: dict :param is_validate_only: Only validate the data and return any errors. :type is_validate_only: boolean :param cache: Cached data, typically for performance enhancements during bulk operations. :type cache: dict :returns: tuple (<result>, <errors>, <retVal>) """ result = False retVal = {} domain = data['domain'] add_ip = data.get('add_ip') ip = data.get('ip') ip_type = data.get('ip_type') if add_ip: error = validate_and_normalize_ip(ip, ip_type)[1] if error: errors.append(error) if is_validate_only: error = get_valid_root_domain(domain)[2] if error: errors.append(error) # check for duplicate domains fqdn_domain = retrieve_domain(domain, cache) if fqdn_domain: if isinstance(fqdn_domain, Domain): resp_url = reverse('crits-domains-views-domain_detail', args=[domain]) message = ('Warning: Domain already exists: ' '<a href="%s">%s</a>' % (resp_url, domain)) retVal['message'] = message retVal['status'] = form_consts.Status.DUPLICATE retVal['warning'] = message else: result_cache = cache.get(form_consts.Domain.CACHED_RESULTS); result_cache[domain.lower()] = True elif not errors: user = request.user reference = data.get('source_reference') source_name = data.get('source_name') method = data.get('source_method') tlp = data.get('source_tlp') bucket_list = data.get(form_consts.Common.BUCKET_LIST_VARIABLE_NAME) ticket = data.get(form_consts.Common.TICKET_VARIABLE_NAME) related_id = data.get('related_id') related_type = data.get('related_type') relationship_type = data.get('relationship_type') if user.check_source_write(source_name): source = [create_embedded_source(source_name, reference=reference, method=method, tlp=tlp, analyst=user.username)] else: result = {"success": False, "message": "User does not have permission to add objects \ using source %s." % str(source_name)} return False, False, result if data.get('campaign') and data.get('confidence'): campaign = [EmbeddedCampaign(name=data.get('campaign'), confidence=data.get('confidence'), analyst=user.username)] else: campaign = [] retVal = upsert_domain(domain, source, user.username, campaign, bucket_list=bucket_list, ticket=ticket, cache=cache, related_id=related_id, related_type=related_type, relationship_type=relationship_type) if not retVal['success']: errors.append(retVal.get('message')) retVal['message'] = "" else: new_domain = retVal['object'] ip_result = {} if add_ip: if data.get('same_source'): ip_source = source_name ip_method = method ip_reference = reference ip_tlp = tlp else: ip_source = data.get('ip_source') ip_method = data.get('ip_method') ip_reference = data.get('ip_reference') ip_tlp = data.get('ip_tlp') from crits.ips.handlers import ip_add_update ip_result = ip_add_update(ip, ip_type, source=ip_source, source_method=ip_method, source_reference=ip_reference, source_tlp=ip_tlp, campaign=campaign, user=user, bucket_list=bucket_list, ticket=ticket, cache=cache) if not ip_result['success']: errors.append(ip_result['message']) else: #add a relationship with the new IP address new_ip = ip_result['object'] if new_domain and new_ip: new_domain.add_relationship(new_ip, RelationshipTypes.RESOLVED_TO, analyst=user.username, get_rels=False) new_domain.save(username=user.username) #set the URL for viewing the new data resp_url = reverse('crits-domains-views-domain_detail', args=[domain]) if retVal['is_domain_new'] == True: retVal['message'] = ('Success! Click here to view the new domain: ' '<a href="%s">%s</a>' % (resp_url, domain)) else: message = ('Updated existing domain: <a href="%s">%s</a>' % (resp_url, domain)) retVal['message'] = message retVal[form_consts.Status.STATUS_FIELD] = form_consts.Status.DUPLICATE retVal['warning'] = message #add indicators if data.get('add_indicators'): from crits.indicators.handlers import create_indicator_from_tlo # If we have an IP object, add an indicator for that. if ip_result.get('success'): ip = ip_result['object'] result = create_indicator_from_tlo('IP', ip, user, ip_source, source_tlp=ip_tlp, add_domain=False) ip_ind = result.get('indicator') if not result['success']: errors.append(result['message']) # Add an indicator for the domain. result = create_indicator_from_tlo('Domain', new_domain, user, source_name, source_tlp=tlp, add_domain=False) if not result['success']: errors.append(result['message']) elif ip_result.get('success') and ip_ind: forge_relationship(class_=result['indicator'], right_class=ip_ind, rel_type=RelationshipTypes.RESOLVED_TO, user=user.username) result = True # This block validates, and may also add, objects to the Domain if retVal.get('success') or is_validate_only == True: if rowData: objectsData = rowData.get(form_consts.Common.OBJECTS_DATA) # add new objects if they exist if objectsData: objectsData = json.loads(objectsData) current_domain = retrieve_domain(domain, cache) for object_row_counter, objectData in enumerate(objectsData, 1): if current_domain != None: # if the domain exists then try to add objects to it if isinstance(current_domain, Domain) == True: objectDict = object_array_to_dict(objectData, "Domain", current_domain.id) else: objectDict = object_array_to_dict(objectData, "Domain", "") current_domain = None; else: objectDict = object_array_to_dict(objectData, "Domain", "") (obj_result, errors, obj_retVal) = validate_and_add_new_handler_object( None, objectDict, request, errors, object_row_counter, is_validate_only=is_validate_only, cache=cache, obj=current_domain) if not obj_result: retVal['success'] = False return result, errors, retVal
[ "def", "add_new_domain", "(", "data", ",", "request", ",", "errors", ",", "rowData", "=", "None", ",", "is_validate_only", "=", "False", ",", "cache", "=", "{", "}", ")", ":", "result", "=", "False", "retVal", "=", "{", "}", "domain", "=", "data", "[", "'domain'", "]", "add_ip", "=", "data", ".", "get", "(", "'add_ip'", ")", "ip", "=", "data", ".", "get", "(", "'ip'", ")", "ip_type", "=", "data", ".", "get", "(", "'ip_type'", ")", "if", "add_ip", ":", "error", "=", "validate_and_normalize_ip", "(", "ip", ",", "ip_type", ")", "[", "1", "]", "if", "error", ":", "errors", ".", "append", "(", "error", ")", "if", "is_validate_only", ":", "error", "=", "get_valid_root_domain", "(", "domain", ")", "[", "2", "]", "if", "error", ":", "errors", ".", "append", "(", "error", ")", "# check for duplicate domains", "fqdn_domain", "=", "retrieve_domain", "(", "domain", ",", "cache", ")", "if", "fqdn_domain", ":", "if", "isinstance", "(", "fqdn_domain", ",", "Domain", ")", ":", "resp_url", "=", "reverse", "(", "'crits-domains-views-domain_detail'", ",", "args", "=", "[", "domain", "]", ")", "message", "=", "(", "'Warning: Domain already exists: '", "'<a href=\"%s\">%s</a>'", "%", "(", "resp_url", ",", "domain", ")", ")", "retVal", "[", "'message'", "]", "=", "message", "retVal", "[", "'status'", "]", "=", "form_consts", ".", "Status", ".", "DUPLICATE", "retVal", "[", "'warning'", "]", "=", "message", "else", ":", "result_cache", "=", "cache", ".", "get", "(", "form_consts", ".", "Domain", ".", "CACHED_RESULTS", ")", "result_cache", "[", "domain", ".", "lower", "(", ")", "]", "=", "True", "elif", "not", "errors", ":", "user", "=", "request", ".", "user", "reference", "=", "data", ".", "get", "(", "'source_reference'", ")", "source_name", "=", "data", ".", "get", "(", "'source_name'", ")", "method", "=", "data", ".", "get", "(", "'source_method'", ")", "tlp", "=", "data", ".", "get", "(", "'source_tlp'", ")", "bucket_list", "=", "data", ".", "get", "(", "form_consts", ".", "Common", ".", "BUCKET_LIST_VARIABLE_NAME", ")", "ticket", "=", "data", ".", "get", "(", "form_consts", ".", "Common", ".", "TICKET_VARIABLE_NAME", ")", "related_id", "=", "data", ".", "get", "(", "'related_id'", ")", "related_type", "=", "data", ".", "get", "(", "'related_type'", ")", "relationship_type", "=", "data", ".", "get", "(", "'relationship_type'", ")", "if", "user", ".", "check_source_write", "(", "source_name", ")", ":", "source", "=", "[", "create_embedded_source", "(", "source_name", ",", "reference", "=", "reference", ",", "method", "=", "method", ",", "tlp", "=", "tlp", ",", "analyst", "=", "user", ".", "username", ")", "]", "else", ":", "result", "=", "{", "\"success\"", ":", "False", ",", "\"message\"", ":", "\"User does not have permission to add objects \\\n using source %s.\"", "%", "str", "(", "source_name", ")", "}", "return", "False", ",", "False", ",", "result", "if", "data", ".", "get", "(", "'campaign'", ")", "and", "data", ".", "get", "(", "'confidence'", ")", ":", "campaign", "=", "[", "EmbeddedCampaign", "(", "name", "=", "data", ".", "get", "(", "'campaign'", ")", ",", "confidence", "=", "data", ".", "get", "(", "'confidence'", ")", ",", "analyst", "=", "user", ".", "username", ")", "]", "else", ":", "campaign", "=", "[", "]", "retVal", "=", "upsert_domain", "(", "domain", ",", "source", ",", "user", ".", "username", ",", "campaign", ",", "bucket_list", "=", "bucket_list", ",", "ticket", "=", "ticket", ",", "cache", "=", "cache", ",", "related_id", "=", "related_id", ",", "related_type", "=", "related_type", ",", "relationship_type", "=", "relationship_type", ")", "if", "not", "retVal", "[", "'success'", "]", ":", "errors", ".", "append", "(", "retVal", ".", "get", "(", "'message'", ")", ")", "retVal", "[", "'message'", "]", "=", "\"\"", "else", ":", "new_domain", "=", "retVal", "[", "'object'", "]", "ip_result", "=", "{", "}", "if", "add_ip", ":", "if", "data", ".", "get", "(", "'same_source'", ")", ":", "ip_source", "=", "source_name", "ip_method", "=", "method", "ip_reference", "=", "reference", "ip_tlp", "=", "tlp", "else", ":", "ip_source", "=", "data", ".", "get", "(", "'ip_source'", ")", "ip_method", "=", "data", ".", "get", "(", "'ip_method'", ")", "ip_reference", "=", "data", ".", "get", "(", "'ip_reference'", ")", "ip_tlp", "=", "data", ".", "get", "(", "'ip_tlp'", ")", "from", "crits", ".", "ips", ".", "handlers", "import", "ip_add_update", "ip_result", "=", "ip_add_update", "(", "ip", ",", "ip_type", ",", "source", "=", "ip_source", ",", "source_method", "=", "ip_method", ",", "source_reference", "=", "ip_reference", ",", "source_tlp", "=", "ip_tlp", ",", "campaign", "=", "campaign", ",", "user", "=", "user", ",", "bucket_list", "=", "bucket_list", ",", "ticket", "=", "ticket", ",", "cache", "=", "cache", ")", "if", "not", "ip_result", "[", "'success'", "]", ":", "errors", ".", "append", "(", "ip_result", "[", "'message'", "]", ")", "else", ":", "#add a relationship with the new IP address", "new_ip", "=", "ip_result", "[", "'object'", "]", "if", "new_domain", "and", "new_ip", ":", "new_domain", ".", "add_relationship", "(", "new_ip", ",", "RelationshipTypes", ".", "RESOLVED_TO", ",", "analyst", "=", "user", ".", "username", ",", "get_rels", "=", "False", ")", "new_domain", ".", "save", "(", "username", "=", "user", ".", "username", ")", "#set the URL for viewing the new data", "resp_url", "=", "reverse", "(", "'crits-domains-views-domain_detail'", ",", "args", "=", "[", "domain", "]", ")", "if", "retVal", "[", "'is_domain_new'", "]", "==", "True", ":", "retVal", "[", "'message'", "]", "=", "(", "'Success! Click here to view the new domain: '", "'<a href=\"%s\">%s</a>'", "%", "(", "resp_url", ",", "domain", ")", ")", "else", ":", "message", "=", "(", "'Updated existing domain: <a href=\"%s\">%s</a>'", "%", "(", "resp_url", ",", "domain", ")", ")", "retVal", "[", "'message'", "]", "=", "message", "retVal", "[", "form_consts", ".", "Status", ".", "STATUS_FIELD", "]", "=", "form_consts", ".", "Status", ".", "DUPLICATE", "retVal", "[", "'warning'", "]", "=", "message", "#add indicators", "if", "data", ".", "get", "(", "'add_indicators'", ")", ":", "from", "crits", ".", "indicators", ".", "handlers", "import", "create_indicator_from_tlo", "# If we have an IP object, add an indicator for that.", "if", "ip_result", ".", "get", "(", "'success'", ")", ":", "ip", "=", "ip_result", "[", "'object'", "]", "result", "=", "create_indicator_from_tlo", "(", "'IP'", ",", "ip", ",", "user", ",", "ip_source", ",", "source_tlp", "=", "ip_tlp", ",", "add_domain", "=", "False", ")", "ip_ind", "=", "result", ".", "get", "(", "'indicator'", ")", "if", "not", "result", "[", "'success'", "]", ":", "errors", ".", "append", "(", "result", "[", "'message'", "]", ")", "# Add an indicator for the domain.", "result", "=", "create_indicator_from_tlo", "(", "'Domain'", ",", "new_domain", ",", "user", ",", "source_name", ",", "source_tlp", "=", "tlp", ",", "add_domain", "=", "False", ")", "if", "not", "result", "[", "'success'", "]", ":", "errors", ".", "append", "(", "result", "[", "'message'", "]", ")", "elif", "ip_result", ".", "get", "(", "'success'", ")", "and", "ip_ind", ":", "forge_relationship", "(", "class_", "=", "result", "[", "'indicator'", "]", ",", "right_class", "=", "ip_ind", ",", "rel_type", "=", "RelationshipTypes", ".", "RESOLVED_TO", ",", "user", "=", "user", ".", "username", ")", "result", "=", "True", "# This block validates, and may also add, objects to the Domain", "if", "retVal", ".", "get", "(", "'success'", ")", "or", "is_validate_only", "==", "True", ":", "if", "rowData", ":", "objectsData", "=", "rowData", ".", "get", "(", "form_consts", ".", "Common", ".", "OBJECTS_DATA", ")", "# add new objects if they exist", "if", "objectsData", ":", "objectsData", "=", "json", ".", "loads", "(", "objectsData", ")", "current_domain", "=", "retrieve_domain", "(", "domain", ",", "cache", ")", "for", "object_row_counter", ",", "objectData", "in", "enumerate", "(", "objectsData", ",", "1", ")", ":", "if", "current_domain", "!=", "None", ":", "# if the domain exists then try to add objects to it", "if", "isinstance", "(", "current_domain", ",", "Domain", ")", "==", "True", ":", "objectDict", "=", "object_array_to_dict", "(", "objectData", ",", "\"Domain\"", ",", "current_domain", ".", "id", ")", "else", ":", "objectDict", "=", "object_array_to_dict", "(", "objectData", ",", "\"Domain\"", ",", "\"\"", ")", "current_domain", "=", "None", "else", ":", "objectDict", "=", "object_array_to_dict", "(", "objectData", ",", "\"Domain\"", ",", "\"\"", ")", "(", "obj_result", ",", "errors", ",", "obj_retVal", ")", "=", "validate_and_add_new_handler_object", "(", "None", ",", "objectDict", ",", "request", ",", "errors", ",", "object_row_counter", ",", "is_validate_only", "=", "is_validate_only", ",", "cache", "=", "cache", ",", "obj", "=", "current_domain", ")", "if", "not", "obj_result", ":", "retVal", "[", "'success'", "]", "=", "False", "return", "result", ",", "errors", ",", "retVal" ]
https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/domains/handlers.py#L307-L512
facultyai/dash-bootstrap-components
0532ffefe3e2b329c3ff68e5e0878df7c62fb18f
tasks.py
python
prerelease
(ctx, version)
Release a pre-release version Running this task will: - Bump the version number - Push a release to pypi
Release a pre-release version Running this task will: - Bump the version number - Push a release to pypi
[ "Release", "a", "pre", "-", "release", "version", "Running", "this", "task", "will", ":", "-", "Bump", "the", "version", "number", "-", "Push", "a", "release", "to", "pypi" ]
def prerelease(ctx, version): """ Release a pre-release version Running this task will: - Bump the version number - Push a release to pypi """ info(f"Creating prerelease branch for {version}") set_source_version(version) run(f"git checkout -b prerelease/{version}") run( "git add package.json package-lock.json " "dash_bootstrap_components/_version.py " "tests/test_version.py" ) run(f'git commit -m "Prerelease {version}"') run(f"git push origin prerelease/{version}")
[ "def", "prerelease", "(", "ctx", ",", "version", ")", ":", "info", "(", "f\"Creating prerelease branch for {version}\"", ")", "set_source_version", "(", "version", ")", "run", "(", "f\"git checkout -b prerelease/{version}\"", ")", "run", "(", "\"git add package.json package-lock.json \"", "\"dash_bootstrap_components/_version.py \"", "\"tests/test_version.py\"", ")", "run", "(", "f'git commit -m \"Prerelease {version}\"'", ")", "run", "(", "f\"git push origin prerelease/{version}\"", ")" ]
https://github.com/facultyai/dash-bootstrap-components/blob/0532ffefe3e2b329c3ff68e5e0878df7c62fb18f/tasks.py#L26-L42
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/textio.py
python
Color.bk_black
(cls)
Make the text background color black.
Make the text background color black.
[ "Make", "the", "text", "background", "color", "black", "." ]
def bk_black(cls): "Make the text background color black." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK #wAttributes |= win32.BACKGROUND_BLACK cls._set_text_attributes(wAttributes)
[ "def", "bk_black", "(", "cls", ")", ":", "wAttributes", "=", "cls", ".", "_get_text_attributes", "(", ")", "wAttributes", "&=", "~", "win32", ".", "BACKGROUND_MASK", "#wAttributes |= win32.BACKGROUND_BLACK", "cls", ".", "_set_text_attributes", "(", "wAttributes", ")" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/textio.py#L1032-L1037
sitespeedio/browsertime
4c692c6c69e8c887a99a498cca99f5fbde76f980
browsertime/visualmetrics.py
python
render_video
(directory, video_file)
Render the frames to the given mp4 file
Render the frames to the given mp4 file
[ "Render", "the", "frames", "to", "the", "given", "mp4", "file" ]
def render_video(directory, video_file): """Render the frames to the given mp4 file""" directory = os.path.realpath(directory) files = sorted(glob.glob(os.path.join(directory, "ms_*.png"))) if len(files) > 1: current_image = None with open(os.path.join(directory, files[0]), "rb") as f_in: current_image = f_in.read() if current_image is not None: command = [ "ffmpeg", "-f", "image2pipe", "-vcodec", "png", "-r", "30", "-i", "-", "-vcodec", "libx264", "-r", "30", "-crf", "24", "-g", "15", "-preset", "superfast", "-y", video_file, ] try: proc = subprocess.Popen(command, stdin=subprocess.PIPE) if proc: match = re.compile(r"ms_([0-9]+)\.") m = re.search(match, files[1]) file_index = 0 last_index = len(files) - 1 if m is not None: next_image_time = int(m.group(1)) done = False current_frame = 0 while not done: current_frame_time = int( round(float(current_frame) * 1000.0 / 30.0) ) if current_frame_time >= next_image_time: file_index += 1 with open( os.path.join(directory, files[file_index]), "rb" ) as f_in: current_image = f_in.read() if file_index < last_index: m = re.search(match, files[file_index + 1]) if m: next_image_time = int(m.group(1)) else: done = True proc.stdin.write(current_image) current_frame += 1 # hold the end frame for one second so it's actually # visible for i in range(30): proc.stdin.write(current_image) proc.stdin.close() proc.communicate() except Exception: pass
[ "def", "render_video", "(", "directory", ",", "video_file", ")", ":", "directory", "=", "os", ".", "path", ".", "realpath", "(", "directory", ")", "files", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "\"ms_*.png\"", ")", ")", ")", "if", "len", "(", "files", ")", ">", "1", ":", "current_image", "=", "None", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "files", "[", "0", "]", ")", ",", "\"rb\"", ")", "as", "f_in", ":", "current_image", "=", "f_in", ".", "read", "(", ")", "if", "current_image", "is", "not", "None", ":", "command", "=", "[", "\"ffmpeg\"", ",", "\"-f\"", ",", "\"image2pipe\"", ",", "\"-vcodec\"", ",", "\"png\"", ",", "\"-r\"", ",", "\"30\"", ",", "\"-i\"", ",", "\"-\"", ",", "\"-vcodec\"", ",", "\"libx264\"", ",", "\"-r\"", ",", "\"30\"", ",", "\"-crf\"", ",", "\"24\"", ",", "\"-g\"", ",", "\"15\"", ",", "\"-preset\"", ",", "\"superfast\"", ",", "\"-y\"", ",", "video_file", ",", "]", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", "if", "proc", ":", "match", "=", "re", ".", "compile", "(", "r\"ms_([0-9]+)\\.\"", ")", "m", "=", "re", ".", "search", "(", "match", ",", "files", "[", "1", "]", ")", "file_index", "=", "0", "last_index", "=", "len", "(", "files", ")", "-", "1", "if", "m", "is", "not", "None", ":", "next_image_time", "=", "int", "(", "m", ".", "group", "(", "1", ")", ")", "done", "=", "False", "current_frame", "=", "0", "while", "not", "done", ":", "current_frame_time", "=", "int", "(", "round", "(", "float", "(", "current_frame", ")", "*", "1000.0", "/", "30.0", ")", ")", "if", "current_frame_time", ">=", "next_image_time", ":", "file_index", "+=", "1", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "files", "[", "file_index", "]", ")", ",", "\"rb\"", ")", "as", "f_in", ":", "current_image", "=", "f_in", ".", "read", "(", ")", "if", "file_index", "<", "last_index", ":", "m", "=", "re", ".", "search", "(", "match", ",", "files", "[", "file_index", "+", "1", "]", ")", "if", "m", ":", "next_image_time", "=", "int", "(", "m", ".", "group", "(", "1", ")", ")", "else", ":", "done", "=", "True", "proc", ".", "stdin", ".", "write", "(", "current_image", ")", "current_frame", "+=", "1", "# hold the end frame for one second so it's actually", "# visible", "for", "i", "in", "range", "(", "30", ")", ":", "proc", ".", "stdin", ".", "write", "(", "current_image", ")", "proc", ".", "stdin", ".", "close", "(", ")", "proc", ".", "communicate", "(", ")", "except", "Exception", ":", "pass" ]
https://github.com/sitespeedio/browsertime/blob/4c692c6c69e8c887a99a498cca99f5fbde76f980/browsertime/visualmetrics.py#L1447-L1515
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
deps/v8/third_party/jinja2/filters.py
python
do_list
(value)
return list(value)
Convert the value into a list. If it was a string the returned list will be a list of characters.
Convert the value into a list. If it was a string the returned list will be a list of characters.
[ "Convert", "the", "value", "into", "a", "list", ".", "If", "it", "was", "a", "string", "the", "returned", "list", "will", "be", "a", "list", "of", "characters", "." ]
def do_list(value): """Convert the value into a list. If it was a string the returned list will be a list of characters. """ return list(value)
[ "def", "do_list", "(", "value", ")", ":", "return", "list", "(", "value", ")" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/v8/third_party/jinja2/filters.py#L746-L750
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/bootstrap/erp5_core/InterfaceTemplateItem/portal_components/interface.erp5.IFile.py
python
IFile.getContentType
(default=None)
return content_type, mimetype of data
return content_type, mimetype of data
[ "return", "content_type", "mimetype", "of", "data" ]
def getContentType(default=None): """ return content_type, mimetype of data """
[ "def", "getContentType", "(", "default", "=", "None", ")", ":" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/bootstrap/erp5_core/InterfaceTemplateItem/portal_components/interface.erp5.IFile.py#L44-L47
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
src/pyasm/search/search.py
python
Search.do_search
(self, redo=False, statement=None)
return self.sobjects
self.config = SObjectConfig.get_by_search_type(self.search_type_obj, database) if self.config != None: order_bys = self.config.get_order_by() order_bys = order_bys.split(',') for order_by in order_bys: if order_by: self.add_order_by(order_by)
self.config = SObjectConfig.get_by_search_type(self.search_type_obj, database) if self.config != None: order_bys = self.config.get_order_by() order_bys = order_bys.split(',') for order_by in order_bys: if order_by: self.add_order_by(order_by)
[ "self", ".", "config", "=", "SObjectConfig", ".", "get_by_search_type", "(", "self", ".", "search_type_obj", "database", ")", "if", "self", ".", "config", "!", "=", "None", ":", "order_bys", "=", "self", ".", "config", ".", "get_order_by", "()", "order_bys", "=", "order_bys", ".", "split", "(", ")", "for", "order_by", "in", "order_bys", ":", "if", "order_by", ":", "self", ".", "add_order_by", "(", "order_by", ")" ]
def do_search(self, redo=False, statement=None): if self.null_filter: return [] # if we are doing a remote search, then get the sobjects from the # remote search if isinstance(self.select, RemoteSearch): return self.select.get_sobjects() if not redo and self.is_search_done: return self.sobjects search_type = self.get_base_search_type() security = Environment.get_security() # filter extra_filter = self.search_type_obj.get_value("extra_filter", no_exception=True) if extra_filter: self.add_where(extra_filter) # DEPRECATED: not sure if this was ever used?? # # allow the sobject to alter search # A little convoluted, but it works class_path = self.search_type_obj.get_class() (module_name, class_name) = \ Common.breakup_class_path(class_path) try: try: exec("%s.alter_search(self)" % class_name ) except NameError: exec("from %s import %s" % (module_name,class_name), gl, lc ) exec("%s.alter_search(self)" % class_name ) except ImportError: raise SearchException("Class_path [%s] does not exist" % class_path) # allow security to alter the search if it hasn't been done in SearchLimitWdg if not self.security_filter: security.alter_search(self) # build an sql object database = self.get_database() # SQL Server: Skip the temp column put in by handle_pagination() db_resource = self.db_resource sql = DbContainer.get(db_resource) # get the columns table = self.get_table() columns = sql.get_columns(table) #columns = self.remove_temp_column(columns, sql) select_columns = self.select.get_columns() if select_columns: if select_columns[0] == '*': del(select_columns[0]) columns.extend(select_columns) else: columns = select_columns ''' self.config = SObjectConfig.get_by_search_type(self.search_type_obj, database) if self.config != None: order_bys = self.config.get_order_by() order_bys = order_bys.split(',') for order_by in order_bys: if order_by: self.add_order_by(order_by) ''' # Hard coded replacement. This is done for performance reasons if self.order_by: if search_type in ['sthpw/snapshot', 'sthpw/note','sthpw/sobject_log', 'sthpw/transaction_log', 'sthpw/status_log']: self.add_order_by("timestamp", direction="desc") elif search_type == 'sthpw/task': self.add_order_by("search_type") if self.column_exists("search_code"): self.add_order_by("search_code") elif search_type == 'sthpw/login': self.add_order_by("login") elif search_type == 'sthpw/login_group': self.add_order_by("login_group") elif search_type == 'config/process': self.add_order_by("pipeline_code,sort_order") elif search_type == 'sthpw/message_log': self.add_order_by("timestamp", direction="desc") elif "code" in columns: self.add_order_by("code") # skip retired sobject self.skip_retired(columns) # get columns that are datetime to be converted to strings in # SObject constructor column_info = self.get_column_info() datetime_cols = [] boolean_cols = [] skipped_cols = [] for key,value in column_info.items(): data_type = value.get('data_type') if data_type in ['timestamp', 'time', 'date', 'datetime2']: datetime_cols.append(key) elif data_type in ['boolean']: boolean_cols.append(key) elif data_type in ['sqlserver_timestamp']: skipped_cols.append(key) vendor = db_resource.get_vendor() if vendor == "MongoDb": #statement = self.select.get_statement() #print('statement: ', statement) results = sql.do_query(self.select) # TODO: # Not really used because results is already a dictionary # and the column data is dynamic columns = ['_id'] result_is_dict = True elif vendor in ["Salesforce"] or search_type.startswith("salesforce/"): impl = db_resource.get_database_impl() self.sobjects = impl.execute_query(sql, self.select) # remember that the search has been done self.is_search_done = True return self.sobjects else: # get the select statement and do the query if not statement: statement = self.select.get_statement() #print("QUERY: ", statement) from pyasm.security import Site results = sql.do_query(statement) # this gets the actual order of columns in this SQL columns = sql.get_columns_from_description() result_is_dict = False Container.increment('Search:sql_query') # create a list of objects self.sobjects = [] # precalculate some information from pyasm.biz import Project #full_search_type = Project.get_full_search_type(search_type, project_code=self.project_code) full_search_type = self.get_full_search_type() fast_data = { 'full_search_type': full_search_type, 'search_type_obj': self.search_type_obj, 'database': Project.extract_database(full_search_type), 'db_resource': db_resource, 'datetime_cols': datetime_cols, 'boolean_cols': boolean_cols, 'skipped_cols': skipped_cols, } # Count number of sobjects num_sobjects = Container.get("NUM_SOBJECTS") if not num_sobjects: num_sobjects = 0 num_sobjects = num_sobjects + len(results) if len(results) > 10000: print("WARNING query: (%s) sobjects found: %s" % (len(results), statement.encode('utf-8','ignore'))) Container.put("NUM_SOBJECTS", num_sobjects) # assemble the data dictionaries to be distributed to the sobjects data_list = [] for result in results: if result_is_dict: data = result else: data = dict(zip(columns, result)) if skipped_cols: for skipped_col in skipped_cols: # forcing this data empty because # otherwise the sobject does not have # a column it believes it should have #del data[skipped_col] data[skipped_col] = "" data_list.append(data) fast_data['data'] = data_list # do this inline for performance for i, result in enumerate(results): fast_data['count'] = i sobject = SearchType.fast_create_from_class_path(class_name, self.search_type_obj, columns, result, module_name=module_name, fast_data=fast_data) # add this sobject to the list of sobjects for the search self.sobjects.append(sobject) # remember that the search has been done self.is_search_done = True return self.sobjects
[ "def", "do_search", "(", "self", ",", "redo", "=", "False", ",", "statement", "=", "None", ")", ":", "if", "self", ".", "null_filter", ":", "return", "[", "]", "# if we are doing a remote search, then get the sobjects from the", "# remote search", "if", "isinstance", "(", "self", ".", "select", ",", "RemoteSearch", ")", ":", "return", "self", ".", "select", ".", "get_sobjects", "(", ")", "if", "not", "redo", "and", "self", ".", "is_search_done", ":", "return", "self", ".", "sobjects", "search_type", "=", "self", ".", "get_base_search_type", "(", ")", "security", "=", "Environment", ".", "get_security", "(", ")", "# filter", "extra_filter", "=", "self", ".", "search_type_obj", ".", "get_value", "(", "\"extra_filter\"", ",", "no_exception", "=", "True", ")", "if", "extra_filter", ":", "self", ".", "add_where", "(", "extra_filter", ")", "# DEPRECATED: not sure if this was ever used??", "#", "# allow the sobject to alter search", "# A little convoluted, but it works", "class_path", "=", "self", ".", "search_type_obj", ".", "get_class", "(", ")", "(", "module_name", ",", "class_name", ")", "=", "Common", ".", "breakup_class_path", "(", "class_path", ")", "try", ":", "try", ":", "exec", "(", "\"%s.alter_search(self)\"", "%", "class_name", ")", "except", "NameError", ":", "exec", "(", "\"from %s import %s\"", "%", "(", "module_name", ",", "class_name", ")", ",", "gl", ",", "lc", ")", "exec", "(", "\"%s.alter_search(self)\"", "%", "class_name", ")", "except", "ImportError", ":", "raise", "SearchException", "(", "\"Class_path [%s] does not exist\"", "%", "class_path", ")", "# allow security to alter the search if it hasn't been done in SearchLimitWdg", "if", "not", "self", ".", "security_filter", ":", "security", ".", "alter_search", "(", "self", ")", "# build an sql object", "database", "=", "self", ".", "get_database", "(", ")", "# SQL Server: Skip the temp column put in by handle_pagination()", "db_resource", "=", "self", ".", "db_resource", "sql", "=", "DbContainer", ".", "get", "(", "db_resource", ")", "# get the columns", "table", "=", "self", ".", "get_table", "(", ")", "columns", "=", "sql", ".", "get_columns", "(", "table", ")", "#columns = self.remove_temp_column(columns, sql) ", "select_columns", "=", "self", ".", "select", ".", "get_columns", "(", ")", "if", "select_columns", ":", "if", "select_columns", "[", "0", "]", "==", "'*'", ":", "del", "(", "select_columns", "[", "0", "]", ")", "columns", ".", "extend", "(", "select_columns", ")", "else", ":", "columns", "=", "select_columns", "# Hard coded replacement. This is done for performance reasons", "if", "self", ".", "order_by", ":", "if", "search_type", "in", "[", "'sthpw/snapshot'", ",", "'sthpw/note'", ",", "'sthpw/sobject_log'", ",", "'sthpw/transaction_log'", ",", "'sthpw/status_log'", "]", ":", "self", ".", "add_order_by", "(", "\"timestamp\"", ",", "direction", "=", "\"desc\"", ")", "elif", "search_type", "==", "'sthpw/task'", ":", "self", ".", "add_order_by", "(", "\"search_type\"", ")", "if", "self", ".", "column_exists", "(", "\"search_code\"", ")", ":", "self", ".", "add_order_by", "(", "\"search_code\"", ")", "elif", "search_type", "==", "'sthpw/login'", ":", "self", ".", "add_order_by", "(", "\"login\"", ")", "elif", "search_type", "==", "'sthpw/login_group'", ":", "self", ".", "add_order_by", "(", "\"login_group\"", ")", "elif", "search_type", "==", "'config/process'", ":", "self", ".", "add_order_by", "(", "\"pipeline_code,sort_order\"", ")", "elif", "search_type", "==", "'sthpw/message_log'", ":", "self", ".", "add_order_by", "(", "\"timestamp\"", ",", "direction", "=", "\"desc\"", ")", "elif", "\"code\"", "in", "columns", ":", "self", ".", "add_order_by", "(", "\"code\"", ")", "# skip retired sobject", "self", ".", "skip_retired", "(", "columns", ")", "# get columns that are datetime to be converted to strings in", "# SObject constructor", "column_info", "=", "self", ".", "get_column_info", "(", ")", "datetime_cols", "=", "[", "]", "boolean_cols", "=", "[", "]", "skipped_cols", "=", "[", "]", "for", "key", ",", "value", "in", "column_info", ".", "items", "(", ")", ":", "data_type", "=", "value", ".", "get", "(", "'data_type'", ")", "if", "data_type", "in", "[", "'timestamp'", ",", "'time'", ",", "'date'", ",", "'datetime2'", "]", ":", "datetime_cols", ".", "append", "(", "key", ")", "elif", "data_type", "in", "[", "'boolean'", "]", ":", "boolean_cols", ".", "append", "(", "key", ")", "elif", "data_type", "in", "[", "'sqlserver_timestamp'", "]", ":", "skipped_cols", ".", "append", "(", "key", ")", "vendor", "=", "db_resource", ".", "get_vendor", "(", ")", "if", "vendor", "==", "\"MongoDb\"", ":", "#statement = self.select.get_statement()", "#print('statement: ', statement)", "results", "=", "sql", ".", "do_query", "(", "self", ".", "select", ")", "# TODO:", "# Not really used because results is already a dictionary", "# and the column data is dynamic", "columns", "=", "[", "'_id'", "]", "result_is_dict", "=", "True", "elif", "vendor", "in", "[", "\"Salesforce\"", "]", "or", "search_type", ".", "startswith", "(", "\"salesforce/\"", ")", ":", "impl", "=", "db_resource", ".", "get_database_impl", "(", ")", "self", ".", "sobjects", "=", "impl", ".", "execute_query", "(", "sql", ",", "self", ".", "select", ")", "# remember that the search has been done", "self", ".", "is_search_done", "=", "True", "return", "self", ".", "sobjects", "else", ":", "# get the select statement and do the query", "if", "not", "statement", ":", "statement", "=", "self", ".", "select", ".", "get_statement", "(", ")", "#print(\"QUERY: \", statement)", "from", "pyasm", ".", "security", "import", "Site", "results", "=", "sql", ".", "do_query", "(", "statement", ")", "# this gets the actual order of columns in this SQL", "columns", "=", "sql", ".", "get_columns_from_description", "(", ")", "result_is_dict", "=", "False", "Container", ".", "increment", "(", "'Search:sql_query'", ")", "# create a list of objects", "self", ".", "sobjects", "=", "[", "]", "# precalculate some information", "from", "pyasm", ".", "biz", "import", "Project", "#full_search_type = Project.get_full_search_type(search_type, project_code=self.project_code)", "full_search_type", "=", "self", ".", "get_full_search_type", "(", ")", "fast_data", "=", "{", "'full_search_type'", ":", "full_search_type", ",", "'search_type_obj'", ":", "self", ".", "search_type_obj", ",", "'database'", ":", "Project", ".", "extract_database", "(", "full_search_type", ")", ",", "'db_resource'", ":", "db_resource", ",", "'datetime_cols'", ":", "datetime_cols", ",", "'boolean_cols'", ":", "boolean_cols", ",", "'skipped_cols'", ":", "skipped_cols", ",", "}", "# Count number of sobjects", "num_sobjects", "=", "Container", ".", "get", "(", "\"NUM_SOBJECTS\"", ")", "if", "not", "num_sobjects", ":", "num_sobjects", "=", "0", "num_sobjects", "=", "num_sobjects", "+", "len", "(", "results", ")", "if", "len", "(", "results", ")", ">", "10000", ":", "print", "(", "\"WARNING query: (%s) sobjects found: %s\"", "%", "(", "len", "(", "results", ")", ",", "statement", ".", "encode", "(", "'utf-8'", ",", "'ignore'", ")", ")", ")", "Container", ".", "put", "(", "\"NUM_SOBJECTS\"", ",", "num_sobjects", ")", "# assemble the data dictionaries to be distributed to the sobjects", "data_list", "=", "[", "]", "for", "result", "in", "results", ":", "if", "result_is_dict", ":", "data", "=", "result", "else", ":", "data", "=", "dict", "(", "zip", "(", "columns", ",", "result", ")", ")", "if", "skipped_cols", ":", "for", "skipped_col", "in", "skipped_cols", ":", "# forcing this data empty because", "# otherwise the sobject does not have", "# a column it believes it should have", "#del data[skipped_col]", "data", "[", "skipped_col", "]", "=", "\"\"", "data_list", ".", "append", "(", "data", ")", "fast_data", "[", "'data'", "]", "=", "data_list", "# do this inline for performance", "for", "i", ",", "result", "in", "enumerate", "(", "results", ")", ":", "fast_data", "[", "'count'", "]", "=", "i", "sobject", "=", "SearchType", ".", "fast_create_from_class_path", "(", "class_name", ",", "self", ".", "search_type_obj", ",", "columns", ",", "result", ",", "module_name", "=", "module_name", ",", "fast_data", "=", "fast_data", ")", "# add this sobject to the list of sobjects for the search", "self", ".", "sobjects", ".", "append", "(", "sobject", ")", "# remember that the search has been done", "self", ".", "is_search_done", "=", "True", "return", "self", ".", "sobjects" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/pyasm/search/search.py#L1841-L2056
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
odoo/addons/base/models/res_config.py
python
ResConfigConfigurable.execute
(self)
Method called when the user clicks on the ``Next`` button. Execute *must* be overloaded unless ``action_next`` is overloaded (which is something you generally don't need to do). If ``execute`` returns an action dictionary, that action is executed rather than just going to the next configuration item.
Method called when the user clicks on the ``Next`` button.
[ "Method", "called", "when", "the", "user", "clicks", "on", "the", "Next", "button", "." ]
def execute(self): """ Method called when the user clicks on the ``Next`` button. Execute *must* be overloaded unless ``action_next`` is overloaded (which is something you generally don't need to do). If ``execute`` returns an action dictionary, that action is executed rather than just going to the next configuration item. """ raise NotImplementedError( 'Configuration items need to implement execute')
[ "def", "execute", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'Configuration items need to implement execute'", ")" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/odoo/addons/base/models/res_config.py#L71-L81
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/parso/python/diff.py
python
DiffParser.update
(self, old_lines, new_lines)
return self._module
The algorithm works as follows: Equal: - Assure that the start is a newline, otherwise parse until we get one. - Copy from parsed_until_line + 1 to max(i2 + 1) - Make sure that the indentation is correct (e.g. add DEDENT) - Add old and change positions Insert: - Parse from parsed_until_line + 1 to min(j2 + 1), hopefully not much more. Returns the new module node.
The algorithm works as follows:
[ "The", "algorithm", "works", "as", "follows", ":" ]
def update(self, old_lines, new_lines): ''' The algorithm works as follows: Equal: - Assure that the start is a newline, otherwise parse until we get one. - Copy from parsed_until_line + 1 to max(i2 + 1) - Make sure that the indentation is correct (e.g. add DEDENT) - Add old and change positions Insert: - Parse from parsed_until_line + 1 to min(j2 + 1), hopefully not much more. Returns the new module node. ''' LOG.debug('diff parser start') # Reset the used names cache so they get regenerated. self._module._used_names = None self._parser_lines_new = new_lines self._reset() line_length = len(new_lines) sm = difflib.SequenceMatcher(None, old_lines, self._parser_lines_new) opcodes = sm.get_opcodes() LOG.debug('diff parser calculated') LOG.debug('diff: line_lengths old: %s, new: %s' % (len(old_lines), line_length)) for operation, i1, i2, j1, j2 in opcodes: LOG.debug('diff code[%s] old[%s:%s] new[%s:%s]', operation, i1 + 1, i2, j1 + 1, j2) if j2 == line_length and new_lines[-1] == '': # The empty part after the last newline is not relevant. j2 -= 1 if operation == 'equal': line_offset = j1 - i1 self._copy_from_old_parser(line_offset, i2, j2) elif operation == 'replace': self._parse(until_line=j2) elif operation == 'insert': self._parse(until_line=j2) else: assert operation == 'delete' # With this action all change will finally be applied and we have a # changed module. self._nodes_stack.close() last_pos = self._module.end_pos[0] if last_pos != line_length: current_lines = split_lines(self._module.get_code(), keepends=True) diff = difflib.unified_diff(current_lines, new_lines) raise Exception( "There's an issue (%s != %s) with the diff parser. Please report:\n%s" % (last_pos, line_length, ''.join(diff)) ) LOG.debug('diff parser end') return self._module
[ "def", "update", "(", "self", ",", "old_lines", ",", "new_lines", ")", ":", "LOG", ".", "debug", "(", "'diff parser start'", ")", "# Reset the used names cache so they get regenerated.", "self", ".", "_module", ".", "_used_names", "=", "None", "self", ".", "_parser_lines_new", "=", "new_lines", "self", ".", "_reset", "(", ")", "line_length", "=", "len", "(", "new_lines", ")", "sm", "=", "difflib", ".", "SequenceMatcher", "(", "None", ",", "old_lines", ",", "self", ".", "_parser_lines_new", ")", "opcodes", "=", "sm", ".", "get_opcodes", "(", ")", "LOG", ".", "debug", "(", "'diff parser calculated'", ")", "LOG", ".", "debug", "(", "'diff: line_lengths old: %s, new: %s'", "%", "(", "len", "(", "old_lines", ")", ",", "line_length", ")", ")", "for", "operation", ",", "i1", ",", "i2", ",", "j1", ",", "j2", "in", "opcodes", ":", "LOG", ".", "debug", "(", "'diff code[%s] old[%s:%s] new[%s:%s]'", ",", "operation", ",", "i1", "+", "1", ",", "i2", ",", "j1", "+", "1", ",", "j2", ")", "if", "j2", "==", "line_length", "and", "new_lines", "[", "-", "1", "]", "==", "''", ":", "# The empty part after the last newline is not relevant.", "j2", "-=", "1", "if", "operation", "==", "'equal'", ":", "line_offset", "=", "j1", "-", "i1", "self", ".", "_copy_from_old_parser", "(", "line_offset", ",", "i2", ",", "j2", ")", "elif", "operation", "==", "'replace'", ":", "self", ".", "_parse", "(", "until_line", "=", "j2", ")", "elif", "operation", "==", "'insert'", ":", "self", ".", "_parse", "(", "until_line", "=", "j2", ")", "else", ":", "assert", "operation", "==", "'delete'", "# With this action all change will finally be applied and we have a", "# changed module.", "self", ".", "_nodes_stack", ".", "close", "(", ")", "last_pos", "=", "self", ".", "_module", ".", "end_pos", "[", "0", "]", "if", "last_pos", "!=", "line_length", ":", "current_lines", "=", "split_lines", "(", "self", ".", "_module", ".", "get_code", "(", ")", ",", "keepends", "=", "True", ")", "diff", "=", "difflib", ".", "unified_diff", "(", "current_lines", ",", "new_lines", ")", "raise", "Exception", "(", "\"There's an issue (%s != %s) with the diff parser. Please report:\\n%s\"", "%", "(", "last_pos", ",", "line_length", ",", "''", ".", "join", "(", "diff", ")", ")", ")", "LOG", ".", "debug", "(", "'diff parser end'", ")", "return", "self", ".", "_module" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/parso/python/diff.py#L105-L167
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
addons/event_sms/models/event_registration.py
python
Registration._sms_get_number_fields
(self)
return ['mobile', 'phone']
This method returns the fields to use to find the number to use to send an SMS on a record.
This method returns the fields to use to find the number to use to send an SMS on a record.
[ "This", "method", "returns", "the", "fields", "to", "use", "to", "find", "the", "number", "to", "use", "to", "send", "an", "SMS", "on", "a", "record", "." ]
def _sms_get_number_fields(self): """ This method returns the fields to use to find the number to use to send an SMS on a record. """ return ['mobile', 'phone']
[ "def", "_sms_get_number_fields", "(", "self", ")", ":", "return", "[", "'mobile'", ",", "'phone'", "]" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/event_sms/models/event_registration.py#L10-L13
facebookarchive/nuclide
2a2a0a642d136768b7d2a6d35a652dc5fb77d70a
pkg/nuclide-clang-rpc/VendorLib/clang/cindex.py
python
TranslationUnit.get_includes
(self)
return iter(includes)
Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit. The first object in this sequence is always the input file. Note that this method will not recursively iterate over header files included through precompiled headers.
Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit. The first object in this sequence is always the input file. Note that this method will not recursively iterate over header files included through precompiled headers.
[ "Return", "an", "iterable", "sequence", "of", "FileInclusion", "objects", "that", "describe", "the", "sequence", "of", "inclusions", "in", "a", "translation", "unit", ".", "The", "first", "object", "in", "this", "sequence", "is", "always", "the", "input", "file", ".", "Note", "that", "this", "method", "will", "not", "recursively", "iterate", "over", "header", "files", "included", "through", "precompiled", "headers", "." ]
def get_includes(self): """ Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit. The first object in this sequence is always the input file. Note that this method will not recursively iterate over header files included through precompiled headers. """ def visitor(fobj, lptr, depth, includes): if depth > 0: loc = lptr.contents includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) # Automatically adapt CIndex/ctype pointers to python objects includes = [] conf.lib.clang_getInclusions(self, callbacks['translation_unit_includes'](visitor), includes) return iter(includes)
[ "def", "get_includes", "(", "self", ")", ":", "def", "visitor", "(", "fobj", ",", "lptr", ",", "depth", ",", "includes", ")", ":", "if", "depth", ">", "0", ":", "loc", "=", "lptr", ".", "contents", "includes", ".", "append", "(", "FileInclusion", "(", "loc", ".", "file", ",", "File", "(", "fobj", ")", ",", "loc", ",", "depth", ")", ")", "# Automatically adapt CIndex/ctype pointers to python objects", "includes", "=", "[", "]", "conf", ".", "lib", ".", "clang_getInclusions", "(", "self", ",", "callbacks", "[", "'translation_unit_includes'", "]", "(", "visitor", ")", ",", "includes", ")", "return", "iter", "(", "includes", ")" ]
https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/pkg/nuclide-clang-rpc/VendorLib/clang/cindex.py#L2320-L2338
korolr/dotfiles
8e46933503ecb8d8651739ffeb1d2d4f0f5c6524
.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/png.py
python
Writer.write_array
(self, outfile, pixels)
Write an array in flat row flat pixel format as a PNG file on the output file. See also :meth:`write` method.
Write an array in flat row flat pixel format as a PNG file on the output file. See also :meth:`write` method.
[ "Write", "an", "array", "in", "flat", "row", "flat", "pixel", "format", "as", "a", "PNG", "file", "on", "the", "output", "file", ".", "See", "also", ":", "meth", ":", "write", "method", "." ]
def write_array(self, outfile, pixels): """ Write an array in flat row flat pixel format as a PNG file on the output file. See also :meth:`write` method. """ if self.interlace: self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: self.write_passes(outfile, self.array_scanlines(pixels))
[ "def", "write_array", "(", "self", ",", "outfile", ",", "pixels", ")", ":", "if", "self", ".", "interlace", ":", "self", ".", "write_passes", "(", "outfile", ",", "self", ".", "array_scanlines_interlace", "(", "pixels", ")", ")", "else", ":", "self", ".", "write_passes", "(", "outfile", ",", "self", ".", "array_scanlines", "(", "pixels", ")", ")" ]
https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/png.py#L816-L825
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/closured/lib/python2.7/random.py
python
Random.sample
(self, population, k)
return result
Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use xrange as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60)
Chooses k unique random elements from a population sequence.
[ "Chooses", "k", "unique", "random", "elements", "from", "a", "population", "sequence", "." ]
def sample(self, population, k): """Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use xrange as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60) """ # Sampling without replacement entails tracking either potential # selections (the pool) in a list or previous selections in a set. # When the number of selections is small compared to the # population, then tracking selections is efficient, requiring # only a small set and an occasional reselection. For # a larger number of selections, the pool tracking method is # preferred since the list takes less space than the # set and it doesn't suffer from frequent reselections. n = len(population) if not 0 <= k <= n: raise ValueError("sample larger than population") random = self.random _int = int result = [None] * k setsize = 21 # size of a small set minus size of an empty list if k > 5: setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets if n <= setsize or hasattr(population, "keys"): # An n-length list is smaller than a k-length set, or this is a # mapping type so the other algorithm wouldn't work. pool = list(population) for i in xrange(k): # invariant: non-selected at [0,n-i) j = _int(random() * (n-i)) result[i] = pool[j] pool[j] = pool[n-i-1] # move non-selected item into vacancy else: try: selected = set() selected_add = selected.add for i in xrange(k): j = _int(random() * n) while j in selected: j = _int(random() * n) selected_add(j) result[i] = population[j] except (TypeError, KeyError): # handle (at least) sets if isinstance(population, list): raise return self.sample(tuple(population), k) return result
[ "def", "sample", "(", "self", ",", "population", ",", "k", ")", ":", "# Sampling without replacement entails tracking either potential", "# selections (the pool) in a list or previous selections in a set.", "# When the number of selections is small compared to the", "# population, then tracking selections is efficient, requiring", "# only a small set and an occasional reselection. For", "# a larger number of selections, the pool tracking method is", "# preferred since the list takes less space than the", "# set and it doesn't suffer from frequent reselections.", "n", "=", "len", "(", "population", ")", "if", "not", "0", "<=", "k", "<=", "n", ":", "raise", "ValueError", "(", "\"sample larger than population\"", ")", "random", "=", "self", ".", "random", "_int", "=", "int", "result", "=", "[", "None", "]", "*", "k", "setsize", "=", "21", "# size of a small set minus size of an empty list", "if", "k", ">", "5", ":", "setsize", "+=", "4", "**", "_ceil", "(", "_log", "(", "k", "*", "3", ",", "4", ")", ")", "# table size for big sets", "if", "n", "<=", "setsize", "or", "hasattr", "(", "population", ",", "\"keys\"", ")", ":", "# An n-length list is smaller than a k-length set, or this is a", "# mapping type so the other algorithm wouldn't work.", "pool", "=", "list", "(", "population", ")", "for", "i", "in", "xrange", "(", "k", ")", ":", "# invariant: non-selected at [0,n-i)", "j", "=", "_int", "(", "random", "(", ")", "*", "(", "n", "-", "i", ")", ")", "result", "[", "i", "]", "=", "pool", "[", "j", "]", "pool", "[", "j", "]", "=", "pool", "[", "n", "-", "i", "-", "1", "]", "# move non-selected item into vacancy", "else", ":", "try", ":", "selected", "=", "set", "(", ")", "selected_add", "=", "selected", ".", "add", "for", "i", "in", "xrange", "(", "k", ")", ":", "j", "=", "_int", "(", "random", "(", ")", "*", "n", ")", "while", "j", "in", "selected", ":", "j", "=", "_int", "(", "random", "(", ")", "*", "n", ")", "selected_add", "(", "j", ")", "result", "[", "i", "]", "=", "population", "[", "j", "]", "except", "(", "TypeError", ",", "KeyError", ")", ":", "# handle (at least) sets", "if", "isinstance", "(", "population", ",", "list", ")", ":", "raise", "return", "self", ".", "sample", "(", "tuple", "(", "population", ")", ",", "k", ")", "return", "result" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/random.py#L290-L349
visgl/deck.gl
1dd761d3e06023d8dccbb75a6be38ad6325d5c7f
bindings/pydeck/pydeck/data_utils/viewport_helpers.py
python
euclidean
(y, y1)
return math.sqrt(sum([_squared_diff(x, x0) for x, x0 in zip(y, y1)]))
Euclidean distance in n-dimensions Parameters ---------- y : tuple of float A point in n-dimensions y1 : tuple of float A point in n-dimensions Examples -------- >>> EPSILON = 0.001 >>> euclidean((3, 6, 5), (7, -5, 1)) - 12.369 < EPSILON True
Euclidean distance in n-dimensions
[ "Euclidean", "distance", "in", "n", "-", "dimensions" ]
def euclidean(y, y1): """Euclidean distance in n-dimensions Parameters ---------- y : tuple of float A point in n-dimensions y1 : tuple of float A point in n-dimensions Examples -------- >>> EPSILON = 0.001 >>> euclidean((3, 6, 5), (7, -5, 1)) - 12.369 < EPSILON True """ if not len(y) == len(y1): raise Exception("Input coordinates must be of the same length") return math.sqrt(sum([_squared_diff(x, x0) for x, x0 in zip(y, y1)]))
[ "def", "euclidean", "(", "y", ",", "y1", ")", ":", "if", "not", "len", "(", "y", ")", "==", "len", "(", "y1", ")", ":", "raise", "Exception", "(", "\"Input coordinates must be of the same length\"", ")", "return", "math", ".", "sqrt", "(", "sum", "(", "[", "_squared_diff", "(", "x", ",", "x0", ")", "for", "x", ",", "x0", "in", "zip", "(", "y", ",", "y1", ")", "]", ")", ")" ]
https://github.com/visgl/deck.gl/blob/1dd761d3e06023d8dccbb75a6be38ad6325d5c7f/bindings/pydeck/pydeck/data_utils/viewport_helpers.py#L14-L32
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
deps/npm/node_modules/node-gyp/gyp/tools/pretty_vcproj.py
python
main
(argv)
return 0
Main function of this vcproj prettifier.
Main function of this vcproj prettifier.
[ "Main", "function", "of", "this", "vcproj", "prettifier", "." ]
def main(argv): """Main function of this vcproj prettifier.""" global ARGUMENTS ARGUMENTS = argv # check if we have exactly 1 parameter. if len(argv) < 2: print ('Usage: %s "c:\\path\\to\\vcproj.vcproj" [key1=value1] ' '[key2=value2]' % argv[0]) return 1 # Parse the keys for i in range(2, len(argv)): (key, value) = argv[i].split('=') REPLACEMENTS[key] = value # Open the vcproj and parse the xml. dom = parse(argv[1]) # First thing we need to do is find the Configuration Node and merge them # with the vsprops they include. for configuration_node in GetConfiguationNodes(dom.documentElement): # Get the property sheets associated with this configuration. vsprops = configuration_node.getAttribute('InheritedPropertySheets') # Fix the filenames to be absolute. vsprops_list = FixFilenames(vsprops.strip().split(';'), os.path.dirname(argv[1])) # Extend the list of vsprops with all vsprops contained in the current # vsprops. for current_vsprops in vsprops_list: vsprops_list.extend(GetChildrenVsprops(current_vsprops)) # Now that we have all the vsprops, we need to merge them. for current_vsprops in vsprops_list: MergeProperties(configuration_node, parse(current_vsprops).documentElement) # Now that everything is merged, we need to cleanup the xml. CleanupVcproj(dom.documentElement) # Finally, we use the prett xml function to print the vcproj back to the # user. #print dom.toprettyxml(newl="\n") PrettyPrintNode(dom.documentElement) return 0
[ "def", "main", "(", "argv", ")", ":", "global", "ARGUMENTS", "ARGUMENTS", "=", "argv", "# check if we have exactly 1 parameter.", "if", "len", "(", "argv", ")", "<", "2", ":", "print", "(", "'Usage: %s \"c:\\\\path\\\\to\\\\vcproj.vcproj\" [key1=value1] '", "'[key2=value2]'", "%", "argv", "[", "0", "]", ")", "return", "1", "# Parse the keys", "for", "i", "in", "range", "(", "2", ",", "len", "(", "argv", ")", ")", ":", "(", "key", ",", "value", ")", "=", "argv", "[", "i", "]", ".", "split", "(", "'='", ")", "REPLACEMENTS", "[", "key", "]", "=", "value", "# Open the vcproj and parse the xml.", "dom", "=", "parse", "(", "argv", "[", "1", "]", ")", "# First thing we need to do is find the Configuration Node and merge them", "# with the vsprops they include.", "for", "configuration_node", "in", "GetConfiguationNodes", "(", "dom", ".", "documentElement", ")", ":", "# Get the property sheets associated with this configuration.", "vsprops", "=", "configuration_node", ".", "getAttribute", "(", "'InheritedPropertySheets'", ")", "# Fix the filenames to be absolute.", "vsprops_list", "=", "FixFilenames", "(", "vsprops", ".", "strip", "(", ")", ".", "split", "(", "';'", ")", ",", "os", ".", "path", ".", "dirname", "(", "argv", "[", "1", "]", ")", ")", "# Extend the list of vsprops with all vsprops contained in the current", "# vsprops.", "for", "current_vsprops", "in", "vsprops_list", ":", "vsprops_list", ".", "extend", "(", "GetChildrenVsprops", "(", "current_vsprops", ")", ")", "# Now that we have all the vsprops, we need to merge them.", "for", "current_vsprops", "in", "vsprops_list", ":", "MergeProperties", "(", "configuration_node", ",", "parse", "(", "current_vsprops", ")", ".", "documentElement", ")", "# Now that everything is merged, we need to cleanup the xml.", "CleanupVcproj", "(", "dom", ".", "documentElement", ")", "# Finally, we use the prett xml function to print the vcproj back to the", "# user.", "#print dom.toprettyxml(newl=\"\\n\")", "PrettyPrintNode", "(", "dom", ".", "documentElement", ")", "return", "0" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/npm/node_modules/node-gyp/gyp/tools/pretty_vcproj.py#L279-L325
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/burp-protobuf-decoder/Lib/google/protobuf/message_factory.py
python
_GetAllDescriptors
(desc_protos, package)
Gets all levels of nested message types as a flattened list of descriptors. Args: desc_protos: The descriptor protos to process. package: The package where the protos are defined. Yields: Each message descriptor for each nested type.
Gets all levels of nested message types as a flattened list of descriptors.
[ "Gets", "all", "levels", "of", "nested", "message", "types", "as", "a", "flattened", "list", "of", "descriptors", "." ]
def _GetAllDescriptors(desc_protos, package): """Gets all levels of nested message types as a flattened list of descriptors. Args: desc_protos: The descriptor protos to process. package: The package where the protos are defined. Yields: Each message descriptor for each nested type. """ for desc_proto in desc_protos: name = '.'.join((package, desc_proto.name)) yield _POOL.FindMessageTypeByName(name) for nested_desc in _GetAllDescriptors(desc_proto.nested_type, name): yield nested_desc
[ "def", "_GetAllDescriptors", "(", "desc_protos", ",", "package", ")", ":", "for", "desc_proto", "in", "desc_protos", ":", "name", "=", "'.'", ".", "join", "(", "(", "package", ",", "desc_proto", ".", "name", ")", ")", "yield", "_POOL", ".", "FindMessageTypeByName", "(", "name", ")", "for", "nested_desc", "in", "_GetAllDescriptors", "(", "desc_proto", ".", "nested_type", ",", "name", ")", ":", "yield", "nested_desc" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/burp-protobuf-decoder/Lib/google/protobuf/message_factory.py#L98-L113
GeoNode/geonode
326d70153ad79e1ed831d46a0e3b239d422757a8
geonode/maps/admin.py
python
MapAdmin.delete_queryset
(self, request, queryset)
We need to invoke the 'ResourceBase.delete' method even when deleting through the admin batch action
We need to invoke the 'ResourceBase.delete' method even when deleting through the admin batch action
[ "We", "need", "to", "invoke", "the", "ResourceBase", ".", "delete", "method", "even", "when", "deleting", "through", "the", "admin", "batch", "action" ]
def delete_queryset(self, request, queryset): """ We need to invoke the 'ResourceBase.delete' method even when deleting through the admin batch action """ for obj in queryset: from geonode.resource.manager import resource_manager resource_manager.delete(obj.uuid, instance=obj)
[ "def", "delete_queryset", "(", "self", ",", "request", ",", "queryset", ")", ":", "for", "obj", "in", "queryset", ":", "from", "geonode", ".", "resource", ".", "manager", "import", "resource_manager", "resource_manager", ".", "delete", "(", "obj", ".", "uuid", ",", "instance", "=", "obj", ")" ]
https://github.com/GeoNode/geonode/blob/326d70153ad79e1ed831d46a0e3b239d422757a8/geonode/maps/admin.py#L53-L60
silklabs/silk
08c273949086350aeddd8e23e92f0f79243f446f
node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_EscapeCommandLineArgumentForMSBuild
(s)
return s
Escapes a Windows command-line argument for use by MSBuild.
Escapes a Windows command-line argument for use by MSBuild.
[ "Escapes", "a", "Windows", "command", "-", "line", "argument", "for", "use", "by", "MSBuild", "." ]
def _EscapeCommandLineArgumentForMSBuild(s): """Escapes a Windows command-line argument for use by MSBuild.""" def _Replace(match): return (len(match.group(1)) / 2 * 4) * '\\' + '\\"' # Escape all quotes so that they are interpreted literally. s = quote_replacer_regex2.sub(_Replace, s) return s
[ "def", "_EscapeCommandLineArgumentForMSBuild", "(", "s", ")", ":", "def", "_Replace", "(", "match", ")", ":", "return", "(", "len", "(", "match", ".", "group", "(", "1", ")", ")", "/", "2", "*", "4", ")", "*", "'\\\\'", "+", "'\\\\\"'", "# Escape all quotes so that they are interpreted literally.", "s", "=", "quote_replacer_regex2", ".", "sub", "(", "_Replace", ",", "s", ")", "return", "s" ]
https://github.com/silklabs/silk/blob/08c273949086350aeddd8e23e92f0f79243f446f/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L761-L769
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
python
XCConfigurationList.ConfigurationNamed
(self, name)
Convenience accessor to obtain an XCBuildConfiguration by name.
Convenience accessor to obtain an XCBuildConfiguration by name.
[ "Convenience", "accessor", "to", "obtain", "an", "XCBuildConfiguration", "by", "name", "." ]
def ConfigurationNamed(self, name): """Convenience accessor to obtain an XCBuildConfiguration by name.""" for configuration in self._properties['buildConfigurations']: if configuration._properties['name'] == name: return configuration raise KeyError(name)
[ "def", "ConfigurationNamed", "(", "self", ",", "name", ")", ":", "for", "configuration", "in", "self", ".", "_properties", "[", "'buildConfigurations'", "]", ":", "if", "configuration", ".", "_properties", "[", "'name'", "]", "==", "name", ":", "return", "configuration", "raise", "KeyError", "(", "name", ")" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L1604-L1610
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
configure.py
python
is_arch_armv6
()
return cc_macros_cache.get('__ARM_ARCH') == '6'
Check for ARMv6 instructions
Check for ARMv6 instructions
[ "Check", "for", "ARMv6", "instructions" ]
def is_arch_armv6(): """Check for ARMv6 instructions""" cc_macros_cache = cc_macros() return cc_macros_cache.get('__ARM_ARCH') == '6'
[ "def", "is_arch_armv6", "(", ")", ":", "cc_macros_cache", "=", "cc_macros", "(", ")", "return", "cc_macros_cache", ".", "get", "(", "'__ARM_ARCH'", ")", "==", "'6'" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/configure.py#L956-L959
jam-py/jam-py
0821492cdff8665928e0f093a4435aa64285a45c
jam/third_party/werkzeug/wrappers.py
python
BaseResponse.make_sequence
(self)
Converts the response iterator in a list. By default this happens automatically if required. If `implicit_sequence_conversion` is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. .. versionadded:: 0.6
Converts the response iterator in a list. By default this happens automatically if required. If `implicit_sequence_conversion` is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items.
[ "Converts", "the", "response", "iterator", "in", "a", "list", ".", "By", "default", "this", "happens", "automatically", "if", "required", ".", "If", "implicit_sequence_conversion", "is", "disabled", "this", "method", "is", "not", "automatically", "called", "and", "some", "properties", "might", "raise", "exceptions", ".", "This", "also", "encodes", "all", "the", "items", "." ]
def make_sequence(self): """Converts the response iterator in a list. By default this happens automatically if required. If `implicit_sequence_conversion` is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. .. versionadded:: 0.6 """ if not self.is_sequence: # if we consume an iterable we have to ensure that the close # method of the iterable is called if available when we tear # down the response close = getattr(self.response, 'close', None) self.response = list(self.iter_encoded()) if close is not None: self.call_on_close(close)
[ "def", "make_sequence", "(", "self", ")", ":", "if", "not", "self", ".", "is_sequence", ":", "# if we consume an iterable we have to ensure that the close", "# method of the iterable is called if available when we tear", "# down the response", "close", "=", "getattr", "(", "self", ".", "response", ",", "'close'", ",", "None", ")", "self", ".", "response", "=", "list", "(", "self", ".", "iter_encoded", "(", ")", ")", "if", "close", "is", "not", "None", ":", "self", ".", "call_on_close", "(", "close", ")" ]
https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/werkzeug/wrappers.py#L1045-L1060
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
src/client/tactic_client_lib/tactic_server_stub.py
python
TacticServerStub.undo
(self, transaction_ticket=None, transaction_id=None, ignore_files=False)
return self.server.undo(self.ticket, transaction_ticket, transaction_id, ignore_files)
API Function: undo(transaction_ticket=None, transaction_id=None, ignore_files=False) undo an operation. If no transaction id is given, then the last operation of this user on this project is undone @keyparam: transaction_ticket - explicitly undo a specific transaction transaction_id - explicitly undo a specific transaction by id ignore_files - flag which determines whether the files should also be undone. Useful for large preallcoated checkins.
API Function: undo(transaction_ticket=None, transaction_id=None, ignore_files=False) undo an operation. If no transaction id is given, then the last operation of this user on this project is undone
[ "API", "Function", ":", "undo", "(", "transaction_ticket", "=", "None", "transaction_id", "=", "None", "ignore_files", "=", "False", ")", "undo", "an", "operation", ".", "If", "no", "transaction", "id", "is", "given", "then", "the", "last", "operation", "of", "this", "user", "on", "this", "project", "is", "undone" ]
def undo(self, transaction_ticket=None, transaction_id=None, ignore_files=False): '''API Function: undo(transaction_ticket=None, transaction_id=None, ignore_files=False) undo an operation. If no transaction id is given, then the last operation of this user on this project is undone @keyparam: transaction_ticket - explicitly undo a specific transaction transaction_id - explicitly undo a specific transaction by id ignore_files - flag which determines whether the files should also be undone. Useful for large preallcoated checkins. ''' if self.protocol == "local": return return self.server.undo(self.ticket, transaction_ticket, transaction_id, ignore_files)
[ "def", "undo", "(", "self", ",", "transaction_ticket", "=", "None", ",", "transaction_id", "=", "None", ",", "ignore_files", "=", "False", ")", ":", "if", "self", ".", "protocol", "==", "\"local\"", ":", "return", "return", "self", ".", "server", ".", "undo", "(", "self", ".", "ticket", ",", "transaction_ticket", ",", "transaction_id", ",", "ignore_files", ")" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/client/tactic_client_lib/tactic_server_stub.py#L1015-L1030
WuXianglong/GeekBlog
a4fe5e7de225c4891d498d8e9e8f9c0c47053b86
blog/geekblog/mongodb/blog.py
python
BlogMongodbStorage.get_article_by_slug
(self, slug)
return article_infos
根据SLUG获取文章详情
根据SLUG获取文章详情
[ "根据SLUG获取文章详情" ]
def get_article_by_slug(self, slug): """ 根据SLUG获取文章详情 """ cond = {'slug': slug} article_infos = self._db.articles.find_one(cond, fields=ARTICLE_DETAIL_INFO_FIELDS) return article_infos
[ "def", "get_article_by_slug", "(", "self", ",", "slug", ")", ":", "cond", "=", "{", "'slug'", ":", "slug", "}", "article_infos", "=", "self", ".", "_db", ".", "articles", ".", "find_one", "(", "cond", ",", "fields", "=", "ARTICLE_DETAIL_INFO_FIELDS", ")", "return", "article_infos" ]
https://github.com/WuXianglong/GeekBlog/blob/a4fe5e7de225c4891d498d8e9e8f9c0c47053b86/blog/geekblog/mongodb/blog.py#L118-L122
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/TargetSolver/TargetSolver.py
python
TargetSolver.solveMovement
(self, movement)
return solved_movement_list
Solves a movement.
Solves a movement.
[ "Solves", "a", "movement", "." ]
def solveMovement(self, movement): """ Solves a movement. """ # Apply to all simulation movements simulation_movement_list = movement.getDeliveryRelatedValueList( portal_type="Simulation Movement") solved_movement_list = [] for simulation_movement in simulation_movement_list: solved_movement_list.append(self.solve(simulation_movement)) return solved_movement_list
[ "def", "solveMovement", "(", "self", ",", "movement", ")", ":", "# Apply to all simulation movements", "simulation_movement_list", "=", "movement", ".", "getDeliveryRelatedValueList", "(", "portal_type", "=", "\"Simulation Movement\"", ")", "solved_movement_list", "=", "[", "]", "for", "simulation_movement", "in", "simulation_movement_list", ":", "solved_movement_list", ".", "append", "(", "self", ".", "solve", "(", "simulation_movement", ")", ")", "return", "solved_movement_list" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/TargetSolver/TargetSolver.py#L87-L97
talebook/talebook
55d7fceb3a8c00f12122893b9988274b9ea5758b
webserver/models.py
python
MutableDict.__setitem__
(self, key, value)
Detect dictionary set events and emit change events.
Detect dictionary set events and emit change events.
[ "Detect", "dictionary", "set", "events", "and", "emit", "change", "events", "." ]
def __setitem__(self, key, value): "Detect dictionary set events and emit change events." dict.__setitem__(self, key, value) self.changed()
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "dict", ".", "__setitem__", "(", "self", ",", "key", ",", "value", ")", "self", ".", "changed", "(", ")" ]
https://github.com/talebook/talebook/blob/55d7fceb3a8c00f12122893b9988274b9ea5758b/webserver/models.py#L60-L63
UWFlow/rmc
00bcc1450ffbec3a6c8d956a2a5d1bb3a04bfcb9
models/exam.py
python
Exam.to_schedule_obj
(self, term_id=None)
return _user_schedule_item.UserScheduleItem( id=self.id, class_num='', building=self.location, room='', section_type='EXAM', # TODO(david): Make this a constant section_num=self.sections, start_date=self.start_date, end_date=self.end_date, course_id=self.course_id, term_id=term_id or util.get_current_term_id(), )
Converts to a UserScheduleItem.
Converts to a UserScheduleItem.
[ "Converts", "to", "a", "UserScheduleItem", "." ]
def to_schedule_obj(self, term_id=None): """Converts to a UserScheduleItem.""" return _user_schedule_item.UserScheduleItem( id=self.id, class_num='', building=self.location, room='', section_type='EXAM', # TODO(david): Make this a constant section_num=self.sections, start_date=self.start_date, end_date=self.end_date, course_id=self.course_id, term_id=term_id or util.get_current_term_id(), )
[ "def", "to_schedule_obj", "(", "self", ",", "term_id", "=", "None", ")", ":", "return", "_user_schedule_item", ".", "UserScheduleItem", "(", "id", "=", "self", ".", "id", ",", "class_num", "=", "''", ",", "building", "=", "self", ".", "location", ",", "room", "=", "''", ",", "section_type", "=", "'EXAM'", ",", "# TODO(david): Make this a constant", "section_num", "=", "self", ".", "sections", ",", "start_date", "=", "self", ".", "start_date", ",", "end_date", "=", "self", ".", "end_date", ",", "course_id", "=", "self", ".", "course_id", ",", "term_id", "=", "term_id", "or", "util", ".", "get_current_term_id", "(", ")", ",", ")" ]
https://github.com/UWFlow/rmc/blob/00bcc1450ffbec3a6c8d956a2a5d1bb3a04bfcb9/models/exam.py#L39-L52
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
deps/v8/third_party/jinja2/utils.py
python
LRUCache.keys
(self)
return list(self)
Return a list of all keys ordered by most recent usage.
Return a list of all keys ordered by most recent usage.
[ "Return", "a", "list", "of", "all", "keys", "ordered", "by", "most", "recent", "usage", "." ]
def keys(self): """Return a list of all keys ordered by most recent usage.""" return list(self)
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ")" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/v8/third_party/jinja2/utils.py#L462-L464
wotermelon/toJump
3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f
lib/mac/systrace/catapult/devil/devil/android/sdk/gce_adb_wrapper.py
python
GceAdbWrapper._PushObject
(self, local, remote)
Copies an object from the host to the gce instance using scp. Args: local: Path on the host filesystem. remote: Path on the instance filesystem.
Copies an object from the host to the gce instance using scp.
[ "Copies", "an", "object", "from", "the", "host", "to", "the", "gce", "instance", "using", "scp", "." ]
def _PushObject(self, local, remote): """Copies an object from the host to the gce instance using scp. Args: local: Path on the host filesystem. remote: Path on the instance filesystem. """ cmd = [ 'scp', '-r', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no', local, 'root@%s:%s' % (self._instance_ip, remote) ] status, _ = cmd_helper.GetCmdStatusAndOutput(cmd) if status: raise device_errors.AdbCommandFailedError( cmd, 'File not reachable on host: %s' % local, device_serial=str(self))
[ "def", "_PushObject", "(", "self", ",", "local", ",", "remote", ")", ":", "cmd", "=", "[", "'scp'", ",", "'-r'", ",", "'-o'", ",", "'UserKnownHostsFile=/dev/null'", ",", "'-o'", ",", "'StrictHostKeyChecking=no'", ",", "local", ",", "'root@%s:%s'", "%", "(", "self", ".", "_instance_ip", ",", "remote", ")", "]", "status", ",", "_", "=", "cmd_helper", ".", "GetCmdStatusAndOutput", "(", "cmd", ")", "if", "status", ":", "raise", "device_errors", ".", "AdbCommandFailedError", "(", "cmd", ",", "'File not reachable on host: %s'", "%", "local", ",", "device_serial", "=", "str", "(", "self", ")", ")" ]
https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/mac/systrace/catapult/devil/devil/android/sdk/gce_adb_wrapper.py#L71-L90
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
src/pyasm/search/sql.py
python
AlterTable.commit
(self)
Commit one or more alter table statements
Commit one or more alter table statements
[ "Commit", "one", "or", "more", "alter", "table", "statements" ]
def commit(self): '''Commit one or more alter table statements''' sql = DbContainer.get(self.db_resource) impl = sql.get_database_impl() #database = sql.get_database_name() exists = impl.table_exists(self.db_resource, self.table) # check to see if autocommit should be on if impl.commit_on_schema_change(): DbContainer.commit_thread_sql() if exists: statements = self.get_statements() for statement in statements: sql.do_update(statement) else: print("WARNING: table [%s] does not exist ... skipping" % self.table)
[ "def", "commit", "(", "self", ")", ":", "sql", "=", "DbContainer", ".", "get", "(", "self", ".", "db_resource", ")", "impl", "=", "sql", ".", "get_database_impl", "(", ")", "#database = sql.get_database_name()", "exists", "=", "impl", ".", "table_exists", "(", "self", ".", "db_resource", ",", "self", ".", "table", ")", "# check to see if autocommit should be on", "if", "impl", ".", "commit_on_schema_change", "(", ")", ":", "DbContainer", ".", "commit_thread_sql", "(", ")", "if", "exists", ":", "statements", "=", "self", ".", "get_statements", "(", ")", "for", "statement", "in", "statements", ":", "sql", ".", "do_update", "(", "statement", ")", "else", ":", "print", "(", "\"WARNING: table [%s] does not exist ... skipping\"", "%", "self", ".", "table", ")" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/pyasm/search/sql.py#L3866-L3882
jam-py/jam-py
0821492cdff8665928e0f093a4435aa64285a45c
jam/third_party/sqlalchemy/engine/interfaces.py
python
Dialect.do_execute_no_params
( self, cursor, statement, parameters, context=None )
Provide an implementation of ``cursor.execute(statement)``. The parameter collection should not be sent.
Provide an implementation of ``cursor.execute(statement)``.
[ "Provide", "an", "implementation", "of", "cursor", ".", "execute", "(", "statement", ")", "." ]
def do_execute_no_params( self, cursor, statement, parameters, context=None ): """Provide an implementation of ``cursor.execute(statement)``. The parameter collection should not be sent. """ raise NotImplementedError()
[ "def", "do_execute_no_params", "(", "self", ",", "cursor", ",", "statement", ",", "parameters", ",", "context", "=", "None", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/sqlalchemy/engine/interfaces.py#L678-L687
rapidpro/rapidpro
8b6e58221fff967145f0b3411d85bcc15a0d3e72
temba/tickets/models.py
python
TicketCount.get_by_assignees
(cls, org, assignees: list, status: str)
return {a: counts_by_assignee.get(a.id if a else None, 0) for a in assignees}
Gets counts for a set of assignees (None means no assignee)
Gets counts for a set of assignees (None means no assignee)
[ "Gets", "counts", "for", "a", "set", "of", "assignees", "(", "None", "means", "no", "assignee", ")" ]
def get_by_assignees(cls, org, assignees: list, status: str) -> dict: """ Gets counts for a set of assignees (None means no assignee) """ counts = cls.objects.filter(org=org, status=status) counts = counts.values_list("assignee").annotate(count_sum=Sum("count")) counts_by_assignee = {c[0]: c[1] for c in counts} return {a: counts_by_assignee.get(a.id if a else None, 0) for a in assignees}
[ "def", "get_by_assignees", "(", "cls", ",", "org", ",", "assignees", ":", "list", ",", "status", ":", "str", ")", "->", "dict", ":", "counts", "=", "cls", ".", "objects", ".", "filter", "(", "org", "=", "org", ",", "status", "=", "status", ")", "counts", "=", "counts", ".", "values_list", "(", "\"assignee\"", ")", ".", "annotate", "(", "count_sum", "=", "Sum", "(", "\"count\"", ")", ")", "counts_by_assignee", "=", "{", "c", "[", "0", "]", ":", "c", "[", "1", "]", "for", "c", "in", "counts", "}", "return", "{", "a", ":", "counts_by_assignee", ".", "get", "(", "a", ".", "id", "if", "a", "else", "None", ",", "0", ")", "for", "a", "in", "assignees", "}" ]
https://github.com/rapidpro/rapidpro/blob/8b6e58221fff967145f0b3411d85bcc15a0d3e72/temba/tickets/models.py#L443-L451
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py
python
XmlToString
(content, encoding='utf-8', pretty=False)
return ''.join(xml_parts)
Writes the XML content to disk, touching the file only if it has changed. Visual Studio files have a lot of pre-defined structures. This function makes it easy to represent these structures as Python data structures, instead of having to create a lot of function calls. Each XML element of the content is represented as a list composed of: 1. The name of the element, a string, 2. The attributes of the element, a dictionary (optional), and 3+. The content of the element, if any. Strings are simple text nodes and lists are child elements. Example 1: <test/> becomes ['test'] Example 2: <myelement a='value1' b='value2'> <childtype>This is</childtype> <childtype>it!</childtype> </myelement> becomes ['myelement', {'a':'value1', 'b':'value2'}, ['childtype', 'This is'], ['childtype', 'it!'], ] Args: content: The structured content to be converted. encoding: The encoding to report on the first XML line. pretty: True if we want pretty printing with indents and new lines. Returns: The XML content as a string.
Writes the XML content to disk, touching the file only if it has changed.
[ "Writes", "the", "XML", "content", "to", "disk", "touching", "the", "file", "only", "if", "it", "has", "changed", "." ]
def XmlToString(content, encoding='utf-8', pretty=False): """ Writes the XML content to disk, touching the file only if it has changed. Visual Studio files have a lot of pre-defined structures. This function makes it easy to represent these structures as Python data structures, instead of having to create a lot of function calls. Each XML element of the content is represented as a list composed of: 1. The name of the element, a string, 2. The attributes of the element, a dictionary (optional), and 3+. The content of the element, if any. Strings are simple text nodes and lists are child elements. Example 1: <test/> becomes ['test'] Example 2: <myelement a='value1' b='value2'> <childtype>This is</childtype> <childtype>it!</childtype> </myelement> becomes ['myelement', {'a':'value1', 'b':'value2'}, ['childtype', 'This is'], ['childtype', 'it!'], ] Args: content: The structured content to be converted. encoding: The encoding to report on the first XML line. pretty: True if we want pretty printing with indents and new lines. Returns: The XML content as a string. """ # We create a huge list of all the elements of the file. xml_parts = ['<?xml version="1.0" encoding="%s"?>' % encoding] if pretty: xml_parts.append('\n') _ConstructContentList(xml_parts, content, pretty) # Convert it to a string return ''.join(xml_parts)
[ "def", "XmlToString", "(", "content", ",", "encoding", "=", "'utf-8'", ",", "pretty", "=", "False", ")", ":", "# We create a huge list of all the elements of the file.", "xml_parts", "=", "[", "'<?xml version=\"1.0\" encoding=\"%s\"?>'", "%", "encoding", "]", "if", "pretty", ":", "xml_parts", ".", "append", "(", "'\\n'", ")", "_ConstructContentList", "(", "xml_parts", ",", "content", ",", "pretty", ")", "# Convert it to a string", "return", "''", ".", "join", "(", "xml_parts", ")" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py#L9-L54
TeamvisionCorp/TeamVision
aa2a57469e430ff50cce21174d8f280efa0a83a7
distribute/0.0.4/build_shell/teamvision/teamvision/api/project/viewmodel/project_statistics_charts/vm_highchart.py
python
VM_HighChart.__init__
(self,project_id,version_id)
Constructor
Constructor
[ "Constructor" ]
def __init__(self,project_id,version_id): ''' Constructor ''' self.chart_id=0 self.project_id=project_id self.version_id=version_id
[ "def", "__init__", "(", "self", ",", "project_id", ",", "version_id", ")", ":", "self", ".", "chart_id", "=", "0", "self", ".", "project_id", "=", "project_id", "self", ".", "version_id", "=", "version_id" ]
https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.4/build_shell/teamvision/teamvision/api/project/viewmodel/project_statistics_charts/vm_highchart.py#L15-L21
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py
python
FixPEP8.fix_w391
(self, _)
return range(1, 1 + original_length)
Remove trailing blank lines.
Remove trailing blank lines.
[ "Remove", "trailing", "blank", "lines", "." ]
def fix_w391(self, _): """Remove trailing blank lines.""" blank_count = 0 for line in reversed(self.source): line = line.rstrip() if line: break else: blank_count += 1 original_length = len(self.source) self.source = self.source[:original_length - blank_count] return range(1, 1 + original_length)
[ "def", "fix_w391", "(", "self", ",", "_", ")", ":", "blank_count", "=", "0", "for", "line", "in", "reversed", "(", "self", ".", "source", ")", ":", "line", "=", "line", ".", "rstrip", "(", ")", "if", "line", ":", "break", "else", ":", "blank_count", "+=", "1", "original_length", "=", "len", "(", "self", ".", "source", ")", "self", ".", "source", "=", "self", ".", "source", "[", ":", "original_length", "-", "blank_count", "]", "return", "range", "(", "1", ",", "1", "+", "original_length", ")" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/autopep8.py#L1080-L1092
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
bt5/erp5_syncml/DocumentTemplateItem/portal_components/document.erp5.SyncMLSubscription.py
python
SyncMLSubscription.applyActionList
(self, syncml_request, syncml_response, simulate=False)
Browse the list of sync command received, apply them and generate answer
Browse the list of sync command received, apply them and generate answer
[ "Browse", "the", "list", "of", "sync", "command", "received", "apply", "them", "and", "generate", "answer" ]
def applyActionList(self, syncml_request, syncml_response, simulate=False): """ Browse the list of sync command received, apply them and generate answer """ for action in syncml_request.sync_command_list: self._applySyncCommand( action=action, request_message_id=syncml_request.header["message_id"], syncml_response=syncml_response, simulate=simulate)
[ "def", "applyActionList", "(", "self", ",", "syncml_request", ",", "syncml_response", ",", "simulate", "=", "False", ")", ":", "for", "action", "in", "syncml_request", ".", "sync_command_list", ":", "self", ".", "_applySyncCommand", "(", "action", "=", "action", ",", "request_message_id", "=", "syncml_request", ".", "header", "[", "\"message_id\"", "]", ",", "syncml_response", "=", "syncml_response", ",", "simulate", "=", "simulate", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_syncml/DocumentTemplateItem/portal_components/document.erp5.SyncMLSubscription.py#L419-L428
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
GenerateOutput
(target_list, target_dicts, data, params)
Generate .sln and .vcproj files. This is the entry point for this generator. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. data: Dictionary containing per .gyp data.
Generate .sln and .vcproj files.
[ "Generate", ".", "sln", "and", ".", "vcproj", "files", "." ]
def GenerateOutput(target_list, target_dicts, data, params): """Generate .sln and .vcproj files. This is the entry point for this generator. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. data: Dictionary containing per .gyp data. """ global fixpath_prefix options = params['options'] # Get the project file format version back out of where we stashed it in # GeneratorCalculatedVariables. msvs_version = params['msvs_version'] generator_flags = params.get('generator_flags', {}) # Optionally shard targets marked with 'msvs_shard': SHARD_COUNT. (target_list, target_dicts) = MSVSUtil.ShardTargets(target_list, target_dicts) # Optionally use the large PDB workaround for targets marked with # 'msvs_large_pdb': 1. (target_list, target_dicts) = MSVSUtil.InsertLargePdbShims( target_list, target_dicts, generator_default_variables) # Optionally configure each spec to use ninja as the external builder. if params.get('flavor') == 'ninja': _InitNinjaFlavor(params, target_list, target_dicts) # Prepare the set of configurations. configs = set() for qualified_target in target_list: spec = target_dicts[qualified_target] for config_name, config in spec['configurations'].iteritems(): configs.add(_ConfigFullName(config_name, config)) configs = list(configs) # Figure out all the projects that will be generated and their guids project_objects = _CreateProjectObjects(target_list, target_dicts, options, msvs_version) # Generate each project. missing_sources = [] for project in project_objects.values(): fixpath_prefix = project.fixpath_prefix missing_sources.extend(_GenerateProject(project, options, msvs_version, generator_flags)) fixpath_prefix = None for build_file in data: # Validate build_file extension if not build_file.endswith('.gyp'): continue sln_path = os.path.splitext(build_file)[0] + options.suffix + '.sln' if options.generator_output: sln_path = os.path.join(options.generator_output, sln_path) # Get projects in the solution, and their dependents. sln_projects = gyp.common.BuildFileTargets(target_list, build_file) sln_projects += gyp.common.DeepDependencyTargets(target_dicts, sln_projects) # Create folder hierarchy. root_entries = _GatherSolutionFolders( sln_projects, project_objects, flat=msvs_version.FlatSolution()) # Create solution. sln = MSVSNew.MSVSSolution(sln_path, entries=root_entries, variants=configs, websiteProperties=False, version=msvs_version) sln.Write() if missing_sources: error_message = "Missing input files:\n" + \ '\n'.join(set(missing_sources)) if generator_flags.get('msvs_error_on_missing_sources', False): raise GypError(error_message) else: print >> sys.stdout, "Warning: " + error_message
[ "def", "GenerateOutput", "(", "target_list", ",", "target_dicts", ",", "data", ",", "params", ")", ":", "global", "fixpath_prefix", "options", "=", "params", "[", "'options'", "]", "# Get the project file format version back out of where we stashed it in", "# GeneratorCalculatedVariables.", "msvs_version", "=", "params", "[", "'msvs_version'", "]", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "# Optionally shard targets marked with 'msvs_shard': SHARD_COUNT.", "(", "target_list", ",", "target_dicts", ")", "=", "MSVSUtil", ".", "ShardTargets", "(", "target_list", ",", "target_dicts", ")", "# Optionally use the large PDB workaround for targets marked with", "# 'msvs_large_pdb': 1.", "(", "target_list", ",", "target_dicts", ")", "=", "MSVSUtil", ".", "InsertLargePdbShims", "(", "target_list", ",", "target_dicts", ",", "generator_default_variables", ")", "# Optionally configure each spec to use ninja as the external builder.", "if", "params", ".", "get", "(", "'flavor'", ")", "==", "'ninja'", ":", "_InitNinjaFlavor", "(", "params", ",", "target_list", ",", "target_dicts", ")", "# Prepare the set of configurations.", "configs", "=", "set", "(", ")", "for", "qualified_target", "in", "target_list", ":", "spec", "=", "target_dicts", "[", "qualified_target", "]", "for", "config_name", ",", "config", "in", "spec", "[", "'configurations'", "]", ".", "iteritems", "(", ")", ":", "configs", ".", "add", "(", "_ConfigFullName", "(", "config_name", ",", "config", ")", ")", "configs", "=", "list", "(", "configs", ")", "# Figure out all the projects that will be generated and their guids", "project_objects", "=", "_CreateProjectObjects", "(", "target_list", ",", "target_dicts", ",", "options", ",", "msvs_version", ")", "# Generate each project.", "missing_sources", "=", "[", "]", "for", "project", "in", "project_objects", ".", "values", "(", ")", ":", "fixpath_prefix", "=", "project", ".", "fixpath_prefix", "missing_sources", ".", "extend", "(", "_GenerateProject", "(", "project", ",", "options", ",", "msvs_version", ",", "generator_flags", ")", ")", "fixpath_prefix", "=", "None", "for", "build_file", "in", "data", ":", "# Validate build_file extension", "if", "not", "build_file", ".", "endswith", "(", "'.gyp'", ")", ":", "continue", "sln_path", "=", "os", ".", "path", ".", "splitext", "(", "build_file", ")", "[", "0", "]", "+", "options", ".", "suffix", "+", "'.sln'", "if", "options", ".", "generator_output", ":", "sln_path", "=", "os", ".", "path", ".", "join", "(", "options", ".", "generator_output", ",", "sln_path", ")", "# Get projects in the solution, and their dependents.", "sln_projects", "=", "gyp", ".", "common", ".", "BuildFileTargets", "(", "target_list", ",", "build_file", ")", "sln_projects", "+=", "gyp", ".", "common", ".", "DeepDependencyTargets", "(", "target_dicts", ",", "sln_projects", ")", "# Create folder hierarchy.", "root_entries", "=", "_GatherSolutionFolders", "(", "sln_projects", ",", "project_objects", ",", "flat", "=", "msvs_version", ".", "FlatSolution", "(", ")", ")", "# Create solution.", "sln", "=", "MSVSNew", ".", "MSVSSolution", "(", "sln_path", ",", "entries", "=", "root_entries", ",", "variants", "=", "configs", ",", "websiteProperties", "=", "False", ",", "version", "=", "msvs_version", ")", "sln", ".", "Write", "(", ")", "if", "missing_sources", ":", "error_message", "=", "\"Missing input files:\\n\"", "+", "'\\n'", ".", "join", "(", "set", "(", "missing_sources", ")", ")", "if", "generator_flags", ".", "get", "(", "'msvs_error_on_missing_sources'", ",", "False", ")", ":", "raise", "GypError", "(", "error_message", ")", "else", ":", "print", ">>", "sys", ".", "stdout", ",", "\"Warning: \"", "+", "error_message" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L1956-L2034
korolr/dotfiles
8e46933503ecb8d8651739ffeb1d2d4f0f5c6524
.config/sublime-text-3/Packages/python-markdown/st3/markdown/extensions/footnotes.py
python
FootnotePostTreeprocessor.handle_duplicates
(self, parent)
Find duplicate footnotes and format and add the duplicates.
Find duplicate footnotes and format and add the duplicates.
[ "Find", "duplicate", "footnotes", "and", "format", "and", "add", "the", "duplicates", "." ]
def handle_duplicates(self, parent): """ Find duplicate footnotes and format and add the duplicates. """ for li in list(parent): # Check number of duplicates footnotes and insert # additional links if needed. count = self.get_num_duplicates(li) if count > 1: self.add_duplicates(li, count)
[ "def", "handle_duplicates", "(", "self", ",", "parent", ")", ":", "for", "li", "in", "list", "(", "parent", ")", ":", "# Check number of duplicates footnotes and insert", "# additional links if needed.", "count", "=", "self", ".", "get_num_duplicates", "(", "li", ")", "if", "count", ">", "1", ":", "self", ".", "add_duplicates", "(", "li", ",", "count", ")" ]
https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/python-markdown/st3/markdown/extensions/footnotes.py#L373-L380
quantifiedcode/quantifiedcode
cafc8b99d56a5e51820421af5d77be8b736ab03d
quantifiedcode/helpers/settings.py
python
Settings.load_plugin
(self, name)
Loads the plugin with the given name :param name: name of the plugin to load
Loads the plugin with the given name :param name: name of the plugin to load
[ "Loads", "the", "plugin", "with", "the", "given", "name", ":", "param", "name", ":", "name", "of", "the", "plugin", "to", "load" ]
def load_plugin(self, name): """ Loads the plugin with the given name :param name: name of the plugin to load """ plugin_data = self.get('plugins.{}'.format(name)) if plugin_data is None: raise ValueError("Unknown plugin: {}".format(name)) logger.info("Loading plugin: {}".format(name)) config = self.load_plugin_config(name) #register models for model in config.get('models',[]): self.backend.register(model) #register providers for name, params in config.get('providers',{}).items(): self.providers[name].append(params) # register hooks for hook_name, hook_function in config.get('hooks', []): self.hooks.register(hook_name, hook_function) for filename in config.get('yaml_settings', []): with open(filename) as yaml_file: settings_yaml = yaml.load(yaml_file.read()) update(self._d, settings_yaml, overwrite=False) if config.get('settings'): update(self._d, config['settings'])
[ "def", "load_plugin", "(", "self", ",", "name", ")", ":", "plugin_data", "=", "self", ".", "get", "(", "'plugins.{}'", ".", "format", "(", "name", ")", ")", "if", "plugin_data", "is", "None", ":", "raise", "ValueError", "(", "\"Unknown plugin: {}\"", ".", "format", "(", "name", ")", ")", "logger", ".", "info", "(", "\"Loading plugin: {}\"", ".", "format", "(", "name", ")", ")", "config", "=", "self", ".", "load_plugin_config", "(", "name", ")", "#register models", "for", "model", "in", "config", ".", "get", "(", "'models'", ",", "[", "]", ")", ":", "self", ".", "backend", ".", "register", "(", "model", ")", "#register providers", "for", "name", ",", "params", "in", "config", ".", "get", "(", "'providers'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "self", ".", "providers", "[", "name", "]", ".", "append", "(", "params", ")", "# register hooks", "for", "hook_name", ",", "hook_function", "in", "config", ".", "get", "(", "'hooks'", ",", "[", "]", ")", ":", "self", ".", "hooks", ".", "register", "(", "hook_name", ",", "hook_function", ")", "for", "filename", "in", "config", ".", "get", "(", "'yaml_settings'", ",", "[", "]", ")", ":", "with", "open", "(", "filename", ")", "as", "yaml_file", ":", "settings_yaml", "=", "yaml", ".", "load", "(", "yaml_file", ".", "read", "(", ")", ")", "update", "(", "self", ".", "_d", ",", "settings_yaml", ",", "overwrite", "=", "False", ")", "if", "config", ".", "get", "(", "'settings'", ")", ":", "update", "(", "self", ".", "_d", ",", "config", "[", "'settings'", "]", ")" ]
https://github.com/quantifiedcode/quantifiedcode/blob/cafc8b99d56a5e51820421af5d77be8b736ab03d/quantifiedcode/helpers/settings.py#L134-L164
lambdamusic/Ontospy
534e408372edd392590e12839c32a403430aac23
ontospy/core/utils.py
python
get_files_with_extensions
(folder, extensions)
return out
walk dir and return .* files as a list. Hidden files are ignored. Note: directories are walked recursively
walk dir and return .* files as a list. Hidden files are ignored. Note: directories are walked recursively
[ "walk", "dir", "and", "return", ".", "*", "files", "as", "a", "list", ".", "Hidden", "files", "are", "ignored", ".", "Note", ":", "directories", "are", "walked", "recursively" ]
def get_files_with_extensions(folder, extensions): """walk dir and return .* files as a list. Hidden files are ignored. Note: directories are walked recursively""" out = [] for root, dirs, files in os.walk(folder): for file in files: filename, file_extension = os.path.splitext(file) if not filename.startswith('.') and file_extension.replace(".", "") in extensions: out += [os.path.join(root, file)] # break return out
[ "def", "get_files_with_extensions", "(", "folder", ",", "extensions", ")", ":", "out", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "folder", ")", ":", "for", "file", "in", "files", ":", "filename", ",", "file_extension", "=", "os", ".", "path", ".", "splitext", "(", "file", ")", "if", "not", "filename", ".", "startswith", "(", "'.'", ")", "and", "file_extension", ".", "replace", "(", "\".\"", ",", "\"\"", ")", "in", "extensions", ":", "out", "+=", "[", "os", ".", "path", ".", "join", "(", "root", ",", "file", ")", "]", "# break", "return", "out" ]
https://github.com/lambdamusic/Ontospy/blob/534e408372edd392590e12839c32a403430aac23/ontospy/core/utils.py#L898-L909
stdlib-js/stdlib
e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df
lib/node_modules/@stdlib/stats/base/dists/beta/variance/benchmark/python/benchmark.scipy.py
python
benchmark
()
Run the benchmark and print benchmark results.
Run the benchmark and print benchmark results.
[ "Run", "the", "benchmark", "and", "print", "benchmark", "results", "." ]
def benchmark(): """Run the benchmark and print benchmark results.""" setup = "from scipy.stats import beta; from random import random;" stmt = "y = beta.var(random()*10.0 + 1.0, random()*10.0 + 1.0)" t = timeit.Timer(stmt, setup=setup) print_version() for i in range(REPEATS): print("# python::" + NAME) elapsed = t.timeit(number=ITERATIONS) print_results(elapsed) print("ok " + str(i+1) + " benchmark finished") print_summary(REPEATS, REPEATS)
[ "def", "benchmark", "(", ")", ":", "setup", "=", "\"from scipy.stats import beta; from random import random;\"", "stmt", "=", "\"y = beta.var(random()*10.0 + 1.0, random()*10.0 + 1.0)\"", "t", "=", "timeit", ".", "Timer", "(", "stmt", ",", "setup", "=", "setup", ")", "print_version", "(", ")", "for", "i", "in", "range", "(", "REPEATS", ")", ":", "print", "(", "\"# python::\"", "+", "NAME", ")", "elapsed", "=", "t", ".", "timeit", "(", "number", "=", "ITERATIONS", ")", "print_results", "(", "elapsed", ")", "print", "(", "\"ok \"", "+", "str", "(", "i", "+", "1", ")", "+", "\" benchmark finished\"", ")", "print_summary", "(", "REPEATS", ",", "REPEATS", ")" ]
https://github.com/stdlib-js/stdlib/blob/e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df/lib/node_modules/@stdlib/stats/base/dists/beta/variance/benchmark/python/benchmark.scipy.py#L73-L88
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py
python
_Same
(tool, name, setting_type)
Defines a setting that has the same name in MSVS and MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting.
Defines a setting that has the same name in MSVS and MSBuild.
[ "Defines", "a", "setting", "that", "has", "the", "same", "name", "in", "MSVS", "and", "MSBuild", "." ]
def _Same(tool, name, setting_type): """Defines a setting that has the same name in MSVS and MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ _Renamed(tool, name, name, setting_type)
[ "def", "_Same", "(", "tool", ",", "name", ",", "setting_type", ")", ":", "_Renamed", "(", "tool", ",", "name", ",", "name", ",", "setting_type", ")" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L233-L241
Jumpscale/go-raml
f151e1e143c47282b294fe70c5e56f113988ed10
docs/tutorial/python/requests_client/goramldir/client_support.py
python
timestamp_to_datetime
(timestamp)
return parser.parse(timestamp).replace(tzinfo=None)
Convert from timestamp format to datetime format Input: Time in timestamp format Output: Time in datetime format
Convert from timestamp format to datetime format Input: Time in timestamp format Output: Time in datetime format
[ "Convert", "from", "timestamp", "format", "to", "datetime", "format", "Input", ":", "Time", "in", "timestamp", "format", "Output", ":", "Time", "in", "datetime", "format" ]
def timestamp_to_datetime(timestamp): """ Convert from timestamp format to datetime format Input: Time in timestamp format Output: Time in datetime format """ return parser.parse(timestamp).replace(tzinfo=None)
[ "def", "timestamp_to_datetime", "(", "timestamp", ")", ":", "return", "parser", ".", "parse", "(", "timestamp", ")", ".", "replace", "(", "tzinfo", "=", "None", ")" ]
https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/docs/tutorial/python/requests_client/goramldir/client_support.py#L31-L37
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/Sqlmap/lib/utils/api.py
python
option_set
(taskid)
return jsonize({"success": True})
Set an option (command line switch) for a certain task ID
Set an option (command line switch) for a certain task ID
[ "Set", "an", "option", "(", "command", "line", "switch", ")", "for", "a", "certain", "task", "ID" ]
def option_set(taskid): """ Set an option (command line switch) for a certain task ID """ if taskid not in DataStore.tasks: logger.warning("[%s] Invalid task ID provided to option_set()" % taskid) return jsonize({"success": False, "message": "Invalid task ID"}) for option, value in request.json.items(): DataStore.tasks[taskid].set_option(option, value) logger.debug("[%s] Requested to set options" % taskid) return jsonize({"success": True})
[ "def", "option_set", "(", "taskid", ")", ":", "if", "taskid", "not", "in", "DataStore", ".", "tasks", ":", "logger", ".", "warning", "(", "\"[%s] Invalid task ID provided to option_set()\"", "%", "taskid", ")", "return", "jsonize", "(", "{", "\"success\"", ":", "False", ",", "\"message\"", ":", "\"Invalid task ID\"", "}", ")", "for", "option", ",", "value", "in", "request", ".", "json", ".", "items", "(", ")", ":", "DataStore", ".", "tasks", "[", "taskid", "]", ".", "set_option", "(", "option", ",", "value", ")", "logger", ".", "debug", "(", "\"[%s] Requested to set options\"", "%", "taskid", ")", "return", "jsonize", "(", "{", "\"success\"", ":", "True", "}", ")" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/lib/utils/api.py#L440-L452
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_AddAccumulatedActionsToMSVS
(p, spec, actions_dict)
Add actions accumulated into an actions_dict, merging as needed. Arguments: p: the target project spec: the target project dict actions_dict: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file.
Add actions accumulated into an actions_dict, merging as needed.
[ "Add", "actions", "accumulated", "into", "an", "actions_dict", "merging", "as", "needed", "." ]
def _AddAccumulatedActionsToMSVS(p, spec, actions_dict): """Add actions accumulated into an actions_dict, merging as needed. Arguments: p: the target project spec: the target project dict actions_dict: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. """ for primary_input in actions_dict: inputs = OrderedSet() outputs = OrderedSet() descriptions = [] commands = [] for action in actions_dict[primary_input]: inputs.update(OrderedSet(action['inputs'])) outputs.update(OrderedSet(action['outputs'])) descriptions.append(action['description']) commands.append(action['command']) # Add the custom build step for one input file. description = ', and also '.join(descriptions) command = '\r\n'.join(commands) _AddCustomBuildToolForMSVS(p, spec, primary_input=primary_input, inputs=inputs, outputs=outputs, description=description, cmd=command)
[ "def", "_AddAccumulatedActionsToMSVS", "(", "p", ",", "spec", ",", "actions_dict", ")", ":", "for", "primary_input", "in", "actions_dict", ":", "inputs", "=", "OrderedSet", "(", ")", "outputs", "=", "OrderedSet", "(", ")", "descriptions", "=", "[", "]", "commands", "=", "[", "]", "for", "action", "in", "actions_dict", "[", "primary_input", "]", ":", "inputs", ".", "update", "(", "OrderedSet", "(", "action", "[", "'inputs'", "]", ")", ")", "outputs", ".", "update", "(", "OrderedSet", "(", "action", "[", "'outputs'", "]", ")", ")", "descriptions", ".", "append", "(", "action", "[", "'description'", "]", ")", "commands", ".", "append", "(", "action", "[", "'command'", "]", ")", "# Add the custom build step for one input file.", "description", "=", "', and also '", ".", "join", "(", "descriptions", ")", "command", "=", "'\\r\\n'", ".", "join", "(", "commands", ")", "_AddCustomBuildToolForMSVS", "(", "p", ",", "spec", ",", "primary_input", "=", "primary_input", ",", "inputs", "=", "inputs", ",", "outputs", "=", "outputs", ",", "description", "=", "description", ",", "cmd", "=", "command", ")" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L457-L484
silklabs/silk
08c273949086350aeddd8e23e92f0f79243f446f
node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
QuoteForRspFile
(arg)
return '"' + arg + '"'
Quote a command line argument so that it appears as one argument when processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for Windows programs).
Quote a command line argument so that it appears as one argument when processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for Windows programs).
[ "Quote", "a", "command", "line", "argument", "so", "that", "it", "appears", "as", "one", "argument", "when", "processed", "via", "cmd", ".", "exe", "and", "parsed", "by", "CommandLineToArgvW", "(", "as", "is", "typical", "for", "Windows", "programs", ")", "." ]
def QuoteForRspFile(arg): """Quote a command line argument so that it appears as one argument when processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for Windows programs).""" # See http://goo.gl/cuFbX and http://goo.gl/dhPnp including the comment # threads. This is actually the quoting rules for CommandLineToArgvW, not # for the shell, because the shell doesn't do anything in Windows. This # works more or less because most programs (including the compiler, etc.) # use that function to handle command line arguments. # For a literal quote, CommandLineToArgvW requires 2n+1 backslashes # preceding it, and results in n backslashes + the quote. So we substitute # in 2* what we match, +1 more, plus the quote. arg = windows_quoter_regex.sub(lambda mo: 2 * mo.group(1) + '\\"', arg) # %'s also need to be doubled otherwise they're interpreted as batch # positional arguments. Also make sure to escape the % so that they're # passed literally through escaping so they can be singled to just the # original %. Otherwise, trying to pass the literal representation that # looks like an environment variable to the shell (e.g. %PATH%) would fail. arg = arg.replace('%', '%%') # These commands are used in rsp files, so no escaping for the shell (via ^) # is necessary. # Finally, wrap the whole thing in quotes so that the above quote rule # applies and whitespace isn't a word break. return '"' + arg + '"'
[ "def", "QuoteForRspFile", "(", "arg", ")", ":", "# See http://goo.gl/cuFbX and http://goo.gl/dhPnp including the comment", "# threads. This is actually the quoting rules for CommandLineToArgvW, not", "# for the shell, because the shell doesn't do anything in Windows. This", "# works more or less because most programs (including the compiler, etc.)", "# use that function to handle command line arguments.", "# For a literal quote, CommandLineToArgvW requires 2n+1 backslashes", "# preceding it, and results in n backslashes + the quote. So we substitute", "# in 2* what we match, +1 more, plus the quote.", "arg", "=", "windows_quoter_regex", ".", "sub", "(", "lambda", "mo", ":", "2", "*", "mo", ".", "group", "(", "1", ")", "+", "'\\\\\"'", ",", "arg", ")", "# %'s also need to be doubled otherwise they're interpreted as batch", "# positional arguments. Also make sure to escape the % so that they're", "# passed literally through escaping so they can be singled to just the", "# original %. Otherwise, trying to pass the literal representation that", "# looks like an environment variable to the shell (e.g. %PATH%) would fail.", "arg", "=", "arg", ".", "replace", "(", "'%'", ",", "'%%'", ")", "# These commands are used in rsp files, so no escaping for the shell (via ^)", "# is necessary.", "# Finally, wrap the whole thing in quotes so that the above quote rule", "# applies and whitespace isn't a word break.", "return", "'\"'", "+", "arg", "+", "'\"'" ]
https://github.com/silklabs/silk/blob/08c273949086350aeddd8e23e92f0f79243f446f/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L23-L50
CivilHub/CivilHub
97c3ebe6031e6a3600c09d0fd99b764448ca592d
postman/templatetags/postman_tags.py
python
OrderByNode.render
(self, context)
return '?'+gets.urlencode() if gets else ''
Return a formatted GET query string, as "?order_key=order_val". Preserves existing GET's keys, if any, such as a page number. For that, the view has to provide request.GET in a 'gets' entry of the context.
Return a formatted GET query string, as "?order_key=order_val".
[ "Return", "a", "formatted", "GET", "query", "string", "as", "?order_key", "=", "order_val", "." ]
def render(self, context): """ Return a formatted GET query string, as "?order_key=order_val". Preserves existing GET's keys, if any, such as a page number. For that, the view has to provide request.GET in a 'gets' entry of the context. """ if 'gets' in context: gets = context['gets'].copy() else: gets = QueryDict('').copy() if ORDER_BY_KEY in gets: code = gets.pop(ORDER_BY_KEY)[0] else: code = None if self.code: gets[ORDER_BY_KEY] = self.code if self.code != code else self.code.upper() return '?'+gets.urlencode() if gets else ''
[ "def", "render", "(", "self", ",", "context", ")", ":", "if", "'gets'", "in", "context", ":", "gets", "=", "context", "[", "'gets'", "]", ".", "copy", "(", ")", "else", ":", "gets", "=", "QueryDict", "(", "''", ")", ".", "copy", "(", ")", "if", "ORDER_BY_KEY", "in", "gets", ":", "code", "=", "gets", ".", "pop", "(", "ORDER_BY_KEY", ")", "[", "0", "]", "else", ":", "code", "=", "None", "if", "self", ".", "code", ":", "gets", "[", "ORDER_BY_KEY", "]", "=", "self", ".", "code", "if", "self", ".", "code", "!=", "code", "else", "self", ".", "code", ".", "upper", "(", ")", "return", "'?'", "+", "gets", ".", "urlencode", "(", ")", "if", "gets", "else", "''" ]
https://github.com/CivilHub/CivilHub/blob/97c3ebe6031e6a3600c09d0fd99b764448ca592d/postman/templatetags/postman_tags.py#L77-L95
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/pytree.py
python
WildcardPattern._iterative_matches
(self, nodes)
Helper to iteratively yield the matches.
Helper to iteratively yield the matches.
[ "Helper", "to", "iteratively", "yield", "the", "matches", "." ]
def _iterative_matches(self, nodes): """Helper to iteratively yield the matches.""" nodelen = len(nodes) if 0 >= self.min: yield 0, {} results = [] # generate matches that use just one alt from self.content for alt in self.content: for c, r in generate_matches(alt, nodes): yield c, r results.append((c, r)) # for each match, iterate down the nodes while results: new_results = [] for c0, r0 in results: # stop if the entire set of nodes has been matched if c0 < nodelen and c0 <= self.max: for alt in self.content: for c1, r1 in generate_matches(alt, nodes[c0:]): if c1 > 0: r = {} r.update(r0) r.update(r1) yield c0 + c1, r new_results.append((c0 + c1, r)) results = new_results
[ "def", "_iterative_matches", "(", "self", ",", "nodes", ")", ":", "nodelen", "=", "len", "(", "nodes", ")", "if", "0", ">=", "self", ".", "min", ":", "yield", "0", ",", "{", "}", "results", "=", "[", "]", "# generate matches that use just one alt from self.content", "for", "alt", "in", "self", ".", "content", ":", "for", "c", ",", "r", "in", "generate_matches", "(", "alt", ",", "nodes", ")", ":", "yield", "c", ",", "r", "results", ".", "append", "(", "(", "c", ",", "r", ")", ")", "# for each match, iterate down the nodes", "while", "results", ":", "new_results", "=", "[", "]", "for", "c0", ",", "r0", "in", "results", ":", "# stop if the entire set of nodes has been matched", "if", "c0", "<", "nodelen", "and", "c0", "<=", "self", ".", "max", ":", "for", "alt", "in", "self", ".", "content", ":", "for", "c1", ",", "r1", "in", "generate_matches", "(", "alt", ",", "nodes", "[", "c0", ":", "]", ")", ":", "if", "c1", ">", "0", ":", "r", "=", "{", "}", "r", ".", "update", "(", "r0", ")", "r", ".", "update", "(", "r1", ")", "yield", "c0", "+", "c1", ",", "r", "new_results", ".", "append", "(", "(", "c0", "+", "c1", ",", "r", ")", ")", "results", "=", "new_results" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/pytree.py#L767-L794
ijason/NodeJS-Sample-App
a09d085cee52d07523ed87c8aa35a8bcb1c31537
EmployeeDB/node_modules/mongodb/upload.py
python
GuessVCSName
(options)
return (VCS_UNKNOWN, None)
Helper to guess the version control system. This examines the current directory, guesses which VersionControlSystem we're using, and returns an string indicating which VCS is detected. Returns: A pair (vcs, output). vcs is a string indicating which VCS was detected and is one of VCS_GIT, VCS_MERCURIAL, VCS_SUBVERSION, VCS_PERFORCE, VCS_CVS, or VCS_UNKNOWN. Since local perforce repositories can't be easily detected, this method will only guess VCS_PERFORCE if any perforce options have been specified. output is a string containing any interesting output from the vcs detection routine, or None if there is nothing interesting.
Helper to guess the version control system.
[ "Helper", "to", "guess", "the", "version", "control", "system", "." ]
def GuessVCSName(options): """Helper to guess the version control system. This examines the current directory, guesses which VersionControlSystem we're using, and returns an string indicating which VCS is detected. Returns: A pair (vcs, output). vcs is a string indicating which VCS was detected and is one of VCS_GIT, VCS_MERCURIAL, VCS_SUBVERSION, VCS_PERFORCE, VCS_CVS, or VCS_UNKNOWN. Since local perforce repositories can't be easily detected, this method will only guess VCS_PERFORCE if any perforce options have been specified. output is a string containing any interesting output from the vcs detection routine, or None if there is nothing interesting. """ for attribute, value in options.__dict__.iteritems(): if attribute.startswith("p4") and value != None: return (VCS_PERFORCE, None) def RunDetectCommand(vcs_type, command): """Helper to detect VCS by executing command. Returns: A pair (vcs, output) or None. Throws exception on error. """ try: out, returncode = RunShellWithReturnCode(command) if returncode == 0: return (vcs_type, out.strip()) except OSError, (errcode, message): if errcode != errno.ENOENT: # command not found code raise # Mercurial has a command to get the base directory of a repository # Try running it, but don't die if we don't have hg installed. # NOTE: we try Mercurial first as it can sit on top of an SVN working copy. res = RunDetectCommand(VCS_MERCURIAL, ["hg", "root"]) if res != None: return res # Subversion from 1.7 has a single centralized .svn folder # ( see http://subversion.apache.org/docs/release-notes/1.7.html#wc-ng ) # That's why we use 'svn info' instead of checking for .svn dir res = RunDetectCommand(VCS_SUBVERSION, ["svn", "info"]) if res != None: return res # Git has a command to test if you're in a git tree. # Try running it, but don't die if we don't have git installed. res = RunDetectCommand(VCS_GIT, ["git", "rev-parse", "--is-inside-work-tree"]) if res != None: return res # detect CVS repos use `cvs status && $? == 0` rules res = RunDetectCommand(VCS_CVS, ["cvs", "status"]) if res != None: return res return (VCS_UNKNOWN, None)
[ "def", "GuessVCSName", "(", "options", ")", ":", "for", "attribute", ",", "value", "in", "options", ".", "__dict__", ".", "iteritems", "(", ")", ":", "if", "attribute", ".", "startswith", "(", "\"p4\"", ")", "and", "value", "!=", "None", ":", "return", "(", "VCS_PERFORCE", ",", "None", ")", "def", "RunDetectCommand", "(", "vcs_type", ",", "command", ")", ":", "\"\"\"Helper to detect VCS by executing command.\n\n Returns:\n A pair (vcs, output) or None. Throws exception on error.\n \"\"\"", "try", ":", "out", ",", "returncode", "=", "RunShellWithReturnCode", "(", "command", ")", "if", "returncode", "==", "0", ":", "return", "(", "vcs_type", ",", "out", ".", "strip", "(", ")", ")", "except", "OSError", ",", "(", "errcode", ",", "message", ")", ":", "if", "errcode", "!=", "errno", ".", "ENOENT", ":", "# command not found code", "raise", "# Mercurial has a command to get the base directory of a repository", "# Try running it, but don't die if we don't have hg installed.", "# NOTE: we try Mercurial first as it can sit on top of an SVN working copy.", "res", "=", "RunDetectCommand", "(", "VCS_MERCURIAL", ",", "[", "\"hg\"", ",", "\"root\"", "]", ")", "if", "res", "!=", "None", ":", "return", "res", "# Subversion from 1.7 has a single centralized .svn folder", "# ( see http://subversion.apache.org/docs/release-notes/1.7.html#wc-ng )", "# That's why we use 'svn info' instead of checking for .svn dir", "res", "=", "RunDetectCommand", "(", "VCS_SUBVERSION", ",", "[", "\"svn\"", ",", "\"info\"", "]", ")", "if", "res", "!=", "None", ":", "return", "res", "# Git has a command to test if you're in a git tree.", "# Try running it, but don't die if we don't have git installed.", "res", "=", "RunDetectCommand", "(", "VCS_GIT", ",", "[", "\"git\"", ",", "\"rev-parse\"", ",", "\"--is-inside-work-tree\"", "]", ")", "if", "res", "!=", "None", ":", "return", "res", "# detect CVS repos use `cvs status && $? == 0` rules", "res", "=", "RunDetectCommand", "(", "VCS_CVS", ",", "[", "\"cvs\"", ",", "\"status\"", "]", ")", "if", "res", "!=", "None", ":", "return", "res", "return", "(", "VCS_UNKNOWN", ",", "None", ")" ]
https://github.com/ijason/NodeJS-Sample-App/blob/a09d085cee52d07523ed87c8aa35a8bcb1c31537/EmployeeDB/node_modules/mongodb/upload.py#L1920-L1979
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
3rd_party/python3/site-packages/cheroot-6.5.5/cheroot/cli.py
python
main
()
Create a new Cheroot instance with arguments from the command line.
Create a new Cheroot instance with arguments from the command line.
[ "Create", "a", "new", "Cheroot", "instance", "with", "arguments", "from", "the", "command", "line", "." ]
def main(): """Create a new Cheroot instance with arguments from the command line.""" parser = argparse.ArgumentParser( description='Start an instance of the Cheroot WSGI/HTTP server.', ) for arg, spec in _arg_spec.items(): parser.add_argument(arg, **spec) raw_args = parser.parse_args() # ensure cwd in sys.path '' in sys.path or sys.path.insert(0, '') # create a server based on the arguments provided raw_args._wsgi_app.server(raw_args).safe_start()
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Start an instance of the Cheroot WSGI/HTTP server.'", ",", ")", "for", "arg", ",", "spec", "in", "_arg_spec", ".", "items", "(", ")", ":", "parser", ".", "add_argument", "(", "arg", ",", "*", "*", "spec", ")", "raw_args", "=", "parser", ".", "parse_args", "(", ")", "# ensure cwd in sys.path", "''", "in", "sys", ".", "path", "or", "sys", ".", "path", ".", "insert", "(", "0", ",", "''", ")", "# create a server based on the arguments provided", "raw_args", ".", "_wsgi_app", ".", "server", "(", "raw_args", ")", ".", "safe_start", "(", ")" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python3/site-packages/cheroot-6.5.5/cheroot/cli.py#L221-L234
KhronosGroup/Vulkan-Docs
ee155139142a2a71b56238419bf0a6859f7b0a93
scripts/genRef.py
python
xrefRewrite
(text, specURL)
return text
Rewrite asciidoctor xrefs in text to resolve properly in refpages. Xrefs which are to Vulkan refpages are rewritten to link to those refpages. The remainder are rewritten to generate external links into the supplied specification document URL. - text - string to rewrite, or None - specURL - URL to target Returns rewritten text, or None, respectively
Rewrite asciidoctor xrefs in text to resolve properly in refpages. Xrefs which are to Vulkan refpages are rewritten to link to those refpages. The remainder are rewritten to generate external links into the supplied specification document URL.
[ "Rewrite", "asciidoctor", "xrefs", "in", "text", "to", "resolve", "properly", "in", "refpages", ".", "Xrefs", "which", "are", "to", "Vulkan", "refpages", "are", "rewritten", "to", "link", "to", "those", "refpages", ".", "The", "remainder", "are", "rewritten", "to", "generate", "external", "links", "into", "the", "supplied", "specification", "document", "URL", "." ]
def xrefRewrite(text, specURL): """Rewrite asciidoctor xrefs in text to resolve properly in refpages. Xrefs which are to Vulkan refpages are rewritten to link to those refpages. The remainder are rewritten to generate external links into the supplied specification document URL. - text - string to rewrite, or None - specURL - URL to target Returns rewritten text, or None, respectively""" global refLinkPattern, refLinkSubstitute global refLinkTextPattern, refLinkTextSubstitute global specLinkPattern, specLinkSubstitute specLinkSubstitute = r'link:{}#\1[\2^]'.format(specURL) if text is not None: text, _ = refLinkPattern.subn(refLinkSubstitute, text) text, _ = refLinkTextPattern.subn(refLinkTextSubstitute, text) text, _ = specLinkPattern.subn(specLinkSubstitute, text) return text
[ "def", "xrefRewrite", "(", "text", ",", "specURL", ")", ":", "global", "refLinkPattern", ",", "refLinkSubstitute", "global", "refLinkTextPattern", ",", "refLinkTextSubstitute", "global", "specLinkPattern", ",", "specLinkSubstitute", "specLinkSubstitute", "=", "r'link:{}#\\1[\\2^]'", ".", "format", "(", "specURL", ")", "if", "text", "is", "not", "None", ":", "text", ",", "_", "=", "refLinkPattern", ".", "subn", "(", "refLinkSubstitute", ",", "text", ")", "text", ",", "_", "=", "refLinkTextPattern", ".", "subn", "(", "refLinkTextSubstitute", ",", "text", ")", "text", ",", "_", "=", "specLinkPattern", ".", "subn", "(", "specLinkSubstitute", ",", "text", ")", "return", "text" ]
https://github.com/KhronosGroup/Vulkan-Docs/blob/ee155139142a2a71b56238419bf0a6859f7b0a93/scripts/genRef.py#L386-L408
JoneXiong/DjangoX
c2a723e209ef13595f571923faac7eb29e4c8150
xadmin/views/custom_page.py
python
PageView.get_context
(self)
return context
u''' 返回上下文
u''' 返回上下文
[ "u", "返回上下文" ]
def get_context(self): u''' 返回上下文 ''' context = super(PageView, self).get_context() context.update({ 'content': self.get_content() or '', 'title': self.verbose_name or self.__class__.__bases__ [0].__name__, }) if self.pop: if self.admin_site.ext_ui: context['base_template'] = 'xadmin/base_pure_ext.html' else: context['base_template'] = 'xadmin/base_pure.html' return context
[ "def", "get_context", "(", "self", ")", ":", "context", "=", "super", "(", "PageView", ",", "self", ")", ".", "get_context", "(", ")", "context", ".", "update", "(", "{", "'content'", ":", "self", ".", "get_content", "(", ")", "or", "''", ",", "'title'", ":", "self", ".", "verbose_name", "or", "self", ".", "__class__", ".", "__bases__", "[", "0", "]", ".", "__name__", ",", "}", ")", "if", "self", ".", "pop", ":", "if", "self", ".", "admin_site", ".", "ext_ui", ":", "context", "[", "'base_template'", "]", "=", "'xadmin/base_pure_ext.html'", "else", ":", "context", "[", "'base_template'", "]", "=", "'xadmin/base_pure.html'", "return", "context" ]
https://github.com/JoneXiong/DjangoX/blob/c2a723e209ef13595f571923faac7eb29e4c8150/xadmin/views/custom_page.py#L50-L64
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/locale.py
python
atoi
(str)
return atof(str, int)
Converts a string to an integer according to the locale settings.
Converts a string to an integer according to the locale settings.
[ "Converts", "a", "string", "to", "an", "integer", "according", "to", "the", "locale", "settings", "." ]
def atoi(str): "Converts a string to an integer according to the locale settings." return atof(str, int)
[ "def", "atoi", "(", "str", ")", ":", "return", "atof", "(", "str", ",", "int", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/locale.py#L312-L314
nodejs/node-chakracore
770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py
python
WinTool.Dispatch
(self, args)
return getattr(self, method)(*args[1:])
Dispatches a string command to a method.
Dispatches a string command to a method.
[ "Dispatches", "a", "string", "command", "to", "a", "method", "." ]
def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:])
[ "def", "Dispatch", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "1", ":", "raise", "Exception", "(", "\"Not enough arguments\"", ")", "method", "=", "\"Exec%s\"", "%", "self", ".", "_CommandifyName", "(", "args", "[", "0", "]", ")", "return", "getattr", "(", "self", ",", "method", ")", "(", "*", "args", "[", "1", ":", "]", ")" ]
https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py#L64-L70
xtk/X
04c1aa856664a8517d23aefd94c470d47130aead
lib/pypng-0.0.9/code/png.py
python
Reader._as_rescale
(self, get, targetbitdepth)
return width, height, iterscale(), meta
Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.
Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.
[ "Helper", "used", "by", ":", "meth", ":", "asRGB8", "and", ":", "meth", ":", "asRGBA8", "." ]
def _as_rescale(self, get, targetbitdepth): """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" width,height,pixels,meta = get() maxval = 2**meta['bitdepth'] - 1 targetmaxval = 2**targetbitdepth - 1 factor = float(targetmaxval) / float(maxval) meta['bitdepth'] = targetbitdepth def iterscale(): for row in pixels: yield map(lambda x: int(round(x*factor)), row) return width, height, iterscale(), meta
[ "def", "_as_rescale", "(", "self", ",", "get", ",", "targetbitdepth", ")", ":", "width", ",", "height", ",", "pixels", ",", "meta", "=", "get", "(", ")", "maxval", "=", "2", "**", "meta", "[", "'bitdepth'", "]", "-", "1", "targetmaxval", "=", "2", "**", "targetbitdepth", "-", "1", "factor", "=", "float", "(", "targetmaxval", ")", "/", "float", "(", "maxval", ")", "meta", "[", "'bitdepth'", "]", "=", "targetbitdepth", "def", "iterscale", "(", ")", ":", "for", "row", "in", "pixels", ":", "yield", "map", "(", "lambda", "x", ":", "int", "(", "round", "(", "x", "*", "factor", ")", ")", ",", "row", ")", "return", "width", ",", "height", ",", "iterscale", "(", ")", ",", "meta" ]
https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/pypng-0.0.9/code/png.py#L1850-L1861
tensorflow/tfjs-examples
66e9ee0e67526763ab29ef63d89101f8676f3884
sentiment/python/imdb.py
python
indices_to_words
(reverse_index, indices)
return [reverse_index[i - INDEX_FROM] if i >= INDEX_FROM else 'OOV' for i in indices]
Convert an iterable of word indices into words. Args: reverse_index: An `dict` mapping word index (as `int`) to word (as `str`). indices: An iterable of word indices. Returns: Mapped words as a `list` of `str`s.
Convert an iterable of word indices into words.
[ "Convert", "an", "iterable", "of", "word", "indices", "into", "words", "." ]
def indices_to_words(reverse_index, indices): """Convert an iterable of word indices into words. Args: reverse_index: An `dict` mapping word index (as `int`) to word (as `str`). indices: An iterable of word indices. Returns: Mapped words as a `list` of `str`s. """ return [reverse_index[i - INDEX_FROM] if i >= INDEX_FROM else 'OOV' for i in indices]
[ "def", "indices_to_words", "(", "reverse_index", ",", "indices", ")", ":", "return", "[", "reverse_index", "[", "i", "-", "INDEX_FROM", "]", "if", "i", ">=", "INDEX_FROM", "else", "'OOV'", "for", "i", "in", "indices", "]" ]
https://github.com/tensorflow/tfjs-examples/blob/66e9ee0e67526763ab29ef63d89101f8676f3884/sentiment/python/imdb.py#L59-L70
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_internal/req/req_uninstall.py
python
compress_for_rename
(paths)
return set(map(case_map.__getitem__, remaining)) | wildcards
Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk.
Returns a set containing the paths that need to be renamed.
[ "Returns", "a", "set", "containing", "the", "paths", "that", "need", "to", "be", "renamed", "." ]
def compress_for_rename(paths): # type: (Iterable[str]) -> Set[str] """Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. """ case_map = dict((os.path.normcase(p), p) for p in paths) remaining = set(case_map) unchecked = sorted(set(os.path.split(p)[0] for p in case_map.values()), key=len) wildcards = set() # type: Set[str] def norm_join(*a): # type: (str) -> str return os.path.normcase(os.path.join(*a)) for root in unchecked: if any(os.path.normcase(root).startswith(w) for w in wildcards): # This directory has already been handled. continue all_files = set() # type: Set[str] all_subdirs = set() # type: Set[str] for dirname, subdirs, files in os.walk(root): all_subdirs.update(norm_join(root, dirname, d) for d in subdirs) all_files.update(norm_join(root, dirname, f) for f in files) # If all the files we found are in our remaining set of files to # remove, then remove them from the latter set and add a wildcard # for the directory. if not (all_files - remaining): remaining.difference_update(all_files) wildcards.add(root + os.sep) return set(map(case_map.__getitem__, remaining)) | wildcards
[ "def", "compress_for_rename", "(", "paths", ")", ":", "# type: (Iterable[str]) -> Set[str]", "case_map", "=", "dict", "(", "(", "os", ".", "path", ".", "normcase", "(", "p", ")", ",", "p", ")", "for", "p", "in", "paths", ")", "remaining", "=", "set", "(", "case_map", ")", "unchecked", "=", "sorted", "(", "set", "(", "os", ".", "path", ".", "split", "(", "p", ")", "[", "0", "]", "for", "p", "in", "case_map", ".", "values", "(", ")", ")", ",", "key", "=", "len", ")", "wildcards", "=", "set", "(", ")", "# type: Set[str]", "def", "norm_join", "(", "*", "a", ")", ":", "# type: (str) -> str", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "join", "(", "*", "a", ")", ")", "for", "root", "in", "unchecked", ":", "if", "any", "(", "os", ".", "path", ".", "normcase", "(", "root", ")", ".", "startswith", "(", "w", ")", "for", "w", "in", "wildcards", ")", ":", "# This directory has already been handled.", "continue", "all_files", "=", "set", "(", ")", "# type: Set[str]", "all_subdirs", "=", "set", "(", ")", "# type: Set[str]", "for", "dirname", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "root", ")", ":", "all_subdirs", ".", "update", "(", "norm_join", "(", "root", ",", "dirname", ",", "d", ")", "for", "d", "in", "subdirs", ")", "all_files", ".", "update", "(", "norm_join", "(", "root", ",", "dirname", ",", "f", ")", "for", "f", "in", "files", ")", "# If all the files we found are in our remaining set of files to", "# remove, then remove them from the latter set and add a wildcard", "# for the directory.", "if", "not", "(", "all_files", "-", "remaining", ")", ":", "remaining", ".", "difference_update", "(", "all_files", ")", "wildcards", ".", "add", "(", "root", "+", "os", ".", "sep", ")", "return", "set", "(", "map", "(", "case_map", ".", "__getitem__", ",", "remaining", ")", ")", "|", "wildcards" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_internal/req/req_uninstall.py#L111-L148
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
GetXcodeArchsDefault
()
return XCODE_ARCHS_DEFAULT_CACHE
Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used. For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses $(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0 and deprecated with Xcode 5.1. For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit architecture as part of $(ARCHS_STANDARD) and default to only building it. For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they are also part of $(ARCHS_STANDARD). All thoses rules are coded in the construction of the |XcodeArchsDefault| object to use depending on the version of Xcode detected. The object is for performance reason.
Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used.
[ "Returns", "the", "|XcodeArchsDefault|", "object", "to", "use", "to", "expand", "ARCHS", "for", "the", "installed", "version", "of", "Xcode", ".", "The", "default", "values", "used", "by", "Xcode", "for", "ARCHS", "and", "the", "expansion", "of", "the", "variables", "depends", "on", "the", "version", "of", "Xcode", "used", "." ]
def GetXcodeArchsDefault(): """Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used. For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses $(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0 and deprecated with Xcode 5.1. For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit architecture as part of $(ARCHS_STANDARD) and default to only building it. For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they are also part of $(ARCHS_STANDARD). All thoses rules are coded in the construction of the |XcodeArchsDefault| object to use depending on the version of Xcode detected. The object is for performance reason.""" global XCODE_ARCHS_DEFAULT_CACHE if XCODE_ARCHS_DEFAULT_CACHE: return XCODE_ARCHS_DEFAULT_CACHE xcode_version, _ = XcodeVersion() if xcode_version < '0500': XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD)', XcodeArchsVariableMapping(['i386']), XcodeArchsVariableMapping(['i386']), XcodeArchsVariableMapping(['armv7'])) elif xcode_version < '0510': XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD_INCLUDING_64_BIT)', XcodeArchsVariableMapping(['x86_64'], ['x86_64']), XcodeArchsVariableMapping(['i386'], ['i386', 'x86_64']), XcodeArchsVariableMapping( ['armv7', 'armv7s'], ['armv7', 'armv7s', 'arm64'])) else: XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( '$(ARCHS_STANDARD)', XcodeArchsVariableMapping(['x86_64'], ['x86_64']), XcodeArchsVariableMapping(['i386', 'x86_64'], ['i386', 'x86_64']), XcodeArchsVariableMapping( ['armv7', 'armv7s', 'arm64'], ['armv7', 'armv7s', 'arm64'])) return XCODE_ARCHS_DEFAULT_CACHE
[ "def", "GetXcodeArchsDefault", "(", ")", ":", "global", "XCODE_ARCHS_DEFAULT_CACHE", "if", "XCODE_ARCHS_DEFAULT_CACHE", ":", "return", "XCODE_ARCHS_DEFAULT_CACHE", "xcode_version", ",", "_", "=", "XcodeVersion", "(", ")", "if", "xcode_version", "<", "'0500'", ":", "XCODE_ARCHS_DEFAULT_CACHE", "=", "XcodeArchsDefault", "(", "'$(ARCHS_STANDARD)'", ",", "XcodeArchsVariableMapping", "(", "[", "'i386'", "]", ")", ",", "XcodeArchsVariableMapping", "(", "[", "'i386'", "]", ")", ",", "XcodeArchsVariableMapping", "(", "[", "'armv7'", "]", ")", ")", "elif", "xcode_version", "<", "'0510'", ":", "XCODE_ARCHS_DEFAULT_CACHE", "=", "XcodeArchsDefault", "(", "'$(ARCHS_STANDARD_INCLUDING_64_BIT)'", ",", "XcodeArchsVariableMapping", "(", "[", "'x86_64'", "]", ",", "[", "'x86_64'", "]", ")", ",", "XcodeArchsVariableMapping", "(", "[", "'i386'", "]", ",", "[", "'i386'", ",", "'x86_64'", "]", ")", ",", "XcodeArchsVariableMapping", "(", "[", "'armv7'", ",", "'armv7s'", "]", ",", "[", "'armv7'", ",", "'armv7s'", ",", "'arm64'", "]", ")", ")", "else", ":", "XCODE_ARCHS_DEFAULT_CACHE", "=", "XcodeArchsDefault", "(", "'$(ARCHS_STANDARD)'", ",", "XcodeArchsVariableMapping", "(", "[", "'x86_64'", "]", ",", "[", "'x86_64'", "]", ")", ",", "XcodeArchsVariableMapping", "(", "[", "'i386'", ",", "'x86_64'", "]", ",", "[", "'i386'", ",", "'x86_64'", "]", ")", ",", "XcodeArchsVariableMapping", "(", "[", "'armv7'", ",", "'armv7s'", ",", "'arm64'", "]", ",", "[", "'armv7'", ",", "'armv7s'", ",", "'arm64'", "]", ")", ")", "return", "XCODE_ARCHS_DEFAULT_CACHE" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L95-L141
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
tools/cpplint.py
python
CheckCStyleCast
(filename, clean_lines, linenum, cast_type, pattern, error)
return True
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise.
Checks for a C-style cast by looking for the pattern.
[ "Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "." ]
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ line = clean_lines.elided[linenum] match = Search(pattern, line) if not match: return False # Exclude lines with keywords that tend to look like casts context = line[0:match.start(1) - 1] if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): return False # Try expanding current context to see if we one level of # parentheses inside a macro. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 5), -1): context = clean_lines.elided[i] + context if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): return False # operator++(int) and operator--(int) if context.endswith(' operator++') or context.endswith(' operator--'): return False # A single unnamed argument for a function tends to look like old style cast. # If we see those, don't issue warnings for deprecated casts. remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', remainder): return False # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True
[ "def", "CheckCStyleCast", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "not", "match", ":", "return", "False", "# Exclude lines with keywords that tend to look like casts", "context", "=", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", "if", "Match", "(", "r'.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$'", ",", "context", ")", ":", "return", "False", "# Try expanding current context to see if we one level of", "# parentheses inside a macro.", "if", "linenum", ">", "0", ":", "for", "i", "in", "xrange", "(", "linenum", "-", "1", ",", "max", "(", "0", ",", "linenum", "-", "5", ")", ",", "-", "1", ")", ":", "context", "=", "clean_lines", ".", "elided", "[", "i", "]", "+", "context", "if", "Match", "(", "r'.*\\b[_A-Z][_A-Z0-9]*\\s*\\((?:\\([^()]*\\)|[^()])*$'", ",", "context", ")", ":", "return", "False", "# operator++(int) and operator--(int)", "if", "context", ".", "endswith", "(", "' operator++'", ")", "or", "context", ".", "endswith", "(", "' operator--'", ")", ":", "return", "False", "# A single unnamed argument for a function tends to look like old style cast.", "# If we see those, don't issue warnings for deprecated casts.", "remainder", "=", "line", "[", "match", ".", "end", "(", "0", ")", ":", "]", "if", "Match", "(", "r'^\\s*(?:;|const\\b|throw\\b|final\\b|override\\b|[=>{),]|->)'", ",", "remainder", ")", ":", "return", "False", "# At this point, all that should be left is actual casts.", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using C-style cast. Use %s<%s>(...) instead'", "%", "(", "cast_type", ",", "match", ".", "group", "(", "1", ")", ")", ")", "return", "True" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/tools/cpplint.py#L5143-L5193
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/module.py
python
_ModuleContainer.sanitize_label
(self, label)
return label
Converts a label taken from user input into a well-formed label. @type label: str @param label: Label taken from user input. @rtype: str @return: Sanitized label.
Converts a label taken from user input into a well-formed label.
[ "Converts", "a", "label", "taken", "from", "user", "input", "into", "a", "well", "-", "formed", "label", "." ]
def sanitize_label(self, label): """ Converts a label taken from user input into a well-formed label. @type label: str @param label: Label taken from user input. @rtype: str @return: Sanitized label. """ (module, function, offset) = self.split_label_fuzzy(label) label = self.parse_label(module, function, offset) return label
[ "def", "sanitize_label", "(", "self", ",", "label", ")", ":", "(", "module", ",", "function", ",", "offset", ")", "=", "self", ".", "split_label_fuzzy", "(", "label", ")", "label", "=", "self", ".", "parse_label", "(", "module", ",", "function", ",", "offset", ")", "return", "label" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/module.py#L1502-L1514
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
tools/gyp/pylib/gyp/common.py
python
TopologicallySorted
(graph, get_edges)
return ordered_nodes
r"""Topologically sort based on a user provided edge definition. Args: graph: A list of node names. get_edges: A function mapping from node name to a hashable collection of node names which this node has outgoing edges to. Returns: A list containing all of the node in graph in topological order. It is assumed that calling get_edges once for each node and caching is cheaper than repeatedly calling get_edges. Raises: CycleError in the event of a cycle. Example: graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'} def GetEdges(node): return re.findall(r'\$\(([^))]\)', graph[node]) print TopologicallySorted(graph.keys(), GetEdges) ==> ['a', 'c', b']
r"""Topologically sort based on a user provided edge definition.
[ "r", "Topologically", "sort", "based", "on", "a", "user", "provided", "edge", "definition", "." ]
def TopologicallySorted(graph, get_edges): r"""Topologically sort based on a user provided edge definition. Args: graph: A list of node names. get_edges: A function mapping from node name to a hashable collection of node names which this node has outgoing edges to. Returns: A list containing all of the node in graph in topological order. It is assumed that calling get_edges once for each node and caching is cheaper than repeatedly calling get_edges. Raises: CycleError in the event of a cycle. Example: graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'} def GetEdges(node): return re.findall(r'\$\(([^))]\)', graph[node]) print TopologicallySorted(graph.keys(), GetEdges) ==> ['a', 'c', b'] """ get_edges = memoize(get_edges) visited = set() visiting = set() ordered_nodes = [] def Visit(node): if node in visiting: raise CycleError(visiting) if node in visited: return visited.add(node) visiting.add(node) for neighbor in get_edges(node): Visit(neighbor) visiting.remove(node) ordered_nodes.insert(0, node) for node in sorted(graph): Visit(node) return ordered_nodes
[ "def", "TopologicallySorted", "(", "graph", ",", "get_edges", ")", ":", "get_edges", "=", "memoize", "(", "get_edges", ")", "visited", "=", "set", "(", ")", "visiting", "=", "set", "(", ")", "ordered_nodes", "=", "[", "]", "def", "Visit", "(", "node", ")", ":", "if", "node", "in", "visiting", ":", "raise", "CycleError", "(", "visiting", ")", "if", "node", "in", "visited", ":", "return", "visited", ".", "add", "(", "node", ")", "visiting", ".", "add", "(", "node", ")", "for", "neighbor", "in", "get_edges", "(", "node", ")", ":", "Visit", "(", "neighbor", ")", "visiting", ".", "remove", "(", "node", ")", "ordered_nodes", ".", "insert", "(", "0", ",", "node", ")", "for", "node", "in", "sorted", "(", "graph", ")", ":", "Visit", "(", "node", ")", "return", "ordered_nodes" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/tools/gyp/pylib/gyp/common.py#L566-L604
lambdamusic/Ontospy
534e408372edd392590e12839c32a403430aac23
ontospy/core/utils.py
python
inferMainPropertyType
(uriref)
Attempt to reduce the property types to 4 main types (without the OWL ontology - which would be the propert way) In [3]: for x in g.all_properties: ...: print x.rdftype ...: http://www.w3.org/2002/07/owl#FunctionalProperty http://www.w3.org/2002/07/owl#FunctionalProperty http://www.w3.org/2002/07/owl#InverseFunctionalProperty http://www.w3.org/2002/07/owl#ObjectProperty http://www.w3.org/2002/07/owl#ObjectProperty http://www.w3.org/2002/07/owl#TransitiveProperty http://www.w3.org/2002/07/owl#TransitiveProperty etc.....
Attempt to reduce the property types to 4 main types (without the OWL ontology - which would be the propert way)
[ "Attempt", "to", "reduce", "the", "property", "types", "to", "4", "main", "types", "(", "without", "the", "OWL", "ontology", "-", "which", "would", "be", "the", "propert", "way", ")" ]
def inferMainPropertyType(uriref): """ Attempt to reduce the property types to 4 main types (without the OWL ontology - which would be the propert way) In [3]: for x in g.all_properties: ...: print x.rdftype ...: http://www.w3.org/2002/07/owl#FunctionalProperty http://www.w3.org/2002/07/owl#FunctionalProperty http://www.w3.org/2002/07/owl#InverseFunctionalProperty http://www.w3.org/2002/07/owl#ObjectProperty http://www.w3.org/2002/07/owl#ObjectProperty http://www.w3.org/2002/07/owl#TransitiveProperty http://www.w3.org/2002/07/owl#TransitiveProperty etc..... """ if uriref: if uriref == rdflib.OWL.DatatypeProperty: return uriref elif uriref == rdflib.OWL.AnnotationProperty: return uriref elif uriref == rdflib.RDF.Property: return uriref else: # hack.. return rdflib.OWL.ObjectProperty else: return None
[ "def", "inferMainPropertyType", "(", "uriref", ")", ":", "if", "uriref", ":", "if", "uriref", "==", "rdflib", ".", "OWL", ".", "DatatypeProperty", ":", "return", "uriref", "elif", "uriref", "==", "rdflib", ".", "OWL", ".", "AnnotationProperty", ":", "return", "uriref", "elif", "uriref", "==", "rdflib", ".", "RDF", ".", "Property", ":", "return", "uriref", "else", ":", "# hack..", "return", "rdflib", ".", "OWL", ".", "ObjectProperty", "else", ":", "return", "None" ]
https://github.com/lambdamusic/Ontospy/blob/534e408372edd392590e12839c32a403430aac23/ontospy/core/utils.py#L417-L444
silklabs/silk
08c273949086350aeddd8e23e92f0f79243f446f
node_modules/node-gyp/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteTarget
(self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all)
Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all'
Write Makefile code to produce the final target of the gyp spec.
[ "Write", "Makefile", "code", "to", "produce", "the", "final", "target", "of", "the", "gyp", "spec", "." ]
def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Rules for final target.') if extra_outputs: self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs) self.WriteMakeRule(extra_outputs, deps, comment=('Preserve order dependency of ' 'special output on deps.'), order_only = True) target_postbuilds = {} if self.type != 'none': for configname in sorted(configs.keys()): config = configs[configname] if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(configname, generator_default_variables['PRODUCT_DIR'], lambda p: Sourceify(self.Absolutify(p))) # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on. gyp_to_build = gyp.common.InvertRelativePath(self.path) target_postbuild = self.xcode_settings.AddImplicitPostbuilds( configname, QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output))), QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output_binary)))) if target_postbuild: target_postbuilds[configname] = target_postbuild else: ldflags = config.get('ldflags', []) # Compute an rpath for this output if needed. if any(dep.endswith('.so') or '.so.' in dep for dep in deps): # We want to get the literal string "$ORIGIN" into the link command, # so we need lots of escaping. ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset) ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' % self.toolset) library_dirs = config.get('library_dirs', []) ldflags += [('-L%s' % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, 'LDFLAGS_%s' % configname) if self.flavor == 'mac': self.WriteList(self.xcode_settings.GetLibtoolflags(configname), 'LIBTOOLFLAGS_%s' % configname) libraries = spec.get('libraries') if libraries: # Remove duplicate entries libraries = gyp.common.uniquer(libraries) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries) self.WriteList(libraries, 'LIBS') self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary)) if self.flavor == 'mac': self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) # Postbuild actions. Like actions, but implicitly depend on the target's # output. postbuilds = [] if self.flavor == 'mac': if target_postbuilds: postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))') postbuilds.extend( gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) if postbuilds: # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), # so we must output its definition first, since we declare variables # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) for configname in target_postbuilds: self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' % (QuoteSpaces(self.output), configname, gyp.common.EncodePOSIXShellList(target_postbuilds[configname]))) # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path])) for i in xrange(len(postbuilds)): if not postbuilds[i].startswith('$'): postbuilds[i] = EscapeShellArgument(postbuilds[i]) self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output)) self.WriteLn('%s: POSTBUILDS := %s' % ( QuoteSpaces(self.output), ' '.join(postbuilds))) # A bundle directory depends on its dependencies such as bundle resources # and bundle binary. When all dependencies have been built, the bundle # needs to be packaged. if self.is_mac_bundle: # If the framework doesn't contain a binary, then nothing depends # on the actions -- make the framework depend on them directly too. self.WriteDependencyOnExtraOutputs(self.output, extra_outputs) # Bundle dependencies. Note that the code below adds actions to this # target, so if you move these two lines, move the lines below as well. self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS') self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output)) # After the framework is built, package it. Needs to happen before # postbuilds, since postbuilds depend on this. if self.type in ('shared_library', 'loadable_module'): self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' % self.xcode_settings.GetFrameworkVersion()) # Bundle postbuilds can depend on the whole bundle, so run them after # the bundle is packaged, not already after the bundle binary is done. if postbuilds: self.WriteLn('\t@$(call do_postbuilds)') postbuilds = [] # Don't write postbuilds for target's output. # Needed by test/mac/gyptest-rebuild.py. self.WriteLn('\t@true # No-op, used by tests') # Since this target depends on binary and resources which are in # nested subfolders, the framework directory will be older than # its dependencies usually. To prevent this rule from executing # on every build (expensive, especially with postbuilds), expliclity # update the time on the framework directory. self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output)) if postbuilds: assert not self.is_mac_bundle, ('Postbuilds for bundles should be done ' 'on the bundle, not the binary (target \'%s\')' % self.target) assert 'product_dir' not in spec, ('Postbuilds do not work with ' 'custom product_dir') if self.type == 'executable': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'link_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all, postbuilds=postbuilds) elif self.type == 'static_library': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in alink input filenames not supported (%s)" % link_dep) if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library): self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, postbuilds=postbuilds) elif self.type == 'shared_library': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all, postbuilds=postbuilds) elif self.type == 'loadable_module': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in module input filenames not supported (%s)" % link_dep) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd( [self.output_binary], link_deps, 'solink_module', part_of_all, postbuilds=postbuilds) elif self.type == 'none': # Write a stamp line. self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all, postbuilds=postbuilds) else: print "WARNING: no output for", self.type, target # Add an alias for each target (if there are any outputs). # Installable target aliases are created below. if ((self.output and self.output != self.target) and (self.type not in self._INSTALLABLE_TARGETS)): self.WriteMakeRule([self.target], [self.output], comment='Add target alias', phony = True) if part_of_all: self.WriteMakeRule(['all'], [self.target], comment = 'Add target alias to "all" target.', phony = True) # Add special-case rules for our installable targets. # 1) They need to install to the build dir or "product" dir. # 2) They get shortcuts for building (e.g. "make chrome"). # 3) They are part of "make all". if (self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library): if self.type == 'shared_library': file_desc = 'shared library' elif self.type == 'static_library': file_desc = 'static library' else: file_desc = 'executable' install_path = self._InstallableTargetInstallPath() installable_deps = [self.output] if (self.flavor == 'mac' and not 'product_dir' in spec and self.toolset == 'target'): # On mac, products are created in install_path immediately. assert install_path == self.output, '%s != %s' % ( install_path, self.output) # Point the target alias to the final binary output. self.WriteMakeRule([self.target], [install_path], comment='Add target alias', phony = True) if install_path != self.output: assert not self.is_mac_bundle # See comment a few lines above. self.WriteDoCmd([install_path], [self.output], 'copy', comment = 'Copy this to the %s output path.' % file_desc, part_of_all=part_of_all) installable_deps.append(install_path) if self.output != self.alias and self.alias != self.target: self.WriteMakeRule([self.alias], installable_deps, comment = 'Short alias for building this %s.' % file_desc, phony = True) if part_of_all: self.WriteMakeRule(['all'], [install_path], comment = 'Add %s to "all" target.' % file_desc, phony = True)
[ "def", "WriteTarget", "(", "self", ",", "spec", ",", "configs", ",", "deps", ",", "link_deps", ",", "bundle_deps", ",", "extra_outputs", ",", "part_of_all", ")", ":", "self", ".", "WriteLn", "(", "'### Rules for final target.'", ")", "if", "extra_outputs", ":", "self", ".", "WriteDependencyOnExtraOutputs", "(", "self", ".", "output_binary", ",", "extra_outputs", ")", "self", ".", "WriteMakeRule", "(", "extra_outputs", ",", "deps", ",", "comment", "=", "(", "'Preserve order dependency of '", "'special output on deps.'", ")", ",", "order_only", "=", "True", ")", "target_postbuilds", "=", "{", "}", "if", "self", ".", "type", "!=", "'none'", ":", "for", "configname", "in", "sorted", "(", "configs", ".", "keys", "(", ")", ")", ":", "config", "=", "configs", "[", "configname", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "ldflags", "=", "self", ".", "xcode_settings", ".", "GetLdflags", "(", "configname", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ",", "lambda", "p", ":", "Sourceify", "(", "self", ".", "Absolutify", "(", "p", ")", ")", ")", "# TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on.", "gyp_to_build", "=", "gyp", ".", "common", ".", "InvertRelativePath", "(", "self", ".", "path", ")", "target_postbuild", "=", "self", ".", "xcode_settings", ".", "AddImplicitPostbuilds", "(", "configname", ",", "QuoteSpaces", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "gyp_to_build", ",", "self", ".", "output", ")", ")", ")", ",", "QuoteSpaces", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "gyp_to_build", ",", "self", ".", "output_binary", ")", ")", ")", ")", "if", "target_postbuild", ":", "target_postbuilds", "[", "configname", "]", "=", "target_postbuild", "else", ":", "ldflags", "=", "config", ".", "get", "(", "'ldflags'", ",", "[", "]", ")", "# Compute an rpath for this output if needed.", "if", "any", "(", "dep", ".", "endswith", "(", "'.so'", ")", "or", "'.so.'", "in", "dep", "for", "dep", "in", "deps", ")", ":", "# We want to get the literal string \"$ORIGIN\" into the link command,", "# so we need lots of escaping.", "ldflags", ".", "append", "(", "r'-Wl,-rpath=\\$$ORIGIN/lib.%s/'", "%", "self", ".", "toolset", ")", "ldflags", ".", "append", "(", "r'-Wl,-rpath-link=\\$(builddir)/lib.%s/'", "%", "self", ".", "toolset", ")", "library_dirs", "=", "config", ".", "get", "(", "'library_dirs'", ",", "[", "]", ")", "ldflags", "+=", "[", "(", "'-L%s'", "%", "library_dir", ")", "for", "library_dir", "in", "library_dirs", "]", "self", ".", "WriteList", "(", "ldflags", ",", "'LDFLAGS_%s'", "%", "configname", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteList", "(", "self", ".", "xcode_settings", ".", "GetLibtoolflags", "(", "configname", ")", ",", "'LIBTOOLFLAGS_%s'", "%", "configname", ")", "libraries", "=", "spec", ".", "get", "(", "'libraries'", ")", "if", "libraries", ":", "# Remove duplicate entries", "libraries", "=", "gyp", ".", "common", ".", "uniquer", "(", "libraries", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "libraries", "=", "self", ".", "xcode_settings", ".", "AdjustLibraries", "(", "libraries", ")", "self", ".", "WriteList", "(", "libraries", ",", "'LIBS'", ")", "self", ".", "WriteLn", "(", "'%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "self", ".", "WriteLn", "(", "'%s: LIBS := $(LIBS)'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "'%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "# Postbuild actions. Like actions, but implicitly depend on the target's", "# output.", "postbuilds", "=", "[", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "if", "target_postbuilds", ":", "postbuilds", ".", "append", "(", "'$(TARGET_POSTBUILDS_$(BUILDTYPE))'", ")", "postbuilds", ".", "extend", "(", "gyp", ".", "xcode_emulation", ".", "GetSpecPostbuildCommands", "(", "spec", ")", ")", "if", "postbuilds", ":", "# Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE),", "# so we must output its definition first, since we declare variables", "# using \":=\".", "self", ".", "WriteSortedXcodeEnv", "(", "self", ".", "output", ",", "self", ".", "GetSortedXcodePostbuildEnv", "(", ")", ")", "for", "configname", "in", "target_postbuilds", ":", "self", ".", "WriteLn", "(", "'%s: TARGET_POSTBUILDS_%s := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output", ")", ",", "configname", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "target_postbuilds", "[", "configname", "]", ")", ")", ")", "# Postbuilds expect to be run in the gyp file's directory, so insert an", "# implicit postbuild to cd to there.", "postbuilds", ".", "insert", "(", "0", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "[", "'cd'", ",", "self", ".", "path", "]", ")", ")", "for", "i", "in", "xrange", "(", "len", "(", "postbuilds", ")", ")", ":", "if", "not", "postbuilds", "[", "i", "]", ".", "startswith", "(", "'$'", ")", ":", "postbuilds", "[", "i", "]", "=", "EscapeShellArgument", "(", "postbuilds", "[", "i", "]", ")", "self", ".", "WriteLn", "(", "'%s: builddir := $(abs_builddir)'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "self", ".", "WriteLn", "(", "'%s: POSTBUILDS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output", ")", ",", "' '", ".", "join", "(", "postbuilds", ")", ")", ")", "# A bundle directory depends on its dependencies such as bundle resources", "# and bundle binary. When all dependencies have been built, the bundle", "# needs to be packaged.", "if", "self", ".", "is_mac_bundle", ":", "# If the framework doesn't contain a binary, then nothing depends", "# on the actions -- make the framework depend on them directly too.", "self", ".", "WriteDependencyOnExtraOutputs", "(", "self", ".", "output", ",", "extra_outputs", ")", "# Bundle dependencies. Note that the code below adds actions to this", "# target, so if you move these two lines, move the lines below as well.", "self", ".", "WriteList", "(", "map", "(", "QuoteSpaces", ",", "bundle_deps", ")", ",", "'BUNDLE_DEPS'", ")", "self", ".", "WriteLn", "(", "'%s: $(BUNDLE_DEPS)'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "# After the framework is built, package it. Needs to happen before", "# postbuilds, since postbuilds depend on this.", "if", "self", ".", "type", "in", "(", "'shared_library'", ",", "'loadable_module'", ")", ":", "self", ".", "WriteLn", "(", "'\\t@$(call do_cmd,mac_package_framework,,,%s)'", "%", "self", ".", "xcode_settings", ".", "GetFrameworkVersion", "(", ")", ")", "# Bundle postbuilds can depend on the whole bundle, so run them after", "# the bundle is packaged, not already after the bundle binary is done.", "if", "postbuilds", ":", "self", ".", "WriteLn", "(", "'\\t@$(call do_postbuilds)'", ")", "postbuilds", "=", "[", "]", "# Don't write postbuilds for target's output.", "# Needed by test/mac/gyptest-rebuild.py.", "self", ".", "WriteLn", "(", "'\\t@true # No-op, used by tests'", ")", "# Since this target depends on binary and resources which are in", "# nested subfolders, the framework directory will be older than", "# its dependencies usually. To prevent this rule from executing", "# on every build (expensive, especially with postbuilds), expliclity", "# update the time on the framework directory.", "self", ".", "WriteLn", "(", "'\\t@touch -c %s'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "if", "postbuilds", ":", "assert", "not", "self", ".", "is_mac_bundle", ",", "(", "'Postbuilds for bundles should be done '", "'on the bundle, not the binary (target \\'%s\\')'", "%", "self", ".", "target", ")", "assert", "'product_dir'", "not", "in", "spec", ",", "(", "'Postbuilds do not work with '", "'custom product_dir'", ")", "if", "self", ".", "type", "==", "'executable'", ":", "self", ".", "WriteLn", "(", "'%s: LD_INPUTS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ",", "' '", ".", "join", "(", "map", "(", "QuoteSpaces", ",", "link_deps", ")", ")", ")", ")", "if", "self", ".", "toolset", "==", "'host'", "and", "self", ".", "flavor", "==", "'android'", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'link_host'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'link'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'static_library'", ":", "for", "link_dep", "in", "link_deps", ":", "assert", "' '", "not", "in", "link_dep", ",", "(", "\"Spaces in alink input filenames not supported (%s)\"", "%", "link_dep", ")", "if", "(", "self", ".", "flavor", "not", "in", "(", "'mac'", ",", "'openbsd'", ",", "'netbsd'", ",", "'win'", ")", "and", "not", "self", ".", "is_standalone_static_library", ")", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'alink_thin'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'alink'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'shared_library'", ":", "self", ".", "WriteLn", "(", "'%s: LD_INPUTS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ",", "' '", ".", "join", "(", "map", "(", "QuoteSpaces", ",", "link_deps", ")", ")", ")", ")", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'loadable_module'", ":", "for", "link_dep", "in", "link_deps", ":", "assert", "' '", "not", "in", "link_dep", ",", "(", "\"Spaces in module input filenames not supported (%s)\"", "%", "link_dep", ")", "if", "self", ".", "toolset", "==", "'host'", "and", "self", ".", "flavor", "==", "'android'", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink_module_host'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink_module'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'none'", ":", "# Write a stamp line.", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "deps", ",", "'touch'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "print", "\"WARNING: no output for\"", ",", "self", ".", "type", ",", "target", "# Add an alias for each target (if there are any outputs).", "# Installable target aliases are created below.", "if", "(", "(", "self", ".", "output", "and", "self", ".", "output", "!=", "self", ".", "target", ")", "and", "(", "self", ".", "type", "not", "in", "self", ".", "_INSTALLABLE_TARGETS", ")", ")", ":", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "target", "]", ",", "[", "self", ".", "output", "]", ",", "comment", "=", "'Add target alias'", ",", "phony", "=", "True", ")", "if", "part_of_all", ":", "self", ".", "WriteMakeRule", "(", "[", "'all'", "]", ",", "[", "self", ".", "target", "]", ",", "comment", "=", "'Add target alias to \"all\" target.'", ",", "phony", "=", "True", ")", "# Add special-case rules for our installable targets.", "# 1) They need to install to the build dir or \"product\" dir.", "# 2) They get shortcuts for building (e.g. \"make chrome\").", "# 3) They are part of \"make all\".", "if", "(", "self", ".", "type", "in", "self", ".", "_INSTALLABLE_TARGETS", "or", "self", ".", "is_standalone_static_library", ")", ":", "if", "self", ".", "type", "==", "'shared_library'", ":", "file_desc", "=", "'shared library'", "elif", "self", ".", "type", "==", "'static_library'", ":", "file_desc", "=", "'static library'", "else", ":", "file_desc", "=", "'executable'", "install_path", "=", "self", ".", "_InstallableTargetInstallPath", "(", ")", "installable_deps", "=", "[", "self", ".", "output", "]", "if", "(", "self", ".", "flavor", "==", "'mac'", "and", "not", "'product_dir'", "in", "spec", "and", "self", ".", "toolset", "==", "'target'", ")", ":", "# On mac, products are created in install_path immediately.", "assert", "install_path", "==", "self", ".", "output", ",", "'%s != %s'", "%", "(", "install_path", ",", "self", ".", "output", ")", "# Point the target alias to the final binary output.", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "target", "]", ",", "[", "install_path", "]", ",", "comment", "=", "'Add target alias'", ",", "phony", "=", "True", ")", "if", "install_path", "!=", "self", ".", "output", ":", "assert", "not", "self", ".", "is_mac_bundle", "# See comment a few lines above.", "self", ".", "WriteDoCmd", "(", "[", "install_path", "]", ",", "[", "self", ".", "output", "]", ",", "'copy'", ",", "comment", "=", "'Copy this to the %s output path.'", "%", "file_desc", ",", "part_of_all", "=", "part_of_all", ")", "installable_deps", ".", "append", "(", "install_path", ")", "if", "self", ".", "output", "!=", "self", ".", "alias", "and", "self", ".", "alias", "!=", "self", ".", "target", ":", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "alias", "]", ",", "installable_deps", ",", "comment", "=", "'Short alias for building this %s.'", "%", "file_desc", ",", "phony", "=", "True", ")", "if", "part_of_all", ":", "self", ".", "WriteMakeRule", "(", "[", "'all'", "]", ",", "[", "install_path", "]", ",", "comment", "=", "'Add %s to \"all\" target.'", "%", "file_desc", ",", "phony", "=", "True", ")" ]
https://github.com/silklabs/silk/blob/08c273949086350aeddd8e23e92f0f79243f446f/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L1427-L1660
WuXianglong/GeekBlog
a4fe5e7de225c4891d498d8e9e8f9c0c47053b86
blog/geekblog/admin_tools/utils.py
python
AppListElementMixin._get_admin_add_url
(self, model, context)
return reverse('%s:%s_%s_add' % (get_admin_site_name(context), app_label, model.__name__.lower()))
Returns the admin add url.
Returns the admin add url.
[ "Returns", "the", "admin", "add", "url", "." ]
def _get_admin_add_url(self, model, context): """ Returns the admin add url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_add' % (get_admin_site_name(context), app_label, model.__name__.lower()))
[ "def", "_get_admin_add_url", "(", "self", ",", "model", ",", "context", ")", ":", "app_label", "=", "model", ".", "_meta", ".", "app_label", "return", "reverse", "(", "'%s:%s_%s_add'", "%", "(", "get_admin_site_name", "(", "context", ")", ",", "app_label", ",", "model", ".", "__name__", ".", "lower", "(", ")", ")", ")" ]
https://github.com/WuXianglong/GeekBlog/blob/a4fe5e7de225c4891d498d8e9e8f9c0c47053b86/blog/geekblog/admin_tools/utils.py#L116-L123
jrief/django-angular
1fdd2ab3211ed1655acc2d172d826ed7f3ad0574
djng/templatetags/djng_tags.py
python
djng_locale_script
(context, default_language='en')
return format_html('angular-locale_{}.js', language.lower())
Returns a script tag for including the proper locale script in any HTML page. This tag determines the current language with its locale. Usage: <script src="{% static 'node_modules/angular-i18n/' %}{% djng_locale_script %}"></script> or, if used with a default language: <script src="{% static 'node_modules/angular-i18n/' %}{% djng_locale_script 'de' %}"></script>
Returns a script tag for including the proper locale script in any HTML page. This tag determines the current language with its locale.
[ "Returns", "a", "script", "tag", "for", "including", "the", "proper", "locale", "script", "in", "any", "HTML", "page", ".", "This", "tag", "determines", "the", "current", "language", "with", "its", "locale", "." ]
def djng_locale_script(context, default_language='en'): """ Returns a script tag for including the proper locale script in any HTML page. This tag determines the current language with its locale. Usage: <script src="{% static 'node_modules/angular-i18n/' %}{% djng_locale_script %}"></script> or, if used with a default language: <script src="{% static 'node_modules/angular-i18n/' %}{% djng_locale_script 'de' %}"></script> """ language = get_language_from_request(context['request']) if not language: language = default_language return format_html('angular-locale_{}.js', language.lower())
[ "def", "djng_locale_script", "(", "context", ",", "default_language", "=", "'en'", ")", ":", "language", "=", "get_language_from_request", "(", "context", "[", "'request'", "]", ")", "if", "not", "language", ":", "language", "=", "default_language", "return", "format_html", "(", "'angular-locale_{}.js'", ",", "language", ".", "lower", "(", ")", ")" ]
https://github.com/jrief/django-angular/blob/1fdd2ab3211ed1655acc2d172d826ed7f3ad0574/djng/templatetags/djng_tags.py#L97-L110
DocSavage/bloog
ba3e32209006670fbac1beda1e3b631608c2b6cb
handlers/shell/shell.py
python
ShellSession.globals_dict
(self)
return dict((name, pickle.loads(val)) for name, val in zip(self.global_names, self.globals))
Returns a dictionary view of the globals.
Returns a dictionary view of the globals.
[ "Returns", "a", "dictionary", "view", "of", "the", "globals", "." ]
def globals_dict(self): """Returns a dictionary view of the globals. """ return dict((name, pickle.loads(val)) for name, val in zip(self.global_names, self.globals))
[ "def", "globals_dict", "(", "self", ")", ":", "return", "dict", "(", "(", "name", ",", "pickle", ".", "loads", "(", "val", ")", ")", "for", "name", ",", "val", "in", "zip", "(", "self", ".", "global_names", ",", "self", ".", "globals", ")", ")" ]
https://github.com/DocSavage/bloog/blob/ba3e32209006670fbac1beda1e3b631608c2b6cb/handlers/shell/shell.py#L139-L143
GoogleCloudPlatform/PerfKitExplorer
9efa61015d50c25f6d753f0212ad3bf16876d496
third_party/py/apiclient/http.py
python
MediaIoBaseUpload.mimetype
(self)
return self._mimetype
Mime type of the body. Returns: Mime type.
Mime type of the body.
[ "Mime", "type", "of", "the", "body", "." ]
def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype
[ "def", "mimetype", "(", "self", ")", ":", "return", "self", ".", "_mimetype" ]
https://github.com/GoogleCloudPlatform/PerfKitExplorer/blob/9efa61015d50c25f6d753f0212ad3bf16876d496/third_party/py/apiclient/http.py#L317-L323
prometheus-ar/vot.ar
72d8fa1ea08fe417b64340b98dff68df8364afdf
msa/core/ipc/server/__init__.py
python
IPCServer.pir_detected
(self)
Evento de PIR detectado.
Evento de PIR detectado.
[ "Evento", "de", "PIR", "detectado", "." ]
def pir_detected(self): """Evento de PIR detectado.""" self._info("pir_detected") self.parent.controller.pir_detected_cb(True)
[ "def", "pir_detected", "(", "self", ")", ":", "self", ".", "_info", "(", "\"pir_detected\"", ")", "self", ".", "parent", ".", "controller", ".", "pir_detected_cb", "(", "True", ")" ]
https://github.com/prometheus-ar/vot.ar/blob/72d8fa1ea08fe417b64340b98dff68df8364afdf/msa/core/ipc/server/__init__.py#L312-L315
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
tools/cpplint.py
python
CheckAccess
(filename, clean_lines, linenum, nesting_state, error)
Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks for improper use of DISALLOW* macros.
[ "Checks", "for", "improper", "use", "of", "DISALLOW", "*", "macros", "." ]
def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass
[ "def", "CheckAccess", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "matched", "=", "Match", "(", "(", "r'\\s*(DISALLOW_COPY_AND_ASSIGN|'", "r'DISALLOW_IMPLICIT_CONSTRUCTORS)'", ")", ",", "line", ")", "if", "not", "matched", ":", "return", "if", "nesting_state", ".", "stack", "and", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", ":", "if", "nesting_state", ".", "stack", "[", "-", "1", "]", ".", "access", "!=", "'private'", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/constructors'", ",", "3", ",", "'%s must be in the private: section'", "%", "matched", ".", "group", "(", "1", ")", ")", "else", ":", "# Found DISALLOW* macro outside a class declaration, or perhaps it", "# was used inside a function when it should have been part of the", "# class declaration. We could issue a warning here, but it", "# probably resulted in a compiler error already.", "pass" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/cpplint.py#L3030-L3057
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/distutils/versionpredicate.py
python
splitUp
(pred)
return (comp, distutils.version.StrictVersion(verStr))
Parse a single version comparison. Return (comparison string, StrictVersion)
Parse a single version comparison.
[ "Parse", "a", "single", "version", "comparison", "." ]
def splitUp(pred): """Parse a single version comparison. Return (comparison string, StrictVersion) """ res = re_splitComparison.match(pred) if not res: raise ValueError("bad package restriction syntax: %r" % pred) comp, verStr = res.groups() return (comp, distutils.version.StrictVersion(verStr))
[ "def", "splitUp", "(", "pred", ")", ":", "res", "=", "re_splitComparison", ".", "match", "(", "pred", ")", "if", "not", "res", ":", "raise", "ValueError", "(", "\"bad package restriction syntax: %r\"", "%", "pred", ")", "comp", ",", "verStr", "=", "res", ".", "groups", "(", ")", "return", "(", "comp", ",", "distutils", ".", "version", ".", "StrictVersion", "(", "verStr", ")", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/distutils/versionpredicate.py#L16-L25
almonk/Bind
03e9e98fb8b30a58cb4fc2829f06289fa9958897
public/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteRules
(self, rules, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all)
Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) part_of_all: flag indicating this target is part of 'all'
Write Makefile code for any 'rules' from the gyp input.
[ "Write", "Makefile", "code", "for", "any", "rules", "from", "the", "gyp", "input", "." ]
def WriteRules(self, rules, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for rule in rules: name = StringToMakefileVariable('%s_%s' % (self.qualified_target, rule['rule_name'])) count = 0 self.WriteLn('### Generated for rule %s:' % name) all_outputs = [] for rule_source in rule.get('rule_sources', []): dirs = set() (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = \ os.path.splitext(rule_source_basename) outputs = [self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule['outputs']] for out in outputs: dir = os.path.dirname(out) if dir: dirs.add(dir) if int(rule.get('process_outputs_as_sources', False)): extra_sources += outputs if int(rule.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs inputs = map(Sourceify, map(self.Absolutify, [rule_source] + rule.get('inputs', []))) actions = ['$(call do_cmd,%s_%d)' % (name, count)] if name == 'resources_grit': # HACK: This is ugly. Grit intentionally doesn't touch the # timestamp of its output file when the file doesn't change, # which is fine in hash-based dependency systems like scons # and forge, but not kosher in the make world. After some # discussion, hacking around it here seems like the least # amount of pain. actions += ['@touch --no-create $@'] # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] outputs = map(self.Absolutify, outputs) all_outputs += outputs # Only write the 'obj' and 'builddir' rules for the "primary" output # (:1); it's superfluous for the "extra outputs", and this avoids # accidentally writing duplicate dummy rules for those outputs. self.WriteLn('%s: obj := $(abs_obj)' % outputs[0]) self.WriteLn('%s: builddir := $(abs_builddir)' % outputs[0]) self.WriteMakeRule(outputs, inputs + ['FORCE_DO_CMD'], actions) # Spaces in rule filenames are not supported, but rule variables have # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)'). # The spaces within the variables are valid, so remove the variables # before checking. variables_with_spaces = re.compile(r'\$\([^ ]* \$<\)') for output in outputs: output = re.sub(variables_with_spaces, '', output) assert ' ' not in output, ( "Spaces in rule filenames not yet supported (%s)" % output) self.WriteLn('all_deps += %s' % ' '.join(outputs)) action = [self.ExpandInputRoot(ac, rule_source_root, rule_source_dirname) for ac in rule['action']] mkdirs = '' if len(dirs) > 0: mkdirs = 'mkdir -p %s; ' % ' '.join(dirs) cd_action = 'cd %s; ' % Sourceify(self.path or '.') # action, cd_action, and mkdirs get written to a toplevel variable # called cmd_foo. Toplevel variables can't handle things that change # per makefile like $(TARGET), so hardcode the target. if self.flavor == 'mac': action = [gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action] action = gyp.common.EncodePOSIXShellList(action) action = action.replace('$(TARGET)', self.target) cd_action = cd_action.replace('$(TARGET)', self.target) mkdirs = mkdirs.replace('$(TARGET)', self.target) # Set LD_LIBRARY_PATH in case the rule runs an executable from this # build which links to shared libs from this build. # rules run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn( "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=" "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; " "export LD_LIBRARY_PATH; " "%(cd_action)s%(mkdirs)s%(action)s" % { 'action': action, 'cd_action': cd_action, 'count': count, 'mkdirs': mkdirs, 'name': name, }) self.WriteLn( 'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@' % { 'count': count, 'name': name, }) self.WriteLn() count += 1 outputs_variable = 'rule_%s_outputs' % name self.WriteList(all_outputs, outputs_variable) extra_outputs.append('$(%s)' % outputs_variable) self.WriteLn('### Finished generating for rule: %s' % name) self.WriteLn() self.WriteLn('### Finished generating for all rules') self.WriteLn('')
[ "def", "WriteRules", "(", "self", ",", "rules", ",", "extra_sources", ",", "extra_outputs", ",", "extra_mac_bundle_resources", ",", "part_of_all", ")", ":", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", ")", "for", "rule", "in", "rules", ":", "name", "=", "StringToMakefileVariable", "(", "'%s_%s'", "%", "(", "self", ".", "qualified_target", ",", "rule", "[", "'rule_name'", "]", ")", ")", "count", "=", "0", "self", ".", "WriteLn", "(", "'### Generated for rule %s:'", "%", "name", ")", "all_outputs", "=", "[", "]", "for", "rule_source", "in", "rule", ".", "get", "(", "'rule_sources'", ",", "[", "]", ")", ":", "dirs", "=", "set", "(", ")", "(", "rule_source_dirname", ",", "rule_source_basename", ")", "=", "os", ".", "path", ".", "split", "(", "rule_source", ")", "(", "rule_source_root", ",", "rule_source_ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "rule_source_basename", ")", "outputs", "=", "[", "self", ".", "ExpandInputRoot", "(", "out", ",", "rule_source_root", ",", "rule_source_dirname", ")", "for", "out", "in", "rule", "[", "'outputs'", "]", "]", "for", "out", "in", "outputs", ":", "dir", "=", "os", ".", "path", ".", "dirname", "(", "out", ")", "if", "dir", ":", "dirs", ".", "add", "(", "dir", ")", "if", "int", "(", "rule", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "extra_sources", "+=", "outputs", "if", "int", "(", "rule", ".", "get", "(", "'process_outputs_as_mac_bundle_resources'", ",", "False", ")", ")", ":", "extra_mac_bundle_resources", "+=", "outputs", "inputs", "=", "map", "(", "Sourceify", ",", "map", "(", "self", ".", "Absolutify", ",", "[", "rule_source", "]", "+", "rule", ".", "get", "(", "'inputs'", ",", "[", "]", ")", ")", ")", "actions", "=", "[", "'$(call do_cmd,%s_%d)'", "%", "(", "name", ",", "count", ")", "]", "if", "name", "==", "'resources_grit'", ":", "# HACK: This is ugly. Grit intentionally doesn't touch the", "# timestamp of its output file when the file doesn't change,", "# which is fine in hash-based dependency systems like scons", "# and forge, but not kosher in the make world. After some", "# discussion, hacking around it here seems like the least", "# amount of pain.", "actions", "+=", "[", "'@touch --no-create $@'", "]", "# See the comment in WriteCopies about expanding env vars.", "outputs", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "o", ",", "env", ")", "for", "o", "in", "outputs", "]", "inputs", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "i", ",", "env", ")", "for", "i", "in", "inputs", "]", "outputs", "=", "map", "(", "self", ".", "Absolutify", ",", "outputs", ")", "all_outputs", "+=", "outputs", "# Only write the 'obj' and 'builddir' rules for the \"primary\" output", "# (:1); it's superfluous for the \"extra outputs\", and this avoids", "# accidentally writing duplicate dummy rules for those outputs.", "self", ".", "WriteLn", "(", "'%s: obj := $(abs_obj)'", "%", "outputs", "[", "0", "]", ")", "self", ".", "WriteLn", "(", "'%s: builddir := $(abs_builddir)'", "%", "outputs", "[", "0", "]", ")", "self", ".", "WriteMakeRule", "(", "outputs", ",", "inputs", "+", "[", "'FORCE_DO_CMD'", "]", ",", "actions", ")", "# Spaces in rule filenames are not supported, but rule variables have", "# spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)').", "# The spaces within the variables are valid, so remove the variables", "# before checking.", "variables_with_spaces", "=", "re", ".", "compile", "(", "r'\\$\\([^ ]* \\$<\\)'", ")", "for", "output", "in", "outputs", ":", "output", "=", "re", ".", "sub", "(", "variables_with_spaces", ",", "''", ",", "output", ")", "assert", "' '", "not", "in", "output", ",", "(", "\"Spaces in rule filenames not yet supported (%s)\"", "%", "output", ")", "self", ".", "WriteLn", "(", "'all_deps += %s'", "%", "' '", ".", "join", "(", "outputs", ")", ")", "action", "=", "[", "self", ".", "ExpandInputRoot", "(", "ac", ",", "rule_source_root", ",", "rule_source_dirname", ")", "for", "ac", "in", "rule", "[", "'action'", "]", "]", "mkdirs", "=", "''", "if", "len", "(", "dirs", ")", ">", "0", ":", "mkdirs", "=", "'mkdir -p %s; '", "%", "' '", ".", "join", "(", "dirs", ")", "cd_action", "=", "'cd %s; '", "%", "Sourceify", "(", "self", ".", "path", "or", "'.'", ")", "# action, cd_action, and mkdirs get written to a toplevel variable", "# called cmd_foo. Toplevel variables can't handle things that change", "# per makefile like $(TARGET), so hardcode the target.", "if", "self", ".", "flavor", "==", "'mac'", ":", "action", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "command", ",", "env", ")", "for", "command", "in", "action", "]", "action", "=", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "action", ")", "action", "=", "action", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "cd_action", "=", "cd_action", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "mkdirs", "=", "mkdirs", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "# Set LD_LIBRARY_PATH in case the rule runs an executable from this", "# build which links to shared libs from this build.", "# rules run on the host, so they should in theory only use host", "# libraries, but until everything is made cross-compile safe, also use", "# target libraries.", "# TODO(piman): when everything is cross-compile safe, remove lib.target", "self", ".", "WriteLn", "(", "\"cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=\"", "\"$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; \"", "\"export LD_LIBRARY_PATH; \"", "\"%(cd_action)s%(mkdirs)s%(action)s\"", "%", "{", "'action'", ":", "action", ",", "'cd_action'", ":", "cd_action", ",", "'count'", ":", "count", ",", "'mkdirs'", ":", "mkdirs", ",", "'name'", ":", "name", ",", "}", ")", "self", ".", "WriteLn", "(", "'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@'", "%", "{", "'count'", ":", "count", ",", "'name'", ":", "name", ",", "}", ")", "self", ".", "WriteLn", "(", ")", "count", "+=", "1", "outputs_variable", "=", "'rule_%s_outputs'", "%", "name", "self", ".", "WriteList", "(", "all_outputs", ",", "outputs_variable", ")", "extra_outputs", ".", "append", "(", "'$(%s)'", "%", "outputs_variable", ")", "self", ".", "WriteLn", "(", "'### Finished generating for rule: %s'", "%", "name", ")", "self", ".", "WriteLn", "(", ")", "self", ".", "WriteLn", "(", "'### Finished generating for all rules'", ")", "self", ".", "WriteLn", "(", "''", ")" ]
https://github.com/almonk/Bind/blob/03e9e98fb8b30a58cb4fc2829f06289fa9958897/public/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L932-L1056
zhao94254/fun
491acf6a7d9594f91a8cd717a403d9e1e5d0f386
interpreter/scheme/scheme_primitives.py
python
tscheme_showturtle
()
return okay
Make turtle visible.
Make turtle visible.
[ "Make", "turtle", "visible", "." ]
def tscheme_showturtle(): """Make turtle visible.""" _tscheme_prep() turtle.showturtle() return okay
[ "def", "tscheme_showturtle", "(", ")", ":", "_tscheme_prep", "(", ")", "turtle", ".", "showturtle", "(", ")", "return", "okay" ]
https://github.com/zhao94254/fun/blob/491acf6a7d9594f91a8cd717a403d9e1e5d0f386/interpreter/scheme/scheme_primitives.py#L441-L445
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
python
XCConfigurationList.SetBuildSetting
(self, key, value)
Sets the build setting for key to value in all child XCBuildConfiguration objects.
Sets the build setting for key to value in all child XCBuildConfiguration objects.
[ "Sets", "the", "build", "setting", "for", "key", "to", "value", "in", "all", "child", "XCBuildConfiguration", "objects", "." ]
def SetBuildSetting(self, key, value): """Sets the build setting for key to value in all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.SetBuildSetting(key, value)
[ "def", "SetBuildSetting", "(", "self", ",", "key", ",", "value", ")", ":", "for", "configuration", "in", "self", ".", "_properties", "[", "'buildConfigurations'", "]", ":", "configuration", ".", "SetBuildSetting", "(", "key", ",", "value", ")" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L1671-L1677
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/Bastion.py
python
BastionClass.__getattr__
(self, name)
return attribute
Get an as-yet undefined attribute value. This calls the get() function that was passed to the constructor. The result is stored as an instance variable so that the next time the same attribute is requested, __getattr__() won't be invoked. If the get() function raises an exception, this is simply passed on -- exceptions are not cached.
Get an as-yet undefined attribute value.
[ "Get", "an", "as", "-", "yet", "undefined", "attribute", "value", "." ]
def __getattr__(self, name): """Get an as-yet undefined attribute value. This calls the get() function that was passed to the constructor. The result is stored as an instance variable so that the next time the same attribute is requested, __getattr__() won't be invoked. If the get() function raises an exception, this is simply passed on -- exceptions are not cached. """ attribute = self._get_(name) self.__dict__[name] = attribute return attribute
[ "def", "__getattr__", "(", "self", ",", "name", ")", ":", "attribute", "=", "self", ".", "_get_", "(", "name", ")", "self", ".", "__dict__", "[", "name", "]", "=", "attribute", "return", "attribute" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/Bastion.py#L70-L84
domogik/domogik
fefd584d354875bcb15f351cbc455abffaa6501f
src/domogik/common/daemon/daemon.py
python
get_maximum_file_descriptors
()
return result
Return the maximum number of open file descriptors for this process. Return the process hard resource limit of maximum number of open file descriptors. If the limit is “infinity”, a default value of ``MAXFD`` is returned.
Return the maximum number of open file descriptors for this process.
[ "Return", "the", "maximum", "number", "of", "open", "file", "descriptors", "for", "this", "process", "." ]
def get_maximum_file_descriptors(): """ Return the maximum number of open file descriptors for this process. Return the process hard resource limit of maximum number of open file descriptors. If the limit is “infinity”, a default value of ``MAXFD`` is returned. """ limits = resource.getrlimit(resource.RLIMIT_NOFILE) result = limits[1] if result == resource.RLIM_INFINITY: result = MAXFD return result
[ "def", "get_maximum_file_descriptors", "(", ")", ":", "limits", "=", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ")", "result", "=", "limits", "[", "1", "]", "if", "result", "==", "resource", ".", "RLIM_INFINITY", ":", "result", "=", "MAXFD", "return", "result" ]
https://github.com/domogik/domogik/blob/fefd584d354875bcb15f351cbc455abffaa6501f/src/domogik/common/daemon/daemon.py#L690-L702
nprapps/lunchbox
603c0518aa1594b073174a132585f93c7772ef3c
fabfile/flat.py
python
deploy_file
(bucket, src, dst, headers={})
Deploy a single file to S3, if the local version is different.
Deploy a single file to S3, if the local version is different.
[ "Deploy", "a", "single", "file", "to", "S3", "if", "the", "local", "version", "is", "different", "." ]
def deploy_file(bucket, src, dst, headers={}): """ Deploy a single file to S3, if the local version is different. """ k = bucket.get_key(dst) s3_md5 = None if k: s3_md5 = k.etag.strip('"') else: k = Key(bucket) k.key = dst file_headers = copy.copy(headers) if 'Content-Type' not in headers: file_headers['Content-Type'] = mimetypes.guess_type(src)[0] # Gzip file if os.path.splitext(src)[1].lower() in GZIP_FILE_TYPES: file_headers['Content-Encoding'] = 'gzip' with open(src, 'rb') as f_in: contents = f_in.read() output = StringIO() f_out = gzip.GzipFile(filename=dst, mode='wb', fileobj=output) f_out.write(contents) f_out.close() local_md5 = hashlib.md5() local_md5.update(output.getvalue()) local_md5 = local_md5.hexdigest() if local_md5 == s3_md5: print 'Skipping %s (has not changed)' % src else: print 'Uploading %s --> %s (gzipped)' % (src, dst) k.set_contents_from_string(output.getvalue(), file_headers, policy='public-read') # Non-gzip file else: with open(src, 'rb') as f: local_md5 = hashlib.md5() local_md5.update(f.read()) local_md5 = local_md5.hexdigest() if local_md5 == s3_md5: print 'Skipping %s (has not changed)' % src else: print 'Uploading %s --> %s' % (src, dst) k.set_contents_from_filename(src, file_headers, policy='public-read')
[ "def", "deploy_file", "(", "bucket", ",", "src", ",", "dst", ",", "headers", "=", "{", "}", ")", ":", "k", "=", "bucket", ".", "get_key", "(", "dst", ")", "s3_md5", "=", "None", "if", "k", ":", "s3_md5", "=", "k", ".", "etag", ".", "strip", "(", "'\"'", ")", "else", ":", "k", "=", "Key", "(", "bucket", ")", "k", ".", "key", "=", "dst", "file_headers", "=", "copy", ".", "copy", "(", "headers", ")", "if", "'Content-Type'", "not", "in", "headers", ":", "file_headers", "[", "'Content-Type'", "]", "=", "mimetypes", ".", "guess_type", "(", "src", ")", "[", "0", "]", "# Gzip file", "if", "os", ".", "path", ".", "splitext", "(", "src", ")", "[", "1", "]", ".", "lower", "(", ")", "in", "GZIP_FILE_TYPES", ":", "file_headers", "[", "'Content-Encoding'", "]", "=", "'gzip'", "with", "open", "(", "src", ",", "'rb'", ")", "as", "f_in", ":", "contents", "=", "f_in", ".", "read", "(", ")", "output", "=", "StringIO", "(", ")", "f_out", "=", "gzip", ".", "GzipFile", "(", "filename", "=", "dst", ",", "mode", "=", "'wb'", ",", "fileobj", "=", "output", ")", "f_out", ".", "write", "(", "contents", ")", "f_out", ".", "close", "(", ")", "local_md5", "=", "hashlib", ".", "md5", "(", ")", "local_md5", ".", "update", "(", "output", ".", "getvalue", "(", ")", ")", "local_md5", "=", "local_md5", ".", "hexdigest", "(", ")", "if", "local_md5", "==", "s3_md5", ":", "print", "'Skipping %s (has not changed)'", "%", "src", "else", ":", "print", "'Uploading %s --> %s (gzipped)'", "%", "(", "src", ",", "dst", ")", "k", ".", "set_contents_from_string", "(", "output", ".", "getvalue", "(", ")", ",", "file_headers", ",", "policy", "=", "'public-read'", ")", "# Non-gzip file", "else", ":", "with", "open", "(", "src", ",", "'rb'", ")", "as", "f", ":", "local_md5", "=", "hashlib", ".", "md5", "(", ")", "local_md5", ".", "update", "(", "f", ".", "read", "(", ")", ")", "local_md5", "=", "local_md5", ".", "hexdigest", "(", ")", "if", "local_md5", "==", "s3_md5", ":", "print", "'Skipping %s (has not changed)'", "%", "src", "else", ":", "print", "'Uploading %s --> %s'", "%", "(", "src", ",", "dst", ")", "k", ".", "set_contents_from_filename", "(", "src", ",", "file_headers", ",", "policy", "=", "'public-read'", ")" ]
https://github.com/nprapps/lunchbox/blob/603c0518aa1594b073174a132585f93c7772ef3c/fabfile/flat.py#L26-L76
crits/crits
6b357daa5c3060cf622d3a3b0c7b41a9ca69c049
crits/core/mongo_tools.py
python
delete_file
(sample_md5, collection=settings.COL_SAMPLES)
return success
delete_file allows you to delete a file from a gridfs collection specified in the collection parameter. this will only remove the file object, not metadata from assocatiated collections for full deletion of metadata and file use delete_sample :param sample_md5: The MD5 of the file to delete. :type sample_md5: str :param collection: The collection to delete the file from. :type collection: str :returns: True, False, None
delete_file allows you to delete a file from a gridfs collection specified in the collection parameter. this will only remove the file object, not metadata from assocatiated collections for full deletion of metadata and file use delete_sample
[ "delete_file", "allows", "you", "to", "delete", "a", "file", "from", "a", "gridfs", "collection", "specified", "in", "the", "collection", "parameter", ".", "this", "will", "only", "remove", "the", "file", "object", "not", "metadata", "from", "assocatiated", "collections", "for", "full", "deletion", "of", "metadata", "and", "file", "use", "delete_sample" ]
def delete_file(sample_md5, collection=settings.COL_SAMPLES): """ delete_file allows you to delete a file from a gridfs collection specified in the collection parameter. this will only remove the file object, not metadata from assocatiated collections for full deletion of metadata and file use delete_sample :param sample_md5: The MD5 of the file to delete. :type sample_md5: str :param collection: The collection to delete the file from. :type collection: str :returns: True, False, None """ fm = mongo_connector("%s.files" % collection) sample = fm.find_one({'md5': sample_md5}, {'_id': 1}) success = None if sample: objectid = sample["_id"] fs = gridfs_connector("%s" % collection) try: fs.delete(objectid) return True except: return None return success
[ "def", "delete_file", "(", "sample_md5", ",", "collection", "=", "settings", ".", "COL_SAMPLES", ")", ":", "fm", "=", "mongo_connector", "(", "\"%s.files\"", "%", "collection", ")", "sample", "=", "fm", ".", "find_one", "(", "{", "'md5'", ":", "sample_md5", "}", ",", "{", "'_id'", ":", "1", "}", ")", "success", "=", "None", "if", "sample", ":", "objectid", "=", "sample", "[", "\"_id\"", "]", "fs", "=", "gridfs_connector", "(", "\"%s\"", "%", "collection", ")", "try", ":", "fs", ".", "delete", "(", "objectid", ")", "return", "True", "except", ":", "return", "None", "return", "success" ]
https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/core/mongo_tools.py#L142-L166
facebookarchive/nuclide
2a2a0a642d136768b7d2a6d35a652dc5fb77d70a
modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydevd_bundle/pydevd_additional_thread_info_regular.py
python
PyDBAdditionalThreadInfo.get_topmost_frame
(self, thread)
return current_frames.get(thread.ident)
Gets the topmost frame for the given thread. Note that it may be None and callers should remove the reference to the frame as soon as possible to avoid disturbing user code.
Gets the topmost frame for the given thread. Note that it may be None and callers should remove the reference to the frame as soon as possible to avoid disturbing user code.
[ "Gets", "the", "topmost", "frame", "for", "the", "given", "thread", ".", "Note", "that", "it", "may", "be", "None", "and", "callers", "should", "remove", "the", "reference", "to", "the", "frame", "as", "soon", "as", "possible", "to", "avoid", "disturbing", "user", "code", "." ]
def get_topmost_frame(self, thread): ''' Gets the topmost frame for the given thread. Note that it may be None and callers should remove the reference to the frame as soon as possible to avoid disturbing user code. ''' # sys._current_frames(): dictionary with thread id -> topmost frame current_frames = _current_frames() return current_frames.get(thread.ident)
[ "def", "get_topmost_frame", "(", "self", ",", "thread", ")", ":", "# sys._current_frames(): dictionary with thread id -> topmost frame", "current_frames", "=", "_current_frames", "(", ")", "return", "current_frames", ".", "get", "(", "thread", ".", "ident", ")" ]
https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydevd_bundle/pydevd_additional_thread_info_regular.py#L118-L126