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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/ipaddress.py | python | _BaseNetwork.num_addresses | (self) | return int(self.broadcast_address) - int(self.network_address) + 1 | Number of hosts in the current subnet. | Number of hosts in the current subnet. | [
"Number",
"of",
"hosts",
"in",
"the",
"current",
"subnet",
"."
] | def num_addresses(self):
"""Number of hosts in the current subnet."""
return int(self.broadcast_address) - int(self.network_address) + 1 | [
"def",
"num_addresses",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"broadcast_address",
")",
"-",
"int",
"(",
"self",
".",
"network_address",
")",
"+",
"1"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/ipaddress.py#L847-L849 |
|
facebookarchive/nuclide | 2a2a0a642d136768b7d2a6d35a652dc5fb77d70a | modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py | python | Thread.get_stack_trace_with_labels | (self, depth = 16, bMakePretty = True) | return trace | Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer label ).
@raise WindowsError: Raises an exception on error. | Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue. | [
"Tries",
"to",
"get",
"a",
"stack",
"trace",
"for",
"the",
"current",
"function",
".",
"Only",
"works",
"for",
"functions",
"with",
"standard",
"prologue",
"and",
"epilogue",
"."
] | def get_stack_trace_with_labels(self, depth = 16, bMakePretty = True):
"""
Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer label ).
@raise WindowsError: Raises an exception on error.
"""
try:
trace = self.__get_stack_trace(depth, True, bMakePretty)
except Exception:
trace = ()
if not trace:
trace = self.__get_stack_trace_manually(depth, True, bMakePretty)
return trace | [
"def",
"get_stack_trace_with_labels",
"(",
"self",
",",
"depth",
"=",
"16",
",",
"bMakePretty",
"=",
"True",
")",
":",
"try",
":",
"trace",
"=",
"self",
".",
"__get_stack_trace",
"(",
"depth",
",",
"True",
",",
"bMakePretty",
")",
"except",
"Exception",
":",
"trace",
"=",
"(",
")",
"if",
"not",
"trace",
":",
"trace",
"=",
"self",
".",
"__get_stack_trace_manually",
"(",
"depth",
",",
"True",
",",
"bMakePretty",
")",
"return",
"trace"
] | https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py#L1258-L1286 |
|
Opentrons/opentrons | 466e0567065d8773a81c25cd1b5c7998e00adf2c | api/src/opentrons/hardware_control/api.py | python | API.resume | (self, pause_type: PauseType) | Resume motion after a call to :py:meth:`pause`. | Resume motion after a call to :py:meth:`pause`. | [
"Resume",
"motion",
"after",
"a",
"call",
"to",
":",
"py",
":",
"meth",
":",
"pause",
"."
] | def resume(self, pause_type: PauseType):
"""
Resume motion after a call to :py:meth:`pause`.
"""
self._pause_manager.resume(pause_type)
if self._pause_manager.should_pause:
return
# Resume must be called immediately to awaken thread running hardware
# methods (ThreadManager)
self._backend.resume()
async def _chained_calls():
# mirror what happens API.pause.
await self._execution_manager.resume()
self._backend.resume()
asyncio.run_coroutine_threadsafe(_chained_calls(), self._loop) | [
"def",
"resume",
"(",
"self",
",",
"pause_type",
":",
"PauseType",
")",
":",
"self",
".",
"_pause_manager",
".",
"resume",
"(",
"pause_type",
")",
"if",
"self",
".",
"_pause_manager",
".",
"should_pause",
":",
"return",
"# Resume must be called immediately to awaken thread running hardware",
"# methods (ThreadManager)",
"self",
".",
"_backend",
".",
"resume",
"(",
")",
"async",
"def",
"_chained_calls",
"(",
")",
":",
"# mirror what happens API.pause.",
"await",
"self",
".",
"_execution_manager",
".",
"resume",
"(",
")",
"self",
".",
"_backend",
".",
"resume",
"(",
")",
"asyncio",
".",
"run_coroutine_threadsafe",
"(",
"_chained_calls",
"(",
")",
",",
"self",
".",
"_loop",
")"
] | https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/src/opentrons/hardware_control/api.py#L639-L657 |
||
webrtc/apprtc | db975e22ea07a0c11a4179d4beb2feb31cf344f4 | src/third_party/oauth2client/client.py | python | OAuth2WebServerFlow.step2_exchange | (self, code, http=None) | Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object that can be used to authorize requests.
Raises:
FlowExchangeError if a problem occured exchanging the code for a
refresh_token. | Exhanges a code for OAuth2Credentials. | [
"Exhanges",
"a",
"code",
"for",
"OAuth2Credentials",
"."
] | def step2_exchange(self, code, http=None):
"""Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object that can be used to authorize requests.
Raises:
FlowExchangeError if a problem occured exchanging the code for a
refresh_token.
"""
if not (isinstance(code, str) or isinstance(code, unicode)):
if 'code' not in code:
if 'error' in code:
error_msg = code['error']
else:
error_msg = 'No code was supplied in the query parameters.'
raise FlowExchangeError(error_msg)
else:
code = code['code']
body = urllib.urlencode({
'grant_type': 'authorization_code',
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'redirect_uri': self.redirect_uri,
'scope': self.scope,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
if http is None:
http = httplib2.Http()
resp, content = http.request(self.token_uri, method='POST', body=body,
headers=headers)
d = _parse_exchange_token_response(content)
if resp.status == 200 and 'access_token' in d:
access_token = d['access_token']
refresh_token = d.get('refresh_token', None)
token_expiry = None
if 'expires_in' in d:
token_expiry = datetime.datetime.utcnow() + datetime.timedelta(
seconds=int(d['expires_in']))
if 'id_token' in d:
d['id_token'] = _extract_id_token(d['id_token'])
logger.info('Successfully retrieved access token')
return OAuth2Credentials(access_token, self.client_id,
self.client_secret, refresh_token, token_expiry,
self.token_uri, self.user_agent,
revoke_uri=self.revoke_uri,
id_token=d.get('id_token', None),
token_response=d)
else:
logger.info('Failed to retrieve access token: %s' % content)
if 'error' in d:
# you never know what those providers got to say
error_msg = unicode(d['error'])
else:
error_msg = 'Invalid response: %s.' % str(resp.status)
raise FlowExchangeError(error_msg) | [
"def",
"step2_exchange",
"(",
"self",
",",
"code",
",",
"http",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"code",
",",
"str",
")",
"or",
"isinstance",
"(",
"code",
",",
"unicode",
")",
")",
":",
"if",
"'code'",
"not",
"in",
"code",
":",
"if",
"'error'",
"in",
"code",
":",
"error_msg",
"=",
"code",
"[",
"'error'",
"]",
"else",
":",
"error_msg",
"=",
"'No code was supplied in the query parameters.'",
"raise",
"FlowExchangeError",
"(",
"error_msg",
")",
"else",
":",
"code",
"=",
"code",
"[",
"'code'",
"]",
"body",
"=",
"urllib",
".",
"urlencode",
"(",
"{",
"'grant_type'",
":",
"'authorization_code'",
",",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'client_secret'",
":",
"self",
".",
"client_secret",
",",
"'code'",
":",
"code",
",",
"'redirect_uri'",
":",
"self",
".",
"redirect_uri",
",",
"'scope'",
":",
"self",
".",
"scope",
",",
"}",
")",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/x-www-form-urlencoded'",
",",
"}",
"if",
"self",
".",
"user_agent",
"is",
"not",
"None",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"self",
".",
"user_agent",
"if",
"http",
"is",
"None",
":",
"http",
"=",
"httplib2",
".",
"Http",
"(",
")",
"resp",
",",
"content",
"=",
"http",
".",
"request",
"(",
"self",
".",
"token_uri",
",",
"method",
"=",
"'POST'",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"headers",
")",
"d",
"=",
"_parse_exchange_token_response",
"(",
"content",
")",
"if",
"resp",
".",
"status",
"==",
"200",
"and",
"'access_token'",
"in",
"d",
":",
"access_token",
"=",
"d",
"[",
"'access_token'",
"]",
"refresh_token",
"=",
"d",
".",
"get",
"(",
"'refresh_token'",
",",
"None",
")",
"token_expiry",
"=",
"None",
"if",
"'expires_in'",
"in",
"d",
":",
"token_expiry",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"int",
"(",
"d",
"[",
"'expires_in'",
"]",
")",
")",
"if",
"'id_token'",
"in",
"d",
":",
"d",
"[",
"'id_token'",
"]",
"=",
"_extract_id_token",
"(",
"d",
"[",
"'id_token'",
"]",
")",
"logger",
".",
"info",
"(",
"'Successfully retrieved access token'",
")",
"return",
"OAuth2Credentials",
"(",
"access_token",
",",
"self",
".",
"client_id",
",",
"self",
".",
"client_secret",
",",
"refresh_token",
",",
"token_expiry",
",",
"self",
".",
"token_uri",
",",
"self",
".",
"user_agent",
",",
"revoke_uri",
"=",
"self",
".",
"revoke_uri",
",",
"id_token",
"=",
"d",
".",
"get",
"(",
"'id_token'",
",",
"None",
")",
",",
"token_response",
"=",
"d",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Failed to retrieve access token: %s'",
"%",
"content",
")",
"if",
"'error'",
"in",
"d",
":",
"# you never know what those providers got to say",
"error_msg",
"=",
"unicode",
"(",
"d",
"[",
"'error'",
"]",
")",
"else",
":",
"error_msg",
"=",
"'Invalid response: %s.'",
"%",
"str",
"(",
"resp",
".",
"status",
")",
"raise",
"FlowExchangeError",
"(",
"error_msg",
")"
] | https://github.com/webrtc/apprtc/blob/db975e22ea07a0c11a4179d4beb2feb31cf344f4/src/third_party/oauth2client/client.py#L1237-L1310 |
||
axa-group/Parsr | 3a2193b15c56a8fbcafe5efbddd83adbb0f8fd9d | clients/python-client/parsr_client/parsr_client.py | python | ParsrClient.set_server | (self, server: str) | Setter for the Parsr server's address | Setter for the Parsr server's address | [
"Setter",
"for",
"the",
"Parsr",
"server",
"s",
"address"
] | def set_server(self, server: str):
"""Setter for the Parsr server's address
"""
self.server = server | [
"def",
"set_server",
"(",
"self",
",",
"server",
":",
"str",
")",
":",
"self",
".",
"server",
"=",
"server"
] | https://github.com/axa-group/Parsr/blob/3a2193b15c56a8fbcafe5efbddd83adbb0f8fd9d/clients/python-client/parsr_client/parsr_client.py#L58-L61 |
||
prometheus-ar/vot.ar | 72d8fa1ea08fe417b64340b98dff68df8364afdf | msa/core/armve/protocol.py | python | Printer.do_print | (self) | Envia el comando CMD_PRINTER_PRINT al ARM. | Envia el comando CMD_PRINTER_PRINT al ARM. | [
"Envia",
"el",
"comando",
"CMD_PRINTER_PRINT",
"al",
"ARM",
"."
] | def do_print(self):
"""Envia el comando CMD_PRINTER_PRINT al ARM."""
self._send_command(CMD_PRINTER_PRINT) | [
"def",
"do_print",
"(",
"self",
")",
":",
"self",
".",
"_send_command",
"(",
"CMD_PRINTER_PRINT",
")"
] | https://github.com/prometheus-ar/vot.ar/blob/72d8fa1ea08fe417b64340b98dff68df8364afdf/msa/core/armve/protocol.py#L1458-L1460 |
||
sagemath/cloud | 054854b87817edfa95e9044c793059bddc361e67 | sage_salvus.py | python | exercise | (code) | r"""
Use the %exercise cell decorator to create interactive exercise
sets. Put %exercise at the top of the cell, then write Sage code
in the cell that defines the following (all are optional):
- a ``question`` variable, as an HTML string with math in dollar
signs
- an ``answer`` variable, which can be any object, or a pair
(correct_value, interact control) -- see the docstring for
interact for controls.
- an optional callable ``check(answer)`` that returns a boolean or
a 2-tuple
(True or False, message),
where the first argument is True if the answer is correct, and
the optional second argument is a message that should be
displayed in response to the given answer. NOTE: Often the
input "answer" will be a string, so you may have to use Integer,
RealNumber, or sage_eval to evaluate it, depending
on what you want to allow the user to do.
- hints -- optional list of strings to display in sequence each
time the user enters a wrong answer. The last string is
displayed repeatedly. If hints is omitted, the correct answer
is displayed after three attempts.
NOTE: The code that defines the exercise is executed so that it
does not impact (and is not impacted by) the global scope of your
variables elsewhere in your session. Thus you can have many
%exercise cells in a single worksheet with no interference between
them.
The following examples further illustrate how %exercise works.
An exercise to test your ability to sum the first $n$ integers::
%exercise
title = "Sum the first n integers, like Gauss did."
n = randint(3, 100)
question = "What is the sum $1 + 2 + \\cdots + %s$ of the first %s positive integers?"%(n,n)
answer = n*(n+1)//2
Transpose a matrix::
%exercise
title = r"Transpose a $2 \times 2$ Matrix"
A = random_matrix(ZZ,2)
question = "What is the transpose of $%s?$"%latex(A)
answer = A.transpose()
Add together a few numbers::
%exercise
k = randint(2,5)
title = "Add %s numbers"%k
v = [randint(1,10) for _ in range(k)]
question = "What is the sum $%s$?"%(' + '.join([str(x) for x in v]))
answer = sum(v)
The trace of a matrix::
%exercise
title = "Compute the trace of a matrix."
A = random_matrix(ZZ, 3, x=-5, y = 5)^2
question = "What is the trace of $$%s?$$"%latex(A)
answer = A.trace()
Some basic arithmetic with hints and dynamic feedback::
%exercise
k = randint(2,5)
title = "Add %s numbers"%k
v = [randint(1,10) for _ in range(k)]
question = "What is the sum $%s$?"%(' + '.join([str(x) for x in v]))
answer = sum(v)
hints = ['This is basic arithmetic.', 'The sum is near %s.'%(answer+randint(1,5)), "The answer is %s."%answer]
def check(attempt):
c = Integer(attempt) - answer
if c == 0:
return True
if abs(c) >= 10:
return False, "Gees -- not even close!"
if c < 0:
return False, "too low"
if c > 0:
return False, "too high" | r"""
Use the %exercise cell decorator to create interactive exercise
sets. Put %exercise at the top of the cell, then write Sage code
in the cell that defines the following (all are optional): | [
"r",
"Use",
"the",
"%exercise",
"cell",
"decorator",
"to",
"create",
"interactive",
"exercise",
"sets",
".",
"Put",
"%exercise",
"at",
"the",
"top",
"of",
"the",
"cell",
"then",
"write",
"Sage",
"code",
"in",
"the",
"cell",
"that",
"defines",
"the",
"following",
"(",
"all",
"are",
"optional",
")",
":"
] | def exercise(code):
r"""
Use the %exercise cell decorator to create interactive exercise
sets. Put %exercise at the top of the cell, then write Sage code
in the cell that defines the following (all are optional):
- a ``question`` variable, as an HTML string with math in dollar
signs
- an ``answer`` variable, which can be any object, or a pair
(correct_value, interact control) -- see the docstring for
interact for controls.
- an optional callable ``check(answer)`` that returns a boolean or
a 2-tuple
(True or False, message),
where the first argument is True if the answer is correct, and
the optional second argument is a message that should be
displayed in response to the given answer. NOTE: Often the
input "answer" will be a string, so you may have to use Integer,
RealNumber, or sage_eval to evaluate it, depending
on what you want to allow the user to do.
- hints -- optional list of strings to display in sequence each
time the user enters a wrong answer. The last string is
displayed repeatedly. If hints is omitted, the correct answer
is displayed after three attempts.
NOTE: The code that defines the exercise is executed so that it
does not impact (and is not impacted by) the global scope of your
variables elsewhere in your session. Thus you can have many
%exercise cells in a single worksheet with no interference between
them.
The following examples further illustrate how %exercise works.
An exercise to test your ability to sum the first $n$ integers::
%exercise
title = "Sum the first n integers, like Gauss did."
n = randint(3, 100)
question = "What is the sum $1 + 2 + \\cdots + %s$ of the first %s positive integers?"%(n,n)
answer = n*(n+1)//2
Transpose a matrix::
%exercise
title = r"Transpose a $2 \times 2$ Matrix"
A = random_matrix(ZZ,2)
question = "What is the transpose of $%s?$"%latex(A)
answer = A.transpose()
Add together a few numbers::
%exercise
k = randint(2,5)
title = "Add %s numbers"%k
v = [randint(1,10) for _ in range(k)]
question = "What is the sum $%s$?"%(' + '.join([str(x) for x in v]))
answer = sum(v)
The trace of a matrix::
%exercise
title = "Compute the trace of a matrix."
A = random_matrix(ZZ, 3, x=-5, y = 5)^2
question = "What is the trace of $$%s?$$"%latex(A)
answer = A.trace()
Some basic arithmetic with hints and dynamic feedback::
%exercise
k = randint(2,5)
title = "Add %s numbers"%k
v = [randint(1,10) for _ in range(k)]
question = "What is the sum $%s$?"%(' + '.join([str(x) for x in v]))
answer = sum(v)
hints = ['This is basic arithmetic.', 'The sum is near %s.'%(answer+randint(1,5)), "The answer is %s."%answer]
def check(attempt):
c = Integer(attempt) - answer
if c == 0:
return True
if abs(c) >= 10:
return False, "Gees -- not even close!"
if c < 0:
return False, "too low"
if c > 0:
return False, "too high"
"""
f = closure(code)
def g():
x = f()
return x.get('title',''), x.get('question', ''), x.get('answer',''), x.get('check',None), x.get('hints',None)
title, question, answer, check, hints = g()
obj = {}
obj['E'] = Exercise(question, answer, check, hints)
obj['title'] = title
def title_control(t):
return text_control('<h3 class="lighten">%s</h3>'%t)
the_times = []
@interact(layout=[[('go',1), ('title',11,'')],[('')], [('times',12, "<b>Times:</b>")]], flicker=True)
def h(go = button(" "*5 + "Go" + " "*7, label='', icon='fa-refresh', classes="btn-large btn-success"),
title = title_control(title),
times = text_control('')):
c = interact.changed()
if 'go' in c or 'another' in c:
interact.title = title_control(obj['title'])
def cb(obj):
the_times.append("%.1f"%obj['time'])
h.times = ', '.join(the_times)
obj['E'].ask(cb)
title, question, answer, check, hints = g() # get ready for next time.
obj['title'] = title
obj['E'] = Exercise(question, answer, check, hints) | [
"def",
"exercise",
"(",
"code",
")",
":",
"f",
"=",
"closure",
"(",
"code",
")",
"def",
"g",
"(",
")",
":",
"x",
"=",
"f",
"(",
")",
"return",
"x",
".",
"get",
"(",
"'title'",
",",
"''",
")",
",",
"x",
".",
"get",
"(",
"'question'",
",",
"''",
")",
",",
"x",
".",
"get",
"(",
"'answer'",
",",
"''",
")",
",",
"x",
".",
"get",
"(",
"'check'",
",",
"None",
")",
",",
"x",
".",
"get",
"(",
"'hints'",
",",
"None",
")",
"title",
",",
"question",
",",
"answer",
",",
"check",
",",
"hints",
"=",
"g",
"(",
")",
"obj",
"=",
"{",
"}",
"obj",
"[",
"'E'",
"]",
"=",
"Exercise",
"(",
"question",
",",
"answer",
",",
"check",
",",
"hints",
")",
"obj",
"[",
"'title'",
"]",
"=",
"title",
"def",
"title_control",
"(",
"t",
")",
":",
"return",
"text_control",
"(",
"'<h3 class=\"lighten\">%s</h3>'",
"%",
"t",
")",
"the_times",
"=",
"[",
"]",
"@",
"interact",
"(",
"layout",
"=",
"[",
"[",
"(",
"'go'",
",",
"1",
")",
",",
"(",
"'title'",
",",
"11",
",",
"''",
")",
"]",
",",
"[",
"(",
"''",
")",
"]",
",",
"[",
"(",
"'times'",
",",
"12",
",",
"\"<b>Times:</b>\"",
")",
"]",
"]",
",",
"flicker",
"=",
"True",
")",
"def",
"h",
"(",
"go",
"=",
"button",
"(",
"\" \"",
"*",
"5",
"+",
"\"Go\"",
"+",
"\" \"",
"*",
"7",
",",
"label",
"=",
"''",
",",
"icon",
"=",
"'fa-refresh'",
",",
"classes",
"=",
"\"btn-large btn-success\"",
")",
",",
"title",
"=",
"title_control",
"(",
"title",
")",
",",
"times",
"=",
"text_control",
"(",
"''",
")",
")",
":",
"c",
"=",
"interact",
".",
"changed",
"(",
")",
"if",
"'go'",
"in",
"c",
"or",
"'another'",
"in",
"c",
":",
"interact",
".",
"title",
"=",
"title_control",
"(",
"obj",
"[",
"'title'",
"]",
")",
"def",
"cb",
"(",
"obj",
")",
":",
"the_times",
".",
"append",
"(",
"\"%.1f\"",
"%",
"obj",
"[",
"'time'",
"]",
")",
"h",
".",
"times",
"=",
"', '",
".",
"join",
"(",
"the_times",
")",
"obj",
"[",
"'E'",
"]",
".",
"ask",
"(",
"cb",
")",
"title",
",",
"question",
",",
"answer",
",",
"check",
",",
"hints",
"=",
"g",
"(",
")",
"# get ready for next time.",
"obj",
"[",
"'title'",
"]",
"=",
"title",
"obj",
"[",
"'E'",
"]",
"=",
"Exercise",
"(",
"question",
",",
"answer",
",",
"check",
",",
"hints",
")"
] | https://github.com/sagemath/cloud/blob/054854b87817edfa95e9044c793059bddc361e67/sage_salvus.py#L2498-L2617 |
||
kemayo/maphilight | e00d927f648c00b634470bc6c4750378b4953cc0 | tools/parse_path.py | python | Sequence | (token) | return OneOrMore(token + maybeComma) | A sequence of the token | A sequence of the token | [
"A",
"sequence",
"of",
"the",
"token"
] | def Sequence(token):
""" A sequence of the token"""
return OneOrMore(token + maybeComma) | [
"def",
"Sequence",
"(",
"token",
")",
":",
"return",
"OneOrMore",
"(",
"token",
"+",
"maybeComma",
")"
] | https://github.com/kemayo/maphilight/blob/e00d927f648c00b634470bc6c4750378b4953cc0/tools/parse_path.py#L25-L27 |
|
openwisp/openwisp-controller | 0bfda7a28c86092f165b177c551c07babcb40630 | openwisp_controller/subnet_division/rule_types/base.py | python | BaseSubnetDivisionRuleType.should_create_subnets_ips | (cls, instance, **kwargs) | return a boolean value whether subnets and IPs should
be provisioned for "instance" object | return a boolean value whether subnets and IPs should
be provisioned for "instance" object | [
"return",
"a",
"boolean",
"value",
"whether",
"subnets",
"and",
"IPs",
"should",
"be",
"provisioned",
"for",
"instance",
"object"
] | def should_create_subnets_ips(cls, instance, **kwargs):
"""
return a boolean value whether subnets and IPs should
be provisioned for "instance" object
"""
raise NotImplementedError() | [
"def",
"should_create_subnets_ips",
"(",
"cls",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/openwisp/openwisp-controller/blob/0bfda7a28c86092f165b177c551c07babcb40630/openwisp_controller/subnet_division/rule_types/base.py#L99-L104 |
||
sbrshk/whatever | f7ba72effd6f836ca701ed889c747db804d5ea8f | node_modules/node-gyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.ComputeAndroidModule | (self, spec) | return ''.join([prefix, middle, suffix]) | Return the Android module name used for a gyp spec.
We use the complete qualified target name to avoid collisions between
duplicate targets in different directories. We also add a suffix to
distinguish gyp-generated module names. | Return the Android module name used for a gyp spec. | [
"Return",
"the",
"Android",
"module",
"name",
"used",
"for",
"a",
"gyp",
"spec",
"."
] | def ComputeAndroidModule(self, spec):
"""Return the Android module name used for a gyp spec.
We use the complete qualified target name to avoid collisions between
duplicate targets in different directories. We also add a suffix to
distinguish gyp-generated module names.
"""
if int(spec.get('android_unmangled_name', 0)):
assert self.type != 'shared_library' or self.target.startswith('lib')
return self.target
if self.type == 'shared_library':
# For reasons of convention, the Android build system requires that all
# shared library modules are named 'libfoo' when generating -l flags.
prefix = 'lib_'
else:
prefix = ''
if spec['toolset'] == 'host':
suffix = '_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp'
else:
suffix = '_gyp'
if self.path:
middle = make.StringToMakefileVariable('%s_%s' % (self.path, self.target))
else:
middle = make.StringToMakefileVariable(self.target)
return ''.join([prefix, middle, suffix]) | [
"def",
"ComputeAndroidModule",
"(",
"self",
",",
"spec",
")",
":",
"if",
"int",
"(",
"spec",
".",
"get",
"(",
"'android_unmangled_name'",
",",
"0",
")",
")",
":",
"assert",
"self",
".",
"type",
"!=",
"'shared_library'",
"or",
"self",
".",
"target",
".",
"startswith",
"(",
"'lib'",
")",
"return",
"self",
".",
"target",
"if",
"self",
".",
"type",
"==",
"'shared_library'",
":",
"# For reasons of convention, the Android build system requires that all",
"# shared library modules are named 'libfoo' when generating -l flags.",
"prefix",
"=",
"'lib_'",
"else",
":",
"prefix",
"=",
"''",
"if",
"spec",
"[",
"'toolset'",
"]",
"==",
"'host'",
":",
"suffix",
"=",
"'_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp'",
"else",
":",
"suffix",
"=",
"'_gyp'",
"if",
"self",
".",
"path",
":",
"middle",
"=",
"make",
".",
"StringToMakefileVariable",
"(",
"'%s_%s'",
"%",
"(",
"self",
".",
"path",
",",
"self",
".",
"target",
")",
")",
"else",
":",
"middle",
"=",
"make",
".",
"StringToMakefileVariable",
"(",
"self",
".",
"target",
")",
"return",
"''",
".",
"join",
"(",
"[",
"prefix",
",",
"middle",
",",
"suffix",
"]",
")"
] | https://github.com/sbrshk/whatever/blob/f7ba72effd6f836ca701ed889c747db804d5ea8f/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L585-L614 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | bt5/erp5_big_file/DocumentTemplateItem/portal_components/document.erp5.BigFile.py | python | BigFile._appendData | (self, data_chunk, content_type=None) | append data chunk to the end of the file
NOTE if content_type is specified, it will change content_type for the
whole file. | append data chunk to the end of the file | [
"append",
"data",
"chunk",
"to",
"the",
"end",
"of",
"the",
"file"
] | def _appendData(self, data_chunk, content_type=None):
"""append data chunk to the end of the file
NOTE if content_type is specified, it will change content_type for the
whole file.
"""
data, size = self._read_data(data_chunk, data=self._baseGetData())
content_type=self._get_content_type(data_chunk, data, self.__name__,
content_type or self.content_type)
self.update_data(data, content_type, size) | [
"def",
"_appendData",
"(",
"self",
",",
"data_chunk",
",",
"content_type",
"=",
"None",
")",
":",
"data",
",",
"size",
"=",
"self",
".",
"_read_data",
"(",
"data_chunk",
",",
"data",
"=",
"self",
".",
"_baseGetData",
"(",
")",
")",
"content_type",
"=",
"self",
".",
"_get_content_type",
"(",
"data_chunk",
",",
"data",
",",
"self",
".",
"__name__",
",",
"content_type",
"or",
"self",
".",
"content_type",
")",
"self",
".",
"update_data",
"(",
"data",
",",
"content_type",
",",
"size",
")"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_big_file/DocumentTemplateItem/portal_components/document.erp5.BigFile.py#L398-L407 |
||
GoogleCloudPlatform/PerfKitExplorer | 9efa61015d50c25f6d753f0212ad3bf16876d496 | server/perfkit/explorer/samples_mart/explorer_method.py | python | ExplorerQueryBase.__init__ | (self, data_client=None, dataset_name=None) | Create credentials and storage service.
If a data_client is not provided, a credential_file will be used to get
a data connection.
Args:
data_client: A class that provides data connectivity. Typically a
BigQueryClient instance or specialization.
dataset_name: The name of the BigQuery dataset that contains the results. | Create credentials and storage service. | [
"Create",
"credentials",
"and",
"storage",
"service",
"."
] | def __init__(self, data_client=None, dataset_name=None):
"""Create credentials and storage service.
If a data_client is not provided, a credential_file will be used to get
a data connection.
Args:
data_client: A class that provides data connectivity. Typically a
BigQueryClient instance or specialization.
dataset_name: The name of the BigQuery dataset that contains the results.
"""
self._data_client = data_client
self.dataset_name = dataset_name or big_query_client.DATASET_ID
self._Initialize() | [
"def",
"__init__",
"(",
"self",
",",
"data_client",
"=",
"None",
",",
"dataset_name",
"=",
"None",
")",
":",
"self",
".",
"_data_client",
"=",
"data_client",
"self",
".",
"dataset_name",
"=",
"dataset_name",
"or",
"big_query_client",
".",
"DATASET_ID",
"self",
".",
"_Initialize",
"(",
")"
] | https://github.com/GoogleCloudPlatform/PerfKitExplorer/blob/9efa61015d50c25f6d753f0212ad3bf16876d496/server/perfkit/explorer/samples_mart/explorer_method.py#L49-L63 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/difflib.py | python | unified_diff | (a, b, fromfile='', tofile='', fromfiledate='',
tofiledate='', n=3, lineterm='\n') | r"""
Compare two sequences of lines; generate the delta as a unified diff.
Unified diffs are a compact way of showing line changes and a few
lines of context. The number of context lines is set by 'n' which
defaults to three.
By default, the diff control lines (those with ---, +++, or @@) are
created with a trailing newline. This is helpful so that inputs
created from file.readlines() result in diffs that are suitable for
file.writelines() since both the inputs and outputs have trailing
newlines.
For inputs that do not have trailing newlines, set the lineterm
argument to "" so that the output will be uniformly newline free.
The unidiff format normally has a header for filenames and modification
times. Any or all of these may be specified using strings for
'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
The modification times are normally expressed in the ISO 8601 format.
Example:
>>> for line in unified_diff('one two three four'.split(),
... 'zero one tree four'.split(), 'Original', 'Current',
... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
... lineterm=''):
... print line # doctest: +NORMALIZE_WHITESPACE
--- Original 2005-01-26 23:30:50
+++ Current 2010-04-02 10:20:52
@@ -1,4 +1,4 @@
+zero
one
-two
-three
+tree
four | r"""
Compare two sequences of lines; generate the delta as a unified diff. | [
"r",
"Compare",
"two",
"sequences",
"of",
"lines",
";",
"generate",
"the",
"delta",
"as",
"a",
"unified",
"diff",
"."
] | def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
tofiledate='', n=3, lineterm='\n'):
r"""
Compare two sequences of lines; generate the delta as a unified diff.
Unified diffs are a compact way of showing line changes and a few
lines of context. The number of context lines is set by 'n' which
defaults to three.
By default, the diff control lines (those with ---, +++, or @@) are
created with a trailing newline. This is helpful so that inputs
created from file.readlines() result in diffs that are suitable for
file.writelines() since both the inputs and outputs have trailing
newlines.
For inputs that do not have trailing newlines, set the lineterm
argument to "" so that the output will be uniformly newline free.
The unidiff format normally has a header for filenames and modification
times. Any or all of these may be specified using strings for
'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
The modification times are normally expressed in the ISO 8601 format.
Example:
>>> for line in unified_diff('one two three four'.split(),
... 'zero one tree four'.split(), 'Original', 'Current',
... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
... lineterm=''):
... print line # doctest: +NORMALIZE_WHITESPACE
--- Original 2005-01-26 23:30:50
+++ Current 2010-04-02 10:20:52
@@ -1,4 +1,4 @@
+zero
one
-two
-three
+tree
four
"""
started = False
for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
if not started:
started = True
fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
todate = '\t{}'.format(tofiledate) if tofiledate else ''
yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
yield '+++ {}{}{}'.format(tofile, todate, lineterm)
first, last = group[0], group[-1]
file1_range = _format_range_unified(first[1], last[2])
file2_range = _format_range_unified(first[3], last[4])
yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
for tag, i1, i2, j1, j2 in group:
if tag == 'equal':
for line in a[i1:i2]:
yield ' ' + line
continue
if tag in ('replace', 'delete'):
for line in a[i1:i2]:
yield '-' + line
if tag in ('replace', 'insert'):
for line in b[j1:j2]:
yield '+' + line | [
"def",
"unified_diff",
"(",
"a",
",",
"b",
",",
"fromfile",
"=",
"''",
",",
"tofile",
"=",
"''",
",",
"fromfiledate",
"=",
"''",
",",
"tofiledate",
"=",
"''",
",",
"n",
"=",
"3",
",",
"lineterm",
"=",
"'\\n'",
")",
":",
"started",
"=",
"False",
"for",
"group",
"in",
"SequenceMatcher",
"(",
"None",
",",
"a",
",",
"b",
")",
".",
"get_grouped_opcodes",
"(",
"n",
")",
":",
"if",
"not",
"started",
":",
"started",
"=",
"True",
"fromdate",
"=",
"'\\t{}'",
".",
"format",
"(",
"fromfiledate",
")",
"if",
"fromfiledate",
"else",
"''",
"todate",
"=",
"'\\t{}'",
".",
"format",
"(",
"tofiledate",
")",
"if",
"tofiledate",
"else",
"''",
"yield",
"'--- {}{}{}'",
".",
"format",
"(",
"fromfile",
",",
"fromdate",
",",
"lineterm",
")",
"yield",
"'+++ {}{}{}'",
".",
"format",
"(",
"tofile",
",",
"todate",
",",
"lineterm",
")",
"first",
",",
"last",
"=",
"group",
"[",
"0",
"]",
",",
"group",
"[",
"-",
"1",
"]",
"file1_range",
"=",
"_format_range_unified",
"(",
"first",
"[",
"1",
"]",
",",
"last",
"[",
"2",
"]",
")",
"file2_range",
"=",
"_format_range_unified",
"(",
"first",
"[",
"3",
"]",
",",
"last",
"[",
"4",
"]",
")",
"yield",
"'@@ -{} +{} @@{}'",
".",
"format",
"(",
"file1_range",
",",
"file2_range",
",",
"lineterm",
")",
"for",
"tag",
",",
"i1",
",",
"i2",
",",
"j1",
",",
"j2",
"in",
"group",
":",
"if",
"tag",
"==",
"'equal'",
":",
"for",
"line",
"in",
"a",
"[",
"i1",
":",
"i2",
"]",
":",
"yield",
"' '",
"+",
"line",
"continue",
"if",
"tag",
"in",
"(",
"'replace'",
",",
"'delete'",
")",
":",
"for",
"line",
"in",
"a",
"[",
"i1",
":",
"i2",
"]",
":",
"yield",
"'-'",
"+",
"line",
"if",
"tag",
"in",
"(",
"'replace'",
",",
"'insert'",
")",
":",
"for",
"line",
"in",
"b",
"[",
"j1",
":",
"j2",
"]",
":",
"yield",
"'+'",
"+",
"line"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/difflib.py#L1158-L1223 |
||
oldj/SwitchHosts | d0eb2321fe36780ec32c914cbc69a818fc1918d3 | alfred/workflow/web.py | python | request | (method, url, params=None, data=None, headers=None, cookies=None,
files=None, auth=None, timeout=60, allow_redirects=False,
stream=False) | return Response(req, stream) | Initiate an HTTP(S) request. Returns :class:`Response` object.
:param method: 'GET' or 'POST'
:type method: unicode
:param url: URL to open
:type url: unicode
:param params: mapping of URL parameters
:type params: dict
:param data: mapping of form data ``{'field_name': 'value'}`` or
:class:`str`
:type data: dict or str
:param headers: HTTP headers
:type headers: dict
:param cookies: cookies to send to server
:type cookies: dict
:param files: files to upload (see below).
:type files: dict
:param auth: username, password
:type auth: tuple
:param timeout: connection timeout limit in seconds
:type timeout: int
:param allow_redirects: follow redirections
:type allow_redirects: bool
:param stream: Stream content instead of fetching it all at once.
:type stream: bool
:returns: Response object
:rtype: :class:`Response`
The ``files`` argument is a dictionary::
{'fieldname' : { 'filename': 'blah.txt',
'content': '<binary data>',
'mimetype': 'text/plain'}
}
* ``fieldname`` is the name of the field in the HTML form.
* ``mimetype`` is optional. If not provided, :mod:`mimetypes` will
be used to guess the mimetype, or ``application/octet-stream``
will be used. | Initiate an HTTP(S) request. Returns :class:`Response` object. | [
"Initiate",
"an",
"HTTP",
"(",
"S",
")",
"request",
".",
"Returns",
":",
"class",
":",
"Response",
"object",
"."
] | def request(method, url, params=None, data=None, headers=None, cookies=None,
files=None, auth=None, timeout=60, allow_redirects=False,
stream=False):
"""Initiate an HTTP(S) request. Returns :class:`Response` object.
:param method: 'GET' or 'POST'
:type method: unicode
:param url: URL to open
:type url: unicode
:param params: mapping of URL parameters
:type params: dict
:param data: mapping of form data ``{'field_name': 'value'}`` or
:class:`str`
:type data: dict or str
:param headers: HTTP headers
:type headers: dict
:param cookies: cookies to send to server
:type cookies: dict
:param files: files to upload (see below).
:type files: dict
:param auth: username, password
:type auth: tuple
:param timeout: connection timeout limit in seconds
:type timeout: int
:param allow_redirects: follow redirections
:type allow_redirects: bool
:param stream: Stream content instead of fetching it all at once.
:type stream: bool
:returns: Response object
:rtype: :class:`Response`
The ``files`` argument is a dictionary::
{'fieldname' : { 'filename': 'blah.txt',
'content': '<binary data>',
'mimetype': 'text/plain'}
}
* ``fieldname`` is the name of the field in the HTML form.
* ``mimetype`` is optional. If not provided, :mod:`mimetypes` will
be used to guess the mimetype, or ``application/octet-stream``
will be used.
"""
# TODO: cookies
socket.setdefaulttimeout(timeout)
# Default handlers
openers = []
if not allow_redirects:
openers.append(NoRedirectHandler())
if auth is not None: # Add authorisation handler
username, password = auth
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, url, username, password)
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
openers.append(auth_manager)
# Install our custom chain of openers
opener = urllib2.build_opener(*openers)
urllib2.install_opener(opener)
if not headers:
headers = CaseInsensitiveDictionary()
else:
headers = CaseInsensitiveDictionary(headers)
if 'user-agent' not in headers:
headers['user-agent'] = USER_AGENT
# Accept gzip-encoded content
encodings = [s.strip() for s in
headers.get('accept-encoding', '').split(',')]
if 'gzip' not in encodings:
encodings.append('gzip')
headers['accept-encoding'] = ', '.join(encodings)
if files:
if not data:
data = {}
new_headers, data = encode_multipart_formdata(data, files)
headers.update(new_headers)
elif data and isinstance(data, dict):
data = urllib.urlencode(str_dict(data))
# Make sure everything is encoded text
headers = str_dict(headers)
if isinstance(url, unicode):
url = url.encode('utf-8')
if params: # GET args (POST args are handled in encode_multipart_formdata)
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
if query: # Combine query string and `params`
url_params = urlparse.parse_qs(query)
# `params` take precedence over URL query string
url_params.update(params)
params = url_params
query = urllib.urlencode(str_dict(params), doseq=True)
url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))
req = Request(url, data, headers, method=method)
return Response(req, stream) | [
"def",
"request",
"(",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"cookies",
"=",
"None",
",",
"files",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"60",
",",
"allow_redirects",
"=",
"False",
",",
"stream",
"=",
"False",
")",
":",
"# TODO: cookies",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"# Default handlers",
"openers",
"=",
"[",
"]",
"if",
"not",
"allow_redirects",
":",
"openers",
".",
"append",
"(",
"NoRedirectHandler",
"(",
")",
")",
"if",
"auth",
"is",
"not",
"None",
":",
"# Add authorisation handler",
"username",
",",
"password",
"=",
"auth",
"password_manager",
"=",
"urllib2",
".",
"HTTPPasswordMgrWithDefaultRealm",
"(",
")",
"password_manager",
".",
"add_password",
"(",
"None",
",",
"url",
",",
"username",
",",
"password",
")",
"auth_manager",
"=",
"urllib2",
".",
"HTTPBasicAuthHandler",
"(",
"password_manager",
")",
"openers",
".",
"append",
"(",
"auth_manager",
")",
"# Install our custom chain of openers",
"opener",
"=",
"urllib2",
".",
"build_opener",
"(",
"*",
"openers",
")",
"urllib2",
".",
"install_opener",
"(",
"opener",
")",
"if",
"not",
"headers",
":",
"headers",
"=",
"CaseInsensitiveDictionary",
"(",
")",
"else",
":",
"headers",
"=",
"CaseInsensitiveDictionary",
"(",
"headers",
")",
"if",
"'user-agent'",
"not",
"in",
"headers",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"USER_AGENT",
"# Accept gzip-encoded content",
"encodings",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"headers",
".",
"get",
"(",
"'accept-encoding'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
"]",
"if",
"'gzip'",
"not",
"in",
"encodings",
":",
"encodings",
".",
"append",
"(",
"'gzip'",
")",
"headers",
"[",
"'accept-encoding'",
"]",
"=",
"', '",
".",
"join",
"(",
"encodings",
")",
"if",
"files",
":",
"if",
"not",
"data",
":",
"data",
"=",
"{",
"}",
"new_headers",
",",
"data",
"=",
"encode_multipart_formdata",
"(",
"data",
",",
"files",
")",
"headers",
".",
"update",
"(",
"new_headers",
")",
"elif",
"data",
"and",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"urllib",
".",
"urlencode",
"(",
"str_dict",
"(",
"data",
")",
")",
"# Make sure everything is encoded text",
"headers",
"=",
"str_dict",
"(",
"headers",
")",
"if",
"isinstance",
"(",
"url",
",",
"unicode",
")",
":",
"url",
"=",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"params",
":",
"# GET args (POST args are handled in encode_multipart_formdata)",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"if",
"query",
":",
"# Combine query string and `params`",
"url_params",
"=",
"urlparse",
".",
"parse_qs",
"(",
"query",
")",
"# `params` take precedence over URL query string",
"url_params",
".",
"update",
"(",
"params",
")",
"params",
"=",
"url_params",
"query",
"=",
"urllib",
".",
"urlencode",
"(",
"str_dict",
"(",
"params",
")",
",",
"doseq",
"=",
"True",
")",
"url",
"=",
"urlparse",
".",
"urlunsplit",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
")",
")",
"req",
"=",
"Request",
"(",
"url",
",",
"data",
",",
"headers",
",",
"method",
"=",
"method",
")",
"return",
"Response",
"(",
"req",
",",
"stream",
")"
] | https://github.com/oldj/SwitchHosts/blob/d0eb2321fe36780ec32c914cbc69a818fc1918d3/alfred/workflow/web.py#L482-L591 |
|
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_internal/utils/temp_dir.py | python | TempDirectory.create | (self) | Create a temporary directory and store its path in self.path | Create a temporary directory and store its path in self.path | [
"Create",
"a",
"temporary",
"directory",
"and",
"store",
"its",
"path",
"in",
"self",
".",
"path"
] | def create(self):
"""Create a temporary directory and store its path in self.path
"""
if self.path is not None:
logger.debug(
"Skipped creation of temporary directory: {}".format(self.path)
)
return
# We realpath here because some systems have their default tmpdir
# symlinked to another directory. This tends to confuse build
# scripts, so we canonicalize the path by traversing potential
# symlinks here.
self.path = os.path.realpath(
tempfile.mkdtemp(prefix="pip-{}-".format(self.kind))
)
logger.debug("Created temporary directory: {}".format(self.path)) | [
"def",
"create",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
"is",
"not",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Skipped creation of temporary directory: {}\"",
".",
"format",
"(",
"self",
".",
"path",
")",
")",
"return",
"# We realpath here because some systems have their default tmpdir",
"# symlinked to another directory. This tends to confuse build",
"# scripts, so we canonicalize the path by traversing potential",
"# symlinks here.",
"self",
".",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"\"pip-{}-\"",
".",
"format",
"(",
"self",
".",
"kind",
")",
")",
")",
"logger",
".",
"debug",
"(",
"\"Created temporary directory: {}\"",
".",
"format",
"(",
"self",
".",
"path",
")",
")"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_internal/utils/temp_dir.py#L62-L77 |
||
mdipierro/web2py-appliances | f97658293d51519e5f06e1ed503ee85f8154fcf3 | FacebookConnectExample/modules/plugin_fbconnect/facebook.py | python | PhotosProxy.upload | (self, image, aid=None, caption=None, size=(604, 1024)) | return self._client._parse_response(response, 'facebook.photos.upload') | Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=photos.upload
size -- an optional size (width, height) to resize the image to before uploading. Resizes by default
to Facebook's maximum display width of 604. | Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=photos.upload | [
"Facebook",
"API",
"call",
".",
"See",
"http",
":",
"//",
"developers",
".",
"facebook",
".",
"com",
"/",
"documentation",
".",
"php?v",
"=",
"1",
".",
"0&method",
"=",
"photos",
".",
"upload"
] | def upload(self, image, aid=None, caption=None, size=(604, 1024)):
"""Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=photos.upload
size -- an optional size (width, height) to resize the image to before uploading. Resizes by default
to Facebook's maximum display width of 604.
"""
args = {}
if aid is not None:
args['aid'] = aid
if caption is not None:
args['caption'] = caption
args = self._client._build_post_args('facebook.photos.upload', self._client._add_session_args(args))
try:
import cStringIO as StringIO
except ImportError:
import StringIO
try:
import Image
except ImportError:
data = StringIO.StringIO(open(image, 'rb').read())
else:
img = Image.open(image)
if size:
img.thumbnail(size, Image.ANTIALIAS)
data = StringIO.StringIO()
img.save(data, img.format)
content_type, body = self.__encode_multipart_formdata(list(args.iteritems()), [(image, data)])
h = httplib.HTTP('api.facebook.com')
h.putrequest('POST', '/restserver.php')
h.putheader('Content-Type', content_type)
h.putheader('Content-Length', str(len(body)))
h.putheader('MIME-Version', '1.0')
h.putheader('User-Agent', 'PyFacebook Client Library')
h.endheaders()
h.send(body)
reply = h.getreply()
if reply[0] != 200:
raise Exception('Error uploading photo: Facebook returned HTTP %s (%s)' % (reply[0], reply[1]))
response = h.file.read()
return self._client._parse_response(response, 'facebook.photos.upload') | [
"def",
"upload",
"(",
"self",
",",
"image",
",",
"aid",
"=",
"None",
",",
"caption",
"=",
"None",
",",
"size",
"=",
"(",
"604",
",",
"1024",
")",
")",
":",
"args",
"=",
"{",
"}",
"if",
"aid",
"is",
"not",
"None",
":",
"args",
"[",
"'aid'",
"]",
"=",
"aid",
"if",
"caption",
"is",
"not",
"None",
":",
"args",
"[",
"'caption'",
"]",
"=",
"caption",
"args",
"=",
"self",
".",
"_client",
".",
"_build_post_args",
"(",
"'facebook.photos.upload'",
",",
"self",
".",
"_client",
".",
"_add_session_args",
"(",
"args",
")",
")",
"try",
":",
"import",
"cStringIO",
"as",
"StringIO",
"except",
"ImportError",
":",
"import",
"StringIO",
"try",
":",
"import",
"Image",
"except",
"ImportError",
":",
"data",
"=",
"StringIO",
".",
"StringIO",
"(",
"open",
"(",
"image",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
"else",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"image",
")",
"if",
"size",
":",
"img",
".",
"thumbnail",
"(",
"size",
",",
"Image",
".",
"ANTIALIAS",
")",
"data",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"img",
".",
"save",
"(",
"data",
",",
"img",
".",
"format",
")",
"content_type",
",",
"body",
"=",
"self",
".",
"__encode_multipart_formdata",
"(",
"list",
"(",
"args",
".",
"iteritems",
"(",
")",
")",
",",
"[",
"(",
"image",
",",
"data",
")",
"]",
")",
"h",
"=",
"httplib",
".",
"HTTP",
"(",
"'api.facebook.com'",
")",
"h",
".",
"putrequest",
"(",
"'POST'",
",",
"'/restserver.php'",
")",
"h",
".",
"putheader",
"(",
"'Content-Type'",
",",
"content_type",
")",
"h",
".",
"putheader",
"(",
"'Content-Length'",
",",
"str",
"(",
"len",
"(",
"body",
")",
")",
")",
"h",
".",
"putheader",
"(",
"'MIME-Version'",
",",
"'1.0'",
")",
"h",
".",
"putheader",
"(",
"'User-Agent'",
",",
"'PyFacebook Client Library'",
")",
"h",
".",
"endheaders",
"(",
")",
"h",
".",
"send",
"(",
"body",
")",
"reply",
"=",
"h",
".",
"getreply",
"(",
")",
"if",
"reply",
"[",
"0",
"]",
"!=",
"200",
":",
"raise",
"Exception",
"(",
"'Error uploading photo: Facebook returned HTTP %s (%s)'",
"%",
"(",
"reply",
"[",
"0",
"]",
",",
"reply",
"[",
"1",
"]",
")",
")",
"response",
"=",
"h",
".",
"file",
".",
"read",
"(",
")",
"return",
"self",
".",
"_client",
".",
"_parse_response",
"(",
"response",
",",
"'facebook.photos.upload'",
")"
] | https://github.com/mdipierro/web2py-appliances/blob/f97658293d51519e5f06e1ed503ee85f8154fcf3/FacebookConnectExample/modules/plugin_fbconnect/facebook.py#L471-L520 |
|
aosabook/500lines | fba689d101eb5600f5c8f4d7fd79912498e950e2 | contingent/code/contingent/graphlib.py | python | Graph.immediate_consequences_of | (self, task) | return self.sorted(self._consequences_of[task]) | Return the tasks that use `task` as an input. | Return the tasks that use `task` as an input. | [
"Return",
"the",
"tasks",
"that",
"use",
"task",
"as",
"an",
"input",
"."
] | def immediate_consequences_of(self, task):
"""Return the tasks that use `task` as an input."""
return self.sorted(self._consequences_of[task]) | [
"def",
"immediate_consequences_of",
"(",
"self",
",",
"task",
")",
":",
"return",
"self",
".",
"sorted",
"(",
"self",
".",
"_consequences_of",
"[",
"task",
"]",
")"
] | https://github.com/aosabook/500lines/blob/fba689d101eb5600f5c8f4d7fd79912498e950e2/contingent/code/contingent/graphlib.py#L70-L72 |
|
SteeltoeOSS/Samples | a27be0f2fd2af0e263f32aceb131df21fb54c82b | steps/browser_steps.py | python | step_impl | (context, data, url) | :type context: behave.runner.Context
:type data: str
:type url: str | :type context: behave.runner.Context
:type data: str
:type url: str | [
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context",
":",
"type",
"data",
":",
"str",
":",
"type",
"url",
":",
"str"
] | def step_impl(context, data, url):
"""
:type context: behave.runner.Context
:type data: str
:type url: str
"""
url = dns.resolve_url(context, url)
fields = data.split('=')
assert len(fields) == 2, 'Invalid data format: {}'.format(data)
payload = {fields[0]: fields[1]}
context.log.info('posting url {} {}'.format(url, payload))
context.browser = mechanicalsoup.StatefulBrowser()
resp = context.browser.post(url, data=payload)
context.log.info('POST {} [{}]'.format(url, resp.status_code)) | [
"def",
"step_impl",
"(",
"context",
",",
"data",
",",
"url",
")",
":",
"url",
"=",
"dns",
".",
"resolve_url",
"(",
"context",
",",
"url",
")",
"fields",
"=",
"data",
".",
"split",
"(",
"'='",
")",
"assert",
"len",
"(",
"fields",
")",
"==",
"2",
",",
"'Invalid data format: {}'",
".",
"format",
"(",
"data",
")",
"payload",
"=",
"{",
"fields",
"[",
"0",
"]",
":",
"fields",
"[",
"1",
"]",
"}",
"context",
".",
"log",
".",
"info",
"(",
"'posting url {} {}'",
".",
"format",
"(",
"url",
",",
"payload",
")",
")",
"context",
".",
"browser",
"=",
"mechanicalsoup",
".",
"StatefulBrowser",
"(",
")",
"resp",
"=",
"context",
".",
"browser",
".",
"post",
"(",
"url",
",",
"data",
"=",
"payload",
")",
"context",
".",
"log",
".",
"info",
"(",
"'POST {} [{}]'",
".",
"format",
"(",
"url",
",",
"resp",
".",
"status_code",
")",
")"
] | https://github.com/SteeltoeOSS/Samples/blob/a27be0f2fd2af0e263f32aceb131df21fb54c82b/steps/browser_steps.py#L34-L47 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/xml/dom/expatbuilder.py | python | Namespaces.install | (self, parser) | Insert the namespace-handlers onto the parser. | Insert the namespace-handlers onto the parser. | [
"Insert",
"the",
"namespace",
"-",
"handlers",
"onto",
"the",
"parser",
"."
] | def install(self, parser):
"""Insert the namespace-handlers onto the parser."""
ExpatBuilder.install(self, parser)
if self._options.namespace_declarations:
parser.StartNamespaceDeclHandler = (
self.start_namespace_decl_handler) | [
"def",
"install",
"(",
"self",
",",
"parser",
")",
":",
"ExpatBuilder",
".",
"install",
"(",
"self",
",",
"parser",
")",
"if",
"self",
".",
"_options",
".",
"namespace_declarations",
":",
"parser",
".",
"StartNamespaceDeclHandler",
"=",
"(",
"self",
".",
"start_namespace_decl_handler",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/xml/dom/expatbuilder.py#L732-L737 |
||
opencoweb/coweb | 7b3a87ee9eda735a859447d404ee16edde1c5671 | servers/python/coweb/service/manager/object.py | python | ObjectServiceManager.get_manager_id | (self) | return 'object' | Manager id is object matching wrapper module name. | Manager id is object matching wrapper module name. | [
"Manager",
"id",
"is",
"object",
"matching",
"wrapper",
"module",
"name",
"."
] | def get_manager_id(self):
'''Manager id is object matching wrapper module name.'''
return 'object' | [
"def",
"get_manager_id",
"(",
"self",
")",
":",
"return",
"'object'"
] | https://github.com/opencoweb/coweb/blob/7b3a87ee9eda735a859447d404ee16edde1c5671/servers/python/coweb/service/manager/object.py#L10-L12 |
|
ctripcorp/tars | d7954fccaf1a17901f22d844d84c5663a3d79c11 | tars/api/views/deployment.py | python | DeploymentViewSet.reset | (self, request, pk=None, format=None) | return self.retrieve(request) | temp for develop | temp for develop | [
"temp",
"for",
"develop"
] | def reset(self, request, pk=None, format=None):
"""
temp for develop
"""
deployment = self.get_object()
deployment.reset()
return self.retrieve(request) | [
"def",
"reset",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"deployment",
"=",
"self",
".",
"get_object",
"(",
")",
"deployment",
".",
"reset",
"(",
")",
"return",
"self",
".",
"retrieve",
"(",
"request",
")"
] | https://github.com/ctripcorp/tars/blob/d7954fccaf1a17901f22d844d84c5663a3d79c11/tars/api/views/deployment.py#L363-L369 |
|
xtk/X | 04c1aa856664a8517d23aefd94c470d47130aead | lib/pypng-0.0.9/code/png.py | python | Reader.validate_signature | (self) | If signature (header) has not been read then read and
validate it; otherwise do nothing. | If signature (header) has not been read then read and
validate it; otherwise do nothing. | [
"If",
"signature",
"(",
"header",
")",
"has",
"not",
"been",
"read",
"then",
"read",
"and",
"validate",
"it",
";",
"otherwise",
"do",
"nothing",
"."
] | def validate_signature(self):
"""If signature (header) has not been read then read and
validate it; otherwise do nothing.
"""
if self.signature:
return
self.signature = self.file.read(8)
if self.signature != _signature:
raise FormatError("PNG file has invalid signature.") | [
"def",
"validate_signature",
"(",
"self",
")",
":",
"if",
"self",
".",
"signature",
":",
"return",
"self",
".",
"signature",
"=",
"self",
".",
"file",
".",
"read",
"(",
"8",
")",
"if",
"self",
".",
"signature",
"!=",
"_signature",
":",
"raise",
"FormatError",
"(",
"\"PNG file has invalid signature.\"",
")"
] | https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/pypng-0.0.9/code/png.py#L1428-L1437 |
||
mceSystems/node-jsc | 90634f3064fab8e89a85b3942f0cc5054acc86fa | deps/v8/gypfiles/vs_toolchain.py | python | Update | (force=False) | return 0 | Requests an update of the toolchain to the specific hashes we have at
this revision. The update outputs a .json of the various configuration
information required to pass to gyp which we use in |GetToolchainDir()|. | Requests an update of the toolchain to the specific hashes we have at
this revision. The update outputs a .json of the various configuration
information required to pass to gyp which we use in |GetToolchainDir()|. | [
"Requests",
"an",
"update",
"of",
"the",
"toolchain",
"to",
"the",
"specific",
"hashes",
"we",
"have",
"at",
"this",
"revision",
".",
"The",
"update",
"outputs",
"a",
".",
"json",
"of",
"the",
"various",
"configuration",
"information",
"required",
"to",
"pass",
"to",
"gyp",
"which",
"we",
"use",
"in",
"|GetToolchainDir",
"()",
"|",
"."
] | def Update(force=False):
"""Requests an update of the toolchain to the specific hashes we have at
this revision. The update outputs a .json of the various configuration
information required to pass to gyp which we use in |GetToolchainDir()|.
"""
if force != False and force != '--force':
print >>sys.stderr, 'Unknown parameter "%s"' % force
return 1
if force == '--force' or os.path.exists(json_data_file):
force = True
depot_tools_win_toolchain = \
bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1')))
if ((sys.platform in ('win32', 'cygwin') or force) and
depot_tools_win_toolchain):
import find_depot_tools
depot_tools_path = find_depot_tools.add_depot_tools_to_path()
# Necessary so that get_toolchain_if_necessary.py will put the VS toolkit
# in the correct directory.
os.environ['GYP_MSVS_VERSION'] = GetVisualStudioVersion()
get_toolchain_args = [
sys.executable,
os.path.join(depot_tools_path,
'win_toolchain',
'get_toolchain_if_necessary.py'),
'--output-json', json_data_file,
] + _GetDesiredVsToolchainHashes()
if force:
get_toolchain_args.append('--force')
subprocess.check_call(get_toolchain_args)
return 0 | [
"def",
"Update",
"(",
"force",
"=",
"False",
")",
":",
"if",
"force",
"!=",
"False",
"and",
"force",
"!=",
"'--force'",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"'Unknown parameter \"%s\"'",
"%",
"force",
"return",
"1",
"if",
"force",
"==",
"'--force'",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"json_data_file",
")",
":",
"force",
"=",
"True",
"depot_tools_win_toolchain",
"=",
"bool",
"(",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'DEPOT_TOOLS_WIN_TOOLCHAIN'",
",",
"'1'",
")",
")",
")",
"if",
"(",
"(",
"sys",
".",
"platform",
"in",
"(",
"'win32'",
",",
"'cygwin'",
")",
"or",
"force",
")",
"and",
"depot_tools_win_toolchain",
")",
":",
"import",
"find_depot_tools",
"depot_tools_path",
"=",
"find_depot_tools",
".",
"add_depot_tools_to_path",
"(",
")",
"# Necessary so that get_toolchain_if_necessary.py will put the VS toolkit",
"# in the correct directory.",
"os",
".",
"environ",
"[",
"'GYP_MSVS_VERSION'",
"]",
"=",
"GetVisualStudioVersion",
"(",
")",
"get_toolchain_args",
"=",
"[",
"sys",
".",
"executable",
",",
"os",
".",
"path",
".",
"join",
"(",
"depot_tools_path",
",",
"'win_toolchain'",
",",
"'get_toolchain_if_necessary.py'",
")",
",",
"'--output-json'",
",",
"json_data_file",
",",
"]",
"+",
"_GetDesiredVsToolchainHashes",
"(",
")",
"if",
"force",
":",
"get_toolchain_args",
".",
"append",
"(",
"'--force'",
")",
"subprocess",
".",
"check_call",
"(",
"get_toolchain_args",
")",
"return",
"0"
] | https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/v8/gypfiles/vs_toolchain.py#L294-L325 |
|
nodejs/http2 | 734ad72e3939e62bcff0f686b8ec426b8aaa22e3 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py | python | OrderedDict.values | (self) | return [self[key] for key in self] | od.values() -> list of values in od | od.values() -> list of values in od | [
"od",
".",
"values",
"()",
"-",
">",
"list",
"of",
"values",
"in",
"od"
] | def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self] | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"[",
"self",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
"]"
] | https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L147-L149 |
|
agoravoting/agora-ciudadana | a7701035ea77d7a91baa9b5c2d0c05d91d1b4262 | agora_site/agora_core/resources/agora.py | python | AgoraResource.join_action | (self, request, agora, **kwargs) | return self.create_response(request, dict(status="success")) | Action that an user can execute to join an agora if it has permissions | Action that an user can execute to join an agora if it has permissions | [
"Action",
"that",
"an",
"user",
"can",
"execute",
"to",
"join",
"an",
"agora",
"if",
"it",
"has",
"permissions"
] | def join_action(self, request, agora, **kwargs):
'''
Action that an user can execute to join an agora if it has permissions
'''
request.user.get_profile().add_to_agora(agora_id=agora.id, request=request)
return self.create_response(request, dict(status="success")) | [
"def",
"join_action",
"(",
"self",
",",
"request",
",",
"agora",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
".",
"user",
".",
"get_profile",
"(",
")",
".",
"add_to_agora",
"(",
"agora_id",
"=",
"agora",
".",
"id",
",",
"request",
"=",
"request",
")",
"return",
"self",
".",
"create_response",
"(",
"request",
",",
"dict",
"(",
"status",
"=",
"\"success\"",
")",
")"
] | https://github.com/agoravoting/agora-ciudadana/blob/a7701035ea77d7a91baa9b5c2d0c05d91d1b4262/agora_site/agora_core/resources/agora.py#L622-L628 |
|
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | odoo/tools/translate.py | python | trans_load_data | (cr, fileobj, fileformat, lang,
verbose=True, create_empty_translation=False, overwrite=False) | Populates the ir_translation table.
:param fileobj: buffer open to a translation file
:param fileformat: format of the `fielobj` file, one of 'po' or 'csv'
:param lang: language code of the translations contained in `fileobj`
language must be present and activated in the database
:param verbose: increase log output
:param create_empty_translation: create an ir.translation record, even if no value
is provided in the translation entry
:param overwrite: if an ir.translation already exists for a term, replace it with
the one in `fileobj` | Populates the ir_translation table. | [
"Populates",
"the",
"ir_translation",
"table",
"."
] | def trans_load_data(cr, fileobj, fileformat, lang,
verbose=True, create_empty_translation=False, overwrite=False):
"""Populates the ir_translation table.
:param fileobj: buffer open to a translation file
:param fileformat: format of the `fielobj` file, one of 'po' or 'csv'
:param lang: language code of the translations contained in `fileobj`
language must be present and activated in the database
:param verbose: increase log output
:param create_empty_translation: create an ir.translation record, even if no value
is provided in the translation entry
:param overwrite: if an ir.translation already exists for a term, replace it with
the one in `fileobj`
"""
if verbose:
_logger.info('loading translation file for language %s', lang)
env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
try:
if not env['res.lang']._lang_get(lang):
_logger.error("Couldn't read translation for lang '%s', language not found", lang)
return None
# now, the serious things: we read the language file
fileobj.seek(0)
reader = TranslationFileReader(fileobj, fileformat=fileformat)
# read the rest of the file with a cursor-like object for fast inserting translations"
Translation = env['ir.translation']
irt_cursor = Translation._get_import_cursor(overwrite)
def process_row(row):
"""Process a single PO (or POT) entry."""
# dictionary which holds values for this line of the csv file
# {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,
# 'src': ..., 'value': ..., 'module':...}
dic = dict.fromkeys(('type', 'name', 'res_id', 'src', 'value',
'comments', 'imd_model', 'imd_name', 'module'))
dic['lang'] = lang
dic.update(row)
# do not import empty values
if not create_empty_translation and not dic['value']:
return
irt_cursor.push(dic)
# First process the entries from the PO file (doing so also fills/removes
# the entries from the POT file).
for row in reader:
process_row(row)
irt_cursor.finish()
Translation.clear_caches()
if verbose:
_logger.info("translation file loaded successfully")
except IOError:
iso_lang = get_iso_codes(lang)
filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat)
_logger.exception("couldn't read translation file %s", filename) | [
"def",
"trans_load_data",
"(",
"cr",
",",
"fileobj",
",",
"fileformat",
",",
"lang",
",",
"verbose",
"=",
"True",
",",
"create_empty_translation",
"=",
"False",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"_logger",
".",
"info",
"(",
"'loading translation file for language %s'",
",",
"lang",
")",
"env",
"=",
"odoo",
".",
"api",
".",
"Environment",
"(",
"cr",
",",
"odoo",
".",
"SUPERUSER_ID",
",",
"{",
"}",
")",
"try",
":",
"if",
"not",
"env",
"[",
"'res.lang'",
"]",
".",
"_lang_get",
"(",
"lang",
")",
":",
"_logger",
".",
"error",
"(",
"\"Couldn't read translation for lang '%s', language not found\"",
",",
"lang",
")",
"return",
"None",
"# now, the serious things: we read the language file",
"fileobj",
".",
"seek",
"(",
"0",
")",
"reader",
"=",
"TranslationFileReader",
"(",
"fileobj",
",",
"fileformat",
"=",
"fileformat",
")",
"# read the rest of the file with a cursor-like object for fast inserting translations\"",
"Translation",
"=",
"env",
"[",
"'ir.translation'",
"]",
"irt_cursor",
"=",
"Translation",
".",
"_get_import_cursor",
"(",
"overwrite",
")",
"def",
"process_row",
"(",
"row",
")",
":",
"\"\"\"Process a single PO (or POT) entry.\"\"\"",
"# dictionary which holds values for this line of the csv file",
"# {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,",
"# 'src': ..., 'value': ..., 'module':...}",
"dic",
"=",
"dict",
".",
"fromkeys",
"(",
"(",
"'type'",
",",
"'name'",
",",
"'res_id'",
",",
"'src'",
",",
"'value'",
",",
"'comments'",
",",
"'imd_model'",
",",
"'imd_name'",
",",
"'module'",
")",
")",
"dic",
"[",
"'lang'",
"]",
"=",
"lang",
"dic",
".",
"update",
"(",
"row",
")",
"# do not import empty values",
"if",
"not",
"create_empty_translation",
"and",
"not",
"dic",
"[",
"'value'",
"]",
":",
"return",
"irt_cursor",
".",
"push",
"(",
"dic",
")",
"# First process the entries from the PO file (doing so also fills/removes",
"# the entries from the POT file).",
"for",
"row",
"in",
"reader",
":",
"process_row",
"(",
"row",
")",
"irt_cursor",
".",
"finish",
"(",
")",
"Translation",
".",
"clear_caches",
"(",
")",
"if",
"verbose",
":",
"_logger",
".",
"info",
"(",
"\"translation file loaded successfully\"",
")",
"except",
"IOError",
":",
"iso_lang",
"=",
"get_iso_codes",
"(",
"lang",
")",
"filename",
"=",
"'[lang: %s][format: %s]'",
"%",
"(",
"iso_lang",
"or",
"'new'",
",",
"fileformat",
")",
"_logger",
".",
"exception",
"(",
"\"couldn't read translation file %s\"",
",",
"filename",
")"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/odoo/tools/translate.py#L1169-L1230 |
||
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | deps/chakrashim/third_party/jinja2/jinja2/utils.py | python | LRUCache.__setitem__ | (self, key, value) | Sets the value for an item. Moves the item up so that it
has the highest priority then. | Sets the value for an item. Moves the item up so that it
has the highest priority then. | [
"Sets",
"the",
"value",
"for",
"an",
"item",
".",
"Moves",
"the",
"item",
"up",
"so",
"that",
"it",
"has",
"the",
"highest",
"priority",
"then",
"."
] | def __setitem__(self, key, value):
"""Sets the value for an item. Moves the item up so that it
has the highest priority then.
"""
self._wlock.acquire()
try:
if key in self._mapping:
self._remove(key)
elif len(self._mapping) == self.capacity:
del self._mapping[self._popleft()]
self._append(key)
self._mapping[key] = value
finally:
self._wlock.release() | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_wlock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"key",
"in",
"self",
".",
"_mapping",
":",
"self",
".",
"_remove",
"(",
"key",
")",
"elif",
"len",
"(",
"self",
".",
"_mapping",
")",
"==",
"self",
".",
"capacity",
":",
"del",
"self",
".",
"_mapping",
"[",
"self",
".",
"_popleft",
"(",
")",
"]",
"self",
".",
"_append",
"(",
"key",
")",
"self",
".",
"_mapping",
"[",
"key",
"]",
"=",
"value",
"finally",
":",
"self",
".",
"_wlock",
".",
"release",
"(",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/chakrashim/third_party/jinja2/jinja2/utils.py#L413-L426 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.ComputeOutput | (self, spec) | return os.path.join(path, self.ComputeOutputBasename(spec)) | Return the 'output' (full output path) of a gyp spec.
E.g., the loadable module 'foobar' in directory 'baz' will produce
'$(obj)/baz/libfoobar.so' | Return the 'output' (full output path) of a gyp spec. | [
"Return",
"the",
"output",
"(",
"full",
"output",
"path",
")",
"of",
"a",
"gyp",
"spec",
"."
] | def ComputeOutput(self, spec):
"""Return the 'output' (full output path) of a gyp spec.
E.g., the loadable module 'foobar' in directory 'baz' will produce
'$(obj)/baz/libfoobar.so'
"""
if self.type == 'executable':
# We install host executables into shared_intermediate_dir so they can be
# run by gyp rules that refer to PRODUCT_DIR.
path = '$(gyp_shared_intermediate_dir)'
elif self.type == 'shared_library':
if self.toolset == 'host':
path = '$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)'
else:
path = '$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)'
else:
# Other targets just get built into their intermediate dir.
if self.toolset == 'host':
path = ('$(call intermediates-dir-for,%s,%s,true,,'
'$(GYP_HOST_VAR_PREFIX))' % (self.android_class,
self.android_module))
else:
path = ('$(call intermediates-dir-for,%s,%s,,,$(GYP_VAR_PREFIX))'
% (self.android_class, self.android_module))
assert spec.get('product_dir') is None # TODO: not supported?
return os.path.join(path, self.ComputeOutputBasename(spec)) | [
"def",
"ComputeOutput",
"(",
"self",
",",
"spec",
")",
":",
"if",
"self",
".",
"type",
"==",
"'executable'",
":",
"# We install host executables into shared_intermediate_dir so they can be",
"# run by gyp rules that refer to PRODUCT_DIR.",
"path",
"=",
"'$(gyp_shared_intermediate_dir)'",
"elif",
"self",
".",
"type",
"==",
"'shared_library'",
":",
"if",
"self",
".",
"toolset",
"==",
"'host'",
":",
"path",
"=",
"'$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)'",
"else",
":",
"path",
"=",
"'$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)'",
"else",
":",
"# Other targets just get built into their intermediate dir.",
"if",
"self",
".",
"toolset",
"==",
"'host'",
":",
"path",
"=",
"(",
"'$(call intermediates-dir-for,%s,%s,true,,'",
"'$(GYP_HOST_VAR_PREFIX))'",
"%",
"(",
"self",
".",
"android_class",
",",
"self",
".",
"android_module",
")",
")",
"else",
":",
"path",
"=",
"(",
"'$(call intermediates-dir-for,%s,%s,,,$(GYP_VAR_PREFIX))'",
"%",
"(",
"self",
".",
"android_class",
",",
"self",
".",
"android_module",
")",
")",
"assert",
"spec",
".",
"get",
"(",
"'product_dir'",
")",
"is",
"None",
"# TODO: not supported?",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"self",
".",
"ComputeOutputBasename",
"(",
"spec",
")",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L662-L688 |
|
jxcore/jxcore | b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetLdflags | (self, config, gyp_to_build_path, expand_special,
manifest_base_name, output_name, is_executable, build_dir) | return ldflags, intermediate_manifest, manifest_files | Returns the flags that need to be added to link commands, and the
manifest files. | Returns the flags that need to be added to link commands, and the
manifest files. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
"link",
"commands",
"and",
"the",
"manifest",
"files",
"."
] | def GetLdflags(self, config, gyp_to_build_path, expand_special,
manifest_base_name, output_name, is_executable, build_dir):
"""Returns the flags that need to be added to link commands, and the
manifest files."""
config = self._TargetConfig(config)
ldflags = []
ld = self._GetWrapper(self, self.msvs_settings[config],
'VCLinkerTool', append=ldflags)
self._GetDefFileAsLdflags(ldflags, gyp_to_build_path)
ld('GenerateDebugInformation', map={'true': '/DEBUG'})
ld('TargetMachine', map={'1': 'X86', '17': 'X64', '3': 'ARM'},
prefix='/MACHINE:')
ldflags.extend(self._GetAdditionalLibraryDirectories(
'VCLinkerTool', config, gyp_to_build_path))
ld('DelayLoadDLLs', prefix='/DELAYLOAD:')
ld('TreatLinkerWarningAsErrors', prefix='/WX',
map={'true': '', 'false': ':NO'})
out = self.GetOutputName(config, expand_special)
if out:
ldflags.append('/OUT:' + out)
pdb = self.GetPDBName(config, expand_special, output_name + '.pdb')
if pdb:
ldflags.append('/PDB:' + pdb)
pgd = self.GetPGDName(config, expand_special)
if pgd:
ldflags.append('/PGD:' + pgd)
map_file = self.GetMapFileName(config, expand_special)
ld('GenerateMapFile', map={'true': '/MAP:' + map_file if map_file
else '/MAP'})
ld('MapExports', map={'true': '/MAPINFO:EXPORTS'})
ld('AdditionalOptions', prefix='')
minimum_required_version = self._Setting(
('VCLinkerTool', 'MinimumRequiredVersion'), config, default='')
if minimum_required_version:
minimum_required_version = ',' + minimum_required_version
ld('SubSystem',
map={'1': 'CONSOLE%s' % minimum_required_version,
'2': 'WINDOWS%s' % minimum_required_version},
prefix='/SUBSYSTEM:')
ld('TerminalServerAware', map={'1': ':NO', '2': ''}, prefix='/TSAWARE')
ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL')
ld('BaseAddress', prefix='/BASE:')
ld('FixedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/FIXED')
ld('RandomizedBaseAddress',
map={'1': ':NO', '2': ''}, prefix='/DYNAMICBASE')
ld('DataExecutionPrevention',
map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT')
ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:')
ld('ForceSymbolReferences', prefix='/INCLUDE:')
ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:')
ld('LinkTimeCodeGeneration',
map={'1': '', '2': ':PGINSTRUMENT', '3': ':PGOPTIMIZE',
'4': ':PGUPDATE'},
prefix='/LTCG')
ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:')
ld('ResourceOnlyDLL', map={'true': '/NOENTRY'})
ld('EntryPointSymbol', prefix='/ENTRY:')
ld('Profile', map={'true': '/PROFILE'})
ld('LargeAddressAware',
map={'1': ':NO', '2': ''}, prefix='/LARGEADDRESSAWARE')
# TODO(scottmg): This should sort of be somewhere else (not really a flag).
ld('AdditionalDependencies', prefix='')
if self.GetArch(config) == 'x86':
safeseh_default = 'true'
else:
safeseh_default = None
ld('ImageHasSafeExceptionHandlers',
map={'false': ':NO', 'true': ''}, prefix='/SAFESEH',
default=safeseh_default)
# If the base address is not specifically controlled, DYNAMICBASE should
# be on by default.
base_flags = filter(lambda x: 'DYNAMICBASE' in x or x == '/FIXED',
ldflags)
if not base_flags:
ldflags.append('/DYNAMICBASE')
# If the NXCOMPAT flag has not been specified, default to on. Despite the
# documentation that says this only defaults to on when the subsystem is
# Vista or greater (which applies to the linker), the IDE defaults it on
# unless it's explicitly off.
if not filter(lambda x: 'NXCOMPAT' in x, ldflags):
ldflags.append('/NXCOMPAT')
have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags)
manifest_flags, intermediate_manifest, manifest_files = \
self._GetLdManifestFlags(config, manifest_base_name, gyp_to_build_path,
is_executable and not have_def_file, build_dir)
ldflags.extend(manifest_flags)
return ldflags, intermediate_manifest, manifest_files | [
"def",
"GetLdflags",
"(",
"self",
",",
"config",
",",
"gyp_to_build_path",
",",
"expand_special",
",",
"manifest_base_name",
",",
"output_name",
",",
"is_executable",
",",
"build_dir",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"ldflags",
"=",
"[",
"]",
"ld",
"=",
"self",
".",
"_GetWrapper",
"(",
"self",
",",
"self",
".",
"msvs_settings",
"[",
"config",
"]",
",",
"'VCLinkerTool'",
",",
"append",
"=",
"ldflags",
")",
"self",
".",
"_GetDefFileAsLdflags",
"(",
"ldflags",
",",
"gyp_to_build_path",
")",
"ld",
"(",
"'GenerateDebugInformation'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/DEBUG'",
"}",
")",
"ld",
"(",
"'TargetMachine'",
",",
"map",
"=",
"{",
"'1'",
":",
"'X86'",
",",
"'17'",
":",
"'X64'",
",",
"'3'",
":",
"'ARM'",
"}",
",",
"prefix",
"=",
"'/MACHINE:'",
")",
"ldflags",
".",
"extend",
"(",
"self",
".",
"_GetAdditionalLibraryDirectories",
"(",
"'VCLinkerTool'",
",",
"config",
",",
"gyp_to_build_path",
")",
")",
"ld",
"(",
"'DelayLoadDLLs'",
",",
"prefix",
"=",
"'/DELAYLOAD:'",
")",
"ld",
"(",
"'TreatLinkerWarningAsErrors'",
",",
"prefix",
"=",
"'/WX'",
",",
"map",
"=",
"{",
"'true'",
":",
"''",
",",
"'false'",
":",
"':NO'",
"}",
")",
"out",
"=",
"self",
".",
"GetOutputName",
"(",
"config",
",",
"expand_special",
")",
"if",
"out",
":",
"ldflags",
".",
"append",
"(",
"'/OUT:'",
"+",
"out",
")",
"pdb",
"=",
"self",
".",
"GetPDBName",
"(",
"config",
",",
"expand_special",
",",
"output_name",
"+",
"'.pdb'",
")",
"if",
"pdb",
":",
"ldflags",
".",
"append",
"(",
"'/PDB:'",
"+",
"pdb",
")",
"pgd",
"=",
"self",
".",
"GetPGDName",
"(",
"config",
",",
"expand_special",
")",
"if",
"pgd",
":",
"ldflags",
".",
"append",
"(",
"'/PGD:'",
"+",
"pgd",
")",
"map_file",
"=",
"self",
".",
"GetMapFileName",
"(",
"config",
",",
"expand_special",
")",
"ld",
"(",
"'GenerateMapFile'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/MAP:'",
"+",
"map_file",
"if",
"map_file",
"else",
"'/MAP'",
"}",
")",
"ld",
"(",
"'MapExports'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/MAPINFO:EXPORTS'",
"}",
")",
"ld",
"(",
"'AdditionalOptions'",
",",
"prefix",
"=",
"''",
")",
"minimum_required_version",
"=",
"self",
".",
"_Setting",
"(",
"(",
"'VCLinkerTool'",
",",
"'MinimumRequiredVersion'",
")",
",",
"config",
",",
"default",
"=",
"''",
")",
"if",
"minimum_required_version",
":",
"minimum_required_version",
"=",
"','",
"+",
"minimum_required_version",
"ld",
"(",
"'SubSystem'",
",",
"map",
"=",
"{",
"'1'",
":",
"'CONSOLE%s'",
"%",
"minimum_required_version",
",",
"'2'",
":",
"'WINDOWS%s'",
"%",
"minimum_required_version",
"}",
",",
"prefix",
"=",
"'/SUBSYSTEM:'",
")",
"ld",
"(",
"'TerminalServerAware'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/TSAWARE'",
")",
"ld",
"(",
"'LinkIncremental'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/INCREMENTAL'",
")",
"ld",
"(",
"'BaseAddress'",
",",
"prefix",
"=",
"'/BASE:'",
")",
"ld",
"(",
"'FixedBaseAddress'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/FIXED'",
")",
"ld",
"(",
"'RandomizedBaseAddress'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/DYNAMICBASE'",
")",
"ld",
"(",
"'DataExecutionPrevention'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/NXCOMPAT'",
")",
"ld",
"(",
"'OptimizeReferences'",
",",
"map",
"=",
"{",
"'1'",
":",
"'NOREF'",
",",
"'2'",
":",
"'REF'",
"}",
",",
"prefix",
"=",
"'/OPT:'",
")",
"ld",
"(",
"'ForceSymbolReferences'",
",",
"prefix",
"=",
"'/INCLUDE:'",
")",
"ld",
"(",
"'EnableCOMDATFolding'",
",",
"map",
"=",
"{",
"'1'",
":",
"'NOICF'",
",",
"'2'",
":",
"'ICF'",
"}",
",",
"prefix",
"=",
"'/OPT:'",
")",
"ld",
"(",
"'LinkTimeCodeGeneration'",
",",
"map",
"=",
"{",
"'1'",
":",
"''",
",",
"'2'",
":",
"':PGINSTRUMENT'",
",",
"'3'",
":",
"':PGOPTIMIZE'",
",",
"'4'",
":",
"':PGUPDATE'",
"}",
",",
"prefix",
"=",
"'/LTCG'",
")",
"ld",
"(",
"'IgnoreDefaultLibraryNames'",
",",
"prefix",
"=",
"'/NODEFAULTLIB:'",
")",
"ld",
"(",
"'ResourceOnlyDLL'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/NOENTRY'",
"}",
")",
"ld",
"(",
"'EntryPointSymbol'",
",",
"prefix",
"=",
"'/ENTRY:'",
")",
"ld",
"(",
"'Profile'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/PROFILE'",
"}",
")",
"ld",
"(",
"'LargeAddressAware'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/LARGEADDRESSAWARE'",
")",
"# TODO(scottmg): This should sort of be somewhere else (not really a flag).",
"ld",
"(",
"'AdditionalDependencies'",
",",
"prefix",
"=",
"''",
")",
"if",
"self",
".",
"GetArch",
"(",
"config",
")",
"==",
"'x86'",
":",
"safeseh_default",
"=",
"'true'",
"else",
":",
"safeseh_default",
"=",
"None",
"ld",
"(",
"'ImageHasSafeExceptionHandlers'",
",",
"map",
"=",
"{",
"'false'",
":",
"':NO'",
",",
"'true'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/SAFESEH'",
",",
"default",
"=",
"safeseh_default",
")",
"# If the base address is not specifically controlled, DYNAMICBASE should",
"# be on by default.",
"base_flags",
"=",
"filter",
"(",
"lambda",
"x",
":",
"'DYNAMICBASE'",
"in",
"x",
"or",
"x",
"==",
"'/FIXED'",
",",
"ldflags",
")",
"if",
"not",
"base_flags",
":",
"ldflags",
".",
"append",
"(",
"'/DYNAMICBASE'",
")",
"# If the NXCOMPAT flag has not been specified, default to on. Despite the",
"# documentation that says this only defaults to on when the subsystem is",
"# Vista or greater (which applies to the linker), the IDE defaults it on",
"# unless it's explicitly off.",
"if",
"not",
"filter",
"(",
"lambda",
"x",
":",
"'NXCOMPAT'",
"in",
"x",
",",
"ldflags",
")",
":",
"ldflags",
".",
"append",
"(",
"'/NXCOMPAT'",
")",
"have_def_file",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"startswith",
"(",
"'/DEF:'",
")",
",",
"ldflags",
")",
"manifest_flags",
",",
"intermediate_manifest",
",",
"manifest_files",
"=",
"self",
".",
"_GetLdManifestFlags",
"(",
"config",
",",
"manifest_base_name",
",",
"gyp_to_build_path",
",",
"is_executable",
"and",
"not",
"have_def_file",
",",
"build_dir",
")",
"ldflags",
".",
"extend",
"(",
"manifest_flags",
")",
"return",
"ldflags",
",",
"intermediate_manifest",
",",
"manifest_files"
] | https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L555-L647 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydev_imps/_pydev_SocketServer.py | python | TCPServer.fileno | (self) | return self.socket.fileno() | Return socket file number.
Interface required by select(). | Return socket file number. | [
"Return",
"socket",
"file",
"number",
"."
] | def fileno(self):
"""Return socket file number.
Interface required by select().
"""
return self.socket.fileno() | [
"def",
"fileno",
"(",
"self",
")",
":",
"return",
"self",
".",
"socket",
".",
"fileno",
"(",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydev_imps/_pydev_SocketServer.py#L438-L444 |
|
datahuborg/datahub | f066b472c2b66cc3b868bbe433aed2d4557aea32 | src/examples/python/gen_py/datahub/DataHub.py | python | Iface.create_repo | (self, con, repo_name) | Parameters:
- con
- repo_name | Parameters:
- con
- repo_name | [
"Parameters",
":",
"-",
"con",
"-",
"repo_name"
] | def create_repo(self, con, repo_name):
"""
Parameters:
- con
- repo_name
"""
pass | [
"def",
"create_repo",
"(",
"self",
",",
"con",
",",
"repo_name",
")",
":",
"pass"
] | https://github.com/datahuborg/datahub/blob/f066b472c2b66cc3b868bbe433aed2d4557aea32/src/examples/python/gen_py/datahub/DataHub.py#L31-L37 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/unclosured/lib/python2.7/urllib.py | python | ftperrors | () | return _ftperrors | Return the set of errors raised by the FTP class. | Return the set of errors raised by the FTP class. | [
"Return",
"the",
"set",
"of",
"errors",
"raised",
"by",
"the",
"FTP",
"class",
"."
] | def ftperrors():
"""Return the set of errors raised by the FTP class."""
global _ftperrors
if _ftperrors is None:
import ftplib
_ftperrors = ftplib.all_errors
return _ftperrors | [
"def",
"ftperrors",
"(",
")",
":",
"global",
"_ftperrors",
"if",
"_ftperrors",
"is",
"None",
":",
"import",
"ftplib",
"_ftperrors",
"=",
"ftplib",
".",
"all_errors",
"return",
"_ftperrors"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/urllib.py#L824-L830 |
|
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py | python | _Type.ValidateMSVS | (self, value) | Verifies that the value is legal for MSVS.
Args:
value: the value to check for this type.
Raises:
ValueError if value is not valid for MSVS. | Verifies that the value is legal for MSVS. | [
"Verifies",
"that",
"the",
"value",
"is",
"legal",
"for",
"MSVS",
"."
] | def ValidateMSVS(self, value):
"""Verifies that the value is legal for MSVS.
Args:
value: the value to check for this type.
Raises:
ValueError if value is not valid for MSVS.
""" | [
"def",
"ValidateMSVS",
"(",
"self",
",",
"value",
")",
":"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L70-L78 |
||
xtk/X | 04c1aa856664a8517d23aefd94c470d47130aead | lib/selenium/selenium/webdriver/common/alert.py | python | Alert.accept | (self) | Accepts the alert available | Accepts the alert available | [
"Accepts",
"the",
"alert",
"available"
] | def accept(self):
""" Accepts the alert available """
self.driver.execute(Command.ACCEPT_ALERT) | [
"def",
"accept",
"(",
"self",
")",
":",
"self",
".",
"driver",
".",
"execute",
"(",
"Command",
".",
"ACCEPT_ALERT",
")"
] | https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/selenium/selenium/webdriver/common/alert.py#L33-L35 |
||
CaliOpen/Caliopen | 5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8 | src/backend/components/py.pi/caliopen_pi/qualifiers/base.py | python | BaseQualifier.get_participant | (self, message, participant) | return p, c | Try to find a related contact and return a Participant instance. | Try to find a related contact and return a Participant instance. | [
"Try",
"to",
"find",
"a",
"related",
"contact",
"and",
"return",
"a",
"Participant",
"instance",
"."
] | def get_participant(self, message, participant):
"""Try to find a related contact and return a Participant instance."""
p = Participant()
p.address = participant.address.lower()
p.type = participant.type
p.label = participant.label
p.protocol = message.message_protocol
log.debug('Will lookup contact {} for user {}'.
format(participant.address, self.user.user_id))
try:
c = Contact.lookup(self.user, participant.address)
except Exception as exc:
log.error("Contact lookup failed in get_participant for participant {} : {}".format(vars(participant), exc))
raise exc
if c:
p.contact_ids = [c.contact_id]
else:
if p.address == self.identity.identifier and self.user.contact_id:
p.contact_ids = [self.user.contact_id]
return p, c | [
"def",
"get_participant",
"(",
"self",
",",
"message",
",",
"participant",
")",
":",
"p",
"=",
"Participant",
"(",
")",
"p",
".",
"address",
"=",
"participant",
".",
"address",
".",
"lower",
"(",
")",
"p",
".",
"type",
"=",
"participant",
".",
"type",
"p",
".",
"label",
"=",
"participant",
".",
"label",
"p",
".",
"protocol",
"=",
"message",
".",
"message_protocol",
"log",
".",
"debug",
"(",
"'Will lookup contact {} for user {}'",
".",
"format",
"(",
"participant",
".",
"address",
",",
"self",
".",
"user",
".",
"user_id",
")",
")",
"try",
":",
"c",
"=",
"Contact",
".",
"lookup",
"(",
"self",
".",
"user",
",",
"participant",
".",
"address",
")",
"except",
"Exception",
"as",
"exc",
":",
"log",
".",
"error",
"(",
"\"Contact lookup failed in get_participant for participant {} : {}\"",
".",
"format",
"(",
"vars",
"(",
"participant",
")",
",",
"exc",
")",
")",
"raise",
"exc",
"if",
"c",
":",
"p",
".",
"contact_ids",
"=",
"[",
"c",
".",
"contact_id",
"]",
"else",
":",
"if",
"p",
".",
"address",
"==",
"self",
".",
"identity",
".",
"identifier",
"and",
"self",
".",
"user",
".",
"contact_id",
":",
"p",
".",
"contact_ids",
"=",
"[",
"self",
".",
"user",
".",
"contact_id",
"]",
"return",
"p",
",",
"c"
] | https://github.com/CaliOpen/Caliopen/blob/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8/src/backend/components/py.pi/caliopen_pi/qualifiers/base.py#L59-L78 |
|
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | tools/gyp/pylib/gyp/generator/ninja.py | python | Target.PreCompileInput | (self) | return self.actions_stamp or self.precompile_stamp | Return the path, if any, that should be used as a dependency of
any dependent compile step. | Return the path, if any, that should be used as a dependency of
any dependent compile step. | [
"Return",
"the",
"path",
"if",
"any",
"that",
"should",
"be",
"used",
"as",
"a",
"dependency",
"of",
"any",
"dependent",
"compile",
"step",
"."
] | def PreCompileInput(self):
"""Return the path, if any, that should be used as a dependency of
any dependent compile step."""
return self.actions_stamp or self.precompile_stamp | [
"def",
"PreCompileInput",
"(",
"self",
")",
":",
"return",
"self",
".",
"actions_stamp",
"or",
"self",
".",
"precompile_stamp"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/tools/gyp/pylib/gyp/generator/ninja.py#L177-L180 |
|
UWFlow/rmc | 00bcc1450ffbec3a6c8d956a2a5d1bb3a04bfcb9 | server/view_helpers.py | python | redirect_to_profile | (user) | Returns a flask.redirect() to a given user's profile.
Basically redirect the request to the /profile endpoint with their ObjectId
Args:
user: The user's profile to redirects to. Should NOT be None. | Returns a flask.redirect() to a given user's profile. | [
"Returns",
"a",
"flask",
".",
"redirect",
"()",
"to",
"a",
"given",
"user",
"s",
"profile",
"."
] | def redirect_to_profile(user):
"""
Returns a flask.redirect() to a given user's profile.
Basically redirect the request to the /profile endpoint with their ObjectId
Args:
user: The user's profile to redirects to. Should NOT be None.
"""
if user is None:
# This should only happen during development time...
logging.error('redirect_to_profile(user) called with user=None')
return flask.redirect('/profile', 302)
if flask.request.query_string:
return flask.redirect('/profile/%s?%s' % (
user.id, flask.request.query_string), 302)
else:
return flask.redirect('/profile/%s' % user.id, 302) | [
"def",
"redirect_to_profile",
"(",
"user",
")",
":",
"if",
"user",
"is",
"None",
":",
"# This should only happen during development time...",
"logging",
".",
"error",
"(",
"'redirect_to_profile(user) called with user=None'",
")",
"return",
"flask",
".",
"redirect",
"(",
"'/profile'",
",",
"302",
")",
"if",
"flask",
".",
"request",
".",
"query_string",
":",
"return",
"flask",
".",
"redirect",
"(",
"'/profile/%s?%s'",
"%",
"(",
"user",
".",
"id",
",",
"flask",
".",
"request",
".",
"query_string",
")",
",",
"302",
")",
"else",
":",
"return",
"flask",
".",
"redirect",
"(",
"'/profile/%s'",
"%",
"user",
".",
"id",
",",
"302",
")"
] | https://github.com/UWFlow/rmc/blob/00bcc1450ffbec3a6c8d956a2a5d1bb3a04bfcb9/server/view_helpers.py#L134-L152 |
||
jxcore/jxcore | b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | Target.PreActionInput | (self, flavor) | return self.FinalOutput() or self.preaction_stamp | Return the path, if any, that should be used as a dependency of
any dependent action step. | Return the path, if any, that should be used as a dependency of
any dependent action step. | [
"Return",
"the",
"path",
"if",
"any",
"that",
"should",
"be",
"used",
"as",
"a",
"dependency",
"of",
"any",
"dependent",
"action",
"step",
"."
] | def PreActionInput(self, flavor):
"""Return the path, if any, that should be used as a dependency of
any dependent action step."""
if self.UsesToc(flavor):
return self.FinalOutput() + '.TOC'
return self.FinalOutput() or self.preaction_stamp | [
"def",
"PreActionInput",
"(",
"self",
",",
"flavor",
")",
":",
"if",
"self",
".",
"UsesToc",
"(",
"flavor",
")",
":",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"+",
"'.TOC'",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"or",
"self",
".",
"preaction_stamp"
] | https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L163-L168 |
|
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | src/pyasm/prod/service/base_xmlrpc.py | python | BaseXMLRPC.create_set | (self, ticket, project_code, set_name, cat_name, selected) | return [xml, asset_code] | an xml to create a new set node | an xml to create a new set node | [
"an",
"xml",
"to",
"create",
"a",
"new",
"set",
"node"
] | def create_set(self, ticket, project_code, set_name, cat_name, selected):
'''an xml to create a new set node'''
xml = ''
asset_code = ''
try:
self.init(ticket)
Project.set_project(project_code)
cmd = MayaSetCreateCmd()
cmd.set_set_name(set_name)
cmd.set_cat_name(cat_name)
Command.execute_cmd(cmd)
asset_code = cmd.get_asset_code()
if asset_code:
cmd = CreateSetNodeCmd()
cmd.set_asset_code(asset_code)
cmd.set_instance(set_name)
cmd.set_contents(selected)
cmd.execute()
execute_xml = cmd.get_execute_xml()
xml = execute_xml.get_xml()
finally:
DbContainer.close_all()
return [xml, asset_code] | [
"def",
"create_set",
"(",
"self",
",",
"ticket",
",",
"project_code",
",",
"set_name",
",",
"cat_name",
",",
"selected",
")",
":",
"xml",
"=",
"''",
"asset_code",
"=",
"''",
"try",
":",
"self",
".",
"init",
"(",
"ticket",
")",
"Project",
".",
"set_project",
"(",
"project_code",
")",
"cmd",
"=",
"MayaSetCreateCmd",
"(",
")",
"cmd",
".",
"set_set_name",
"(",
"set_name",
")",
"cmd",
".",
"set_cat_name",
"(",
"cat_name",
")",
"Command",
".",
"execute_cmd",
"(",
"cmd",
")",
"asset_code",
"=",
"cmd",
".",
"get_asset_code",
"(",
")",
"if",
"asset_code",
":",
"cmd",
"=",
"CreateSetNodeCmd",
"(",
")",
"cmd",
".",
"set_asset_code",
"(",
"asset_code",
")",
"cmd",
".",
"set_instance",
"(",
"set_name",
")",
"cmd",
".",
"set_contents",
"(",
"selected",
")",
"cmd",
".",
"execute",
"(",
")",
"execute_xml",
"=",
"cmd",
".",
"get_execute_xml",
"(",
")",
"xml",
"=",
"execute_xml",
".",
"get_xml",
"(",
")",
"finally",
":",
"DbContainer",
".",
"close_all",
"(",
")",
"return",
"[",
"xml",
",",
"asset_code",
"]"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/pyasm/prod/service/base_xmlrpc.py#L232-L258 |
|
jeeliz/jeelizFaceFilter | be3ffa5a76c930a98b2b7895c1dfa1faa4a1fa82 | libs/three/blenderExporter/io_three/exporter/api/object.py | python | _valid_node | (obj, valid_types, options) | return True | :param obj:
:param valid_types:
:param options: | [] | def _valid_node(obj, valid_types, options):
"""
:param obj:
:param valid_types:
:param options:
"""
if obj.type not in valid_types:
return False
# skip objects that are not on visible layers
visible_layers = _visible_scene_layers()
if not _on_visible_layer(obj, visible_layers):
return False
try:
export = obj.THREE_export
except AttributeError:
export = True
if not export:
return False
mesh_node = mesh(obj, options)
is_mesh = obj.type == MESH
# skip objects that a mesh could not be resolved
if is_mesh and not mesh_node:
return False
# secondary test; if a mesh node was resolved but no
# faces are detected then bow out
if is_mesh:
mesh_node = data.meshes[mesh_node]
if len(mesh_node.tessfaces) is 0:
return False
# if we get this far assume that the mesh is valid
return True | [
"def",
"_valid_node",
"(",
"obj",
",",
"valid_types",
",",
"options",
")",
":",
"if",
"obj",
".",
"type",
"not",
"in",
"valid_types",
":",
"return",
"False",
"# skip objects that are not on visible layers",
"visible_layers",
"=",
"_visible_scene_layers",
"(",
")",
"if",
"not",
"_on_visible_layer",
"(",
"obj",
",",
"visible_layers",
")",
":",
"return",
"False",
"try",
":",
"export",
"=",
"obj",
".",
"THREE_export",
"except",
"AttributeError",
":",
"export",
"=",
"True",
"if",
"not",
"export",
":",
"return",
"False",
"mesh_node",
"=",
"mesh",
"(",
"obj",
",",
"options",
")",
"is_mesh",
"=",
"obj",
".",
"type",
"==",
"MESH",
"# skip objects that a mesh could not be resolved",
"if",
"is_mesh",
"and",
"not",
"mesh_node",
":",
"return",
"False",
"# secondary test; if a mesh node was resolved but no",
"# faces are detected then bow out",
"if",
"is_mesh",
":",
"mesh_node",
"=",
"data",
".",
"meshes",
"[",
"mesh_node",
"]",
"if",
"len",
"(",
"mesh_node",
".",
"tessfaces",
")",
"is",
"0",
":",
"return",
"False",
"# if we get this far assume that the mesh is valid",
"return",
"True"
] | https://github.com/jeeliz/jeelizFaceFilter/blob/be3ffa5a76c930a98b2b7895c1dfa1faa4a1fa82/libs/three/blenderExporter/io_three/exporter/api/object.py#L700-L738 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/main.py | python | main | (fixer_pkg, args=None) | return int(bool(rt.errors)) | Main program.
Args:
fixer_pkg: the name of a package where the fixers are located.
args: optional; a list of command line arguments. If omitted,
sys.argv[1:] is used.
Returns a suggested exit status (0, 1, 2). | Main program. | [
"Main",
"program",
"."
] | def main(fixer_pkg, args=None):
"""Main program.
Args:
fixer_pkg: the name of a package where the fixers are located.
args: optional; a list of command line arguments. If omitted,
sys.argv[1:] is used.
Returns a suggested exit status (0, 1, 2).
"""
# Set up option parser
parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
parser.add_option("-d", "--doctests_only", action="store_true",
help="Fix up doctests only")
parser.add_option("-f", "--fix", action="append", default=[],
help="Each FIX specifies a transformation; default: all")
parser.add_option("-j", "--processes", action="store", default=1,
type="int", help="Run 2to3 concurrently")
parser.add_option("-x", "--nofix", action="append", default=[],
help="Prevent a transformation from being run")
parser.add_option("-l", "--list-fixes", action="store_true",
help="List available transformations")
parser.add_option("-p", "--print-function", action="store_true",
help="Modify the grammar so that print() is a function")
parser.add_option("-v", "--verbose", action="store_true",
help="More verbose logging")
parser.add_option("--no-diffs", action="store_true",
help="Don't show diffs of the refactoring")
parser.add_option("-w", "--write", action="store_true",
help="Write back modified files")
parser.add_option("-n", "--nobackups", action="store_true", default=False,
help="Don't write backups for modified files")
parser.add_option("-o", "--output-dir", action="store", type="str",
default="", help="Put output files in this directory "
"instead of overwriting the input files. Requires -n.")
parser.add_option("-W", "--write-unchanged-files", action="store_true",
help="Also write files even if no changes were required"
" (useful with --output-dir); implies -w.")
parser.add_option("--add-suffix", action="store", type="str", default="",
help="Append this string to all output filenames."
" Requires -n if non-empty. "
"ex: --add-suffix='3' will generate .py3 files.")
# Parse command line arguments
refactor_stdin = False
flags = {}
options, args = parser.parse_args(args)
if options.write_unchanged_files:
flags["write_unchanged_files"] = True
if not options.write:
warn("--write-unchanged-files/-W implies -w.")
options.write = True
# If we allowed these, the original files would be renamed to backup names
# but not replaced.
if options.output_dir and not options.nobackups:
parser.error("Can't use --output-dir/-o without -n.")
if options.add_suffix and not options.nobackups:
parser.error("Can't use --add-suffix without -n.")
if not options.write and options.no_diffs:
warn("not writing files and not printing diffs; that's not very useful")
if not options.write and options.nobackups:
parser.error("Can't use -n without -w")
if options.list_fixes:
print "Available transformations for the -f/--fix option:"
for fixname in refactor.get_all_fix_names(fixer_pkg):
print fixname
if not args:
return 0
if not args:
print >> sys.stderr, "At least one file or directory argument required."
print >> sys.stderr, "Use --help to show usage."
return 2
if "-" in args:
refactor_stdin = True
if options.write:
print >> sys.stderr, "Can't write to stdin."
return 2
if options.print_function:
flags["print_function"] = True
# Set up logging handler
level = logging.DEBUG if options.verbose else logging.INFO
logging.basicConfig(format='%(name)s: %(message)s', level=level)
logger = logging.getLogger('lib2to3.main')
# Initialize the refactoring tool
avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
explicit = set()
if options.fix:
all_present = False
for fix in options.fix:
if fix == "all":
all_present = True
else:
explicit.add(fixer_pkg + ".fix_" + fix)
requested = avail_fixes.union(explicit) if all_present else explicit
else:
requested = avail_fixes.union(explicit)
fixer_names = requested.difference(unwanted_fixes)
input_base_dir = os.path.commonprefix(args)
if (input_base_dir and not input_base_dir.endswith(os.sep)
and not os.path.isdir(input_base_dir)):
# One or more similar names were passed, their directory is the base.
# os.path.commonprefix() is ignorant of path elements, this corrects
# for that weird API.
input_base_dir = os.path.dirname(input_base_dir)
if options.output_dir:
input_base_dir = input_base_dir.rstrip(os.sep)
logger.info('Output in %r will mirror the input directory %r layout.',
options.output_dir, input_base_dir)
rt = StdoutRefactoringTool(
sorted(fixer_names), flags, sorted(explicit),
options.nobackups, not options.no_diffs,
input_base_dir=input_base_dir,
output_dir=options.output_dir,
append_suffix=options.add_suffix)
# Refactor all files and directories passed as arguments
if not rt.errors:
if refactor_stdin:
rt.refactor_stdin()
else:
try:
rt.refactor(args, options.write, options.doctests_only,
options.processes)
except refactor.MultiprocessingUnsupported:
assert options.processes > 1
print >> sys.stderr, "Sorry, -j isn't " \
"supported on this platform."
return 1
rt.summarize()
# Return error status (0 if rt.errors is zero)
return int(bool(rt.errors)) | [
"def",
"main",
"(",
"fixer_pkg",
",",
"args",
"=",
"None",
")",
":",
"# Set up option parser",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"\"2to3 [options] file|dir ...\"",
")",
"parser",
".",
"add_option",
"(",
"\"-d\"",
",",
"\"--doctests_only\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Fix up doctests only\"",
")",
"parser",
".",
"add_option",
"(",
"\"-f\"",
",",
"\"--fix\"",
",",
"action",
"=",
"\"append\"",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"\"Each FIX specifies a transformation; default: all\"",
")",
"parser",
".",
"add_option",
"(",
"\"-j\"",
",",
"\"--processes\"",
",",
"action",
"=",
"\"store\"",
",",
"default",
"=",
"1",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Run 2to3 concurrently\"",
")",
"parser",
".",
"add_option",
"(",
"\"-x\"",
",",
"\"--nofix\"",
",",
"action",
"=",
"\"append\"",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"\"Prevent a transformation from being run\"",
")",
"parser",
".",
"add_option",
"(",
"\"-l\"",
",",
"\"--list-fixes\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"List available transformations\"",
")",
"parser",
".",
"add_option",
"(",
"\"-p\"",
",",
"\"--print-function\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Modify the grammar so that print() is a function\"",
")",
"parser",
".",
"add_option",
"(",
"\"-v\"",
",",
"\"--verbose\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"More verbose logging\"",
")",
"parser",
".",
"add_option",
"(",
"\"--no-diffs\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Don't show diffs of the refactoring\"",
")",
"parser",
".",
"add_option",
"(",
"\"-w\"",
",",
"\"--write\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Write back modified files\"",
")",
"parser",
".",
"add_option",
"(",
"\"-n\"",
",",
"\"--nobackups\"",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Don't write backups for modified files\"",
")",
"parser",
".",
"add_option",
"(",
"\"-o\"",
",",
"\"--output-dir\"",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"\"str\"",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Put output files in this directory \"",
"\"instead of overwriting the input files. Requires -n.\"",
")",
"parser",
".",
"add_option",
"(",
"\"-W\"",
",",
"\"--write-unchanged-files\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Also write files even if no changes were required\"",
"\" (useful with --output-dir); implies -w.\"",
")",
"parser",
".",
"add_option",
"(",
"\"--add-suffix\"",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"\"str\"",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Append this string to all output filenames.\"",
"\" Requires -n if non-empty. \"",
"\"ex: --add-suffix='3' will generate .py3 files.\"",
")",
"# Parse command line arguments",
"refactor_stdin",
"=",
"False",
"flags",
"=",
"{",
"}",
"options",
",",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"if",
"options",
".",
"write_unchanged_files",
":",
"flags",
"[",
"\"write_unchanged_files\"",
"]",
"=",
"True",
"if",
"not",
"options",
".",
"write",
":",
"warn",
"(",
"\"--write-unchanged-files/-W implies -w.\"",
")",
"options",
".",
"write",
"=",
"True",
"# If we allowed these, the original files would be renamed to backup names",
"# but not replaced.",
"if",
"options",
".",
"output_dir",
"and",
"not",
"options",
".",
"nobackups",
":",
"parser",
".",
"error",
"(",
"\"Can't use --output-dir/-o without -n.\"",
")",
"if",
"options",
".",
"add_suffix",
"and",
"not",
"options",
".",
"nobackups",
":",
"parser",
".",
"error",
"(",
"\"Can't use --add-suffix without -n.\"",
")",
"if",
"not",
"options",
".",
"write",
"and",
"options",
".",
"no_diffs",
":",
"warn",
"(",
"\"not writing files and not printing diffs; that's not very useful\"",
")",
"if",
"not",
"options",
".",
"write",
"and",
"options",
".",
"nobackups",
":",
"parser",
".",
"error",
"(",
"\"Can't use -n without -w\"",
")",
"if",
"options",
".",
"list_fixes",
":",
"print",
"\"Available transformations for the -f/--fix option:\"",
"for",
"fixname",
"in",
"refactor",
".",
"get_all_fix_names",
"(",
"fixer_pkg",
")",
":",
"print",
"fixname",
"if",
"not",
"args",
":",
"return",
"0",
"if",
"not",
"args",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"At least one file or directory argument required.\"",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Use --help to show usage.\"",
"return",
"2",
"if",
"\"-\"",
"in",
"args",
":",
"refactor_stdin",
"=",
"True",
"if",
"options",
".",
"write",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Can't write to stdin.\"",
"return",
"2",
"if",
"options",
".",
"print_function",
":",
"flags",
"[",
"\"print_function\"",
"]",
"=",
"True",
"# Set up logging handler",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"options",
".",
"verbose",
"else",
"logging",
".",
"INFO",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"'%(name)s: %(message)s'",
",",
"level",
"=",
"level",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'lib2to3.main'",
")",
"# Initialize the refactoring tool",
"avail_fixes",
"=",
"set",
"(",
"refactor",
".",
"get_fixers_from_package",
"(",
"fixer_pkg",
")",
")",
"unwanted_fixes",
"=",
"set",
"(",
"fixer_pkg",
"+",
"\".fix_\"",
"+",
"fix",
"for",
"fix",
"in",
"options",
".",
"nofix",
")",
"explicit",
"=",
"set",
"(",
")",
"if",
"options",
".",
"fix",
":",
"all_present",
"=",
"False",
"for",
"fix",
"in",
"options",
".",
"fix",
":",
"if",
"fix",
"==",
"\"all\"",
":",
"all_present",
"=",
"True",
"else",
":",
"explicit",
".",
"add",
"(",
"fixer_pkg",
"+",
"\".fix_\"",
"+",
"fix",
")",
"requested",
"=",
"avail_fixes",
".",
"union",
"(",
"explicit",
")",
"if",
"all_present",
"else",
"explicit",
"else",
":",
"requested",
"=",
"avail_fixes",
".",
"union",
"(",
"explicit",
")",
"fixer_names",
"=",
"requested",
".",
"difference",
"(",
"unwanted_fixes",
")",
"input_base_dir",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"args",
")",
"if",
"(",
"input_base_dir",
"and",
"not",
"input_base_dir",
".",
"endswith",
"(",
"os",
".",
"sep",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"input_base_dir",
")",
")",
":",
"# One or more similar names were passed, their directory is the base.",
"# os.path.commonprefix() is ignorant of path elements, this corrects",
"# for that weird API.",
"input_base_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"input_base_dir",
")",
"if",
"options",
".",
"output_dir",
":",
"input_base_dir",
"=",
"input_base_dir",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
"logger",
".",
"info",
"(",
"'Output in %r will mirror the input directory %r layout.'",
",",
"options",
".",
"output_dir",
",",
"input_base_dir",
")",
"rt",
"=",
"StdoutRefactoringTool",
"(",
"sorted",
"(",
"fixer_names",
")",
",",
"flags",
",",
"sorted",
"(",
"explicit",
")",
",",
"options",
".",
"nobackups",
",",
"not",
"options",
".",
"no_diffs",
",",
"input_base_dir",
"=",
"input_base_dir",
",",
"output_dir",
"=",
"options",
".",
"output_dir",
",",
"append_suffix",
"=",
"options",
".",
"add_suffix",
")",
"# Refactor all files and directories passed as arguments",
"if",
"not",
"rt",
".",
"errors",
":",
"if",
"refactor_stdin",
":",
"rt",
".",
"refactor_stdin",
"(",
")",
"else",
":",
"try",
":",
"rt",
".",
"refactor",
"(",
"args",
",",
"options",
".",
"write",
",",
"options",
".",
"doctests_only",
",",
"options",
".",
"processes",
")",
"except",
"refactor",
".",
"MultiprocessingUnsupported",
":",
"assert",
"options",
".",
"processes",
">",
"1",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Sorry, -j isn't \"",
"\"supported on this platform.\"",
"return",
"1",
"rt",
".",
"summarize",
"(",
")",
"# Return error status (0 if rt.errors is zero)",
"return",
"int",
"(",
"bool",
"(",
"rt",
".",
"errors",
")",
")"
] | 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/main.py#L134-L269 |
|
NVIDIA-AI-IOT/deepstream_360_d_smart_parking_application | b9b1f9e9aa84e379c573063fc5622ef50d38898d | tracker/code/mctrack/mctracker.py | python | MulticamTracker.select_rep_member_from_list | (self, json_list) | return retval | This method selects one representative dict from the list
of vehicle detections (in json_list)
Returns:
[dict] -- A representative day2 schema dictionary of
selected representative vehicle detection | This method selects one representative dict from the list
of vehicle detections (in json_list) | [
"This",
"method",
"selects",
"one",
"representative",
"dict",
"from",
"the",
"list",
"of",
"vehicle",
"detections",
"(",
"in",
"json_list",
")"
] | def select_rep_member_from_list(self, json_list):
"""
This method selects one representative dict from the list
of vehicle detections (in json_list)
Returns:
[dict] -- A representative day2 schema dictionary of
selected representative vehicle detection
"""
retval = None
if json_list:
retval = json_list[0]
pref = 100
min_obj_id = None
for ele in json_list:
# 1st pref = entry/exit
# 2nd pref = one with videopath
if ele["event"]["type"] in ["entry", "exit"]:
retval = ele
pref = 1
elif(pref > 1) and (ele["videoPath"] != ""):
retval = ele
pref = 2
elif(pref > 2) and (min_obj_id is None or
min_obj_id > ele["object"]["id"]):
retval = ele
min_obj_id = ele["object"]["id"]
pref = 3
return retval | [
"def",
"select_rep_member_from_list",
"(",
"self",
",",
"json_list",
")",
":",
"retval",
"=",
"None",
"if",
"json_list",
":",
"retval",
"=",
"json_list",
"[",
"0",
"]",
"pref",
"=",
"100",
"min_obj_id",
"=",
"None",
"for",
"ele",
"in",
"json_list",
":",
"# 1st pref = entry/exit",
"# 2nd pref = one with videopath",
"if",
"ele",
"[",
"\"event\"",
"]",
"[",
"\"type\"",
"]",
"in",
"[",
"\"entry\"",
",",
"\"exit\"",
"]",
":",
"retval",
"=",
"ele",
"pref",
"=",
"1",
"elif",
"(",
"pref",
">",
"1",
")",
"and",
"(",
"ele",
"[",
"\"videoPath\"",
"]",
"!=",
"\"\"",
")",
":",
"retval",
"=",
"ele",
"pref",
"=",
"2",
"elif",
"(",
"pref",
">",
"2",
")",
"and",
"(",
"min_obj_id",
"is",
"None",
"or",
"min_obj_id",
">",
"ele",
"[",
"\"object\"",
"]",
"[",
"\"id\"",
"]",
")",
":",
"retval",
"=",
"ele",
"min_obj_id",
"=",
"ele",
"[",
"\"object\"",
"]",
"[",
"\"id\"",
"]",
"pref",
"=",
"3",
"return",
"retval"
] | https://github.com/NVIDIA-AI-IOT/deepstream_360_d_smart_parking_application/blob/b9b1f9e9aa84e379c573063fc5622ef50d38898d/tracker/code/mctrack/mctracker.py#L554-L582 |
|
agoravoting/agora-ciudadana | a7701035ea77d7a91baa9b5c2d0c05d91d1b4262 | agora_site/misc/utils.py | python | rest | (path, query={}, data={}, headers={}, method="GET", request=None) | return (res.status_code, res._container) | Converts a RPC-like call to something like a HttpRequest, passes it
to the right view function (via django's url resolver) and returns
the result.
Args:
path: a uri-like string representing an API endpoint. e.g. /resource/27.
/api/v2/ is automatically prepended to the path.
query: dictionary of GET-like query parameters to pass to view
data: dictionary of POST-like parameters to pass to view
headers: dictionary of extra headers to pass to view (will end up in request.META)
method: HTTP verb for the emulated request
Returns:
a tuple of (status, content):
status: integer representing an HTTP response code
content: string, body of response; may be empty | Converts a RPC-like call to something like a HttpRequest, passes it
to the right view function (via django's url resolver) and returns
the result. | [
"Converts",
"a",
"RPC",
"-",
"like",
"call",
"to",
"something",
"like",
"a",
"HttpRequest",
"passes",
"it",
"to",
"the",
"right",
"view",
"function",
"(",
"via",
"django",
"s",
"url",
"resolver",
")",
"and",
"returns",
"the",
"result",
"."
] | def rest(path, query={}, data={}, headers={}, method="GET", request=None):
"""
Converts a RPC-like call to something like a HttpRequest, passes it
to the right view function (via django's url resolver) and returns
the result.
Args:
path: a uri-like string representing an API endpoint. e.g. /resource/27.
/api/v2/ is automatically prepended to the path.
query: dictionary of GET-like query parameters to pass to view
data: dictionary of POST-like parameters to pass to view
headers: dictionary of extra headers to pass to view (will end up in request.META)
method: HTTP verb for the emulated request
Returns:
a tuple of (status, content):
status: integer representing an HTTP response code
content: string, body of response; may be empty
"""
#adjust for lack of trailing slash, just in case
if path[-1] != '/':
path += '/'
hreq = FakeHttpRequest()
hreq.path = '/api/v1' + path
hreq.GET = query
if isinstance(data, basestring):
hreq.POST = customstr(data)
else:
hreq.POST = customstr(json.dumps(data))
hreq.META = headers
hreq.method = method
if request:
hreq.user = request.user
try:
view = resolve(hreq.path)
res = view.func(hreq, *view.args, **view.kwargs)
except Resolver404:
return (404, '')
#container is the untouched content before HttpResponse mangles it
return (res.status_code, res._container) | [
"def",
"rest",
"(",
"path",
",",
"query",
"=",
"{",
"}",
",",
"data",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"method",
"=",
"\"GET\"",
",",
"request",
"=",
"None",
")",
":",
"#adjust for lack of trailing slash, just in case",
"if",
"path",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"path",
"+=",
"'/'",
"hreq",
"=",
"FakeHttpRequest",
"(",
")",
"hreq",
".",
"path",
"=",
"'/api/v1'",
"+",
"path",
"hreq",
".",
"GET",
"=",
"query",
"if",
"isinstance",
"(",
"data",
",",
"basestring",
")",
":",
"hreq",
".",
"POST",
"=",
"customstr",
"(",
"data",
")",
"else",
":",
"hreq",
".",
"POST",
"=",
"customstr",
"(",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"hreq",
".",
"META",
"=",
"headers",
"hreq",
".",
"method",
"=",
"method",
"if",
"request",
":",
"hreq",
".",
"user",
"=",
"request",
".",
"user",
"try",
":",
"view",
"=",
"resolve",
"(",
"hreq",
".",
"path",
")",
"res",
"=",
"view",
".",
"func",
"(",
"hreq",
",",
"*",
"view",
".",
"args",
",",
"*",
"*",
"view",
".",
"kwargs",
")",
"except",
"Resolver404",
":",
"return",
"(",
"404",
",",
"''",
")",
"#container is the untouched content before HttpResponse mangles it",
"return",
"(",
"res",
".",
"status_code",
",",
"res",
".",
"_container",
")"
] | https://github.com/agoravoting/agora-ciudadana/blob/a7701035ea77d7a91baa9b5c2d0c05d91d1b4262/agora_site/misc/utils.py#L375-L415 |
|
CaliOpen/Caliopen | 5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8 | src/backend/tools/py.CLI/caliopen_cli/commands/setup_storage.py | python | setup_storage | (settings=None) | Create cassandra models. | Create cassandra models. | [
"Create",
"cassandra",
"models",
"."
] | def setup_storage(settings=None):
"""Create cassandra models."""
from caliopen_storage.core import core_registry
# Make discovery happen
from caliopen_main.user.core import User
from caliopen_main.user.core import (UserIdentity,
IdentityLookup,
IdentityTypeLookup)
from caliopen_main.contact.objects.contact import Contact
from caliopen_main.message.objects.message import Message
from caliopen_main.common.objects.tag import ResourceTag
from caliopen_main.device.core import Device
from caliopen_main.notification.core import Notification, NotificationTtl
from caliopen_main.protocol.core import Provider
from cassandra.cqlengine.management import sync_table, \
create_keyspace_simple
keyspace = Configuration('global').get('cassandra.keyspace')
if not keyspace:
raise Exception('Configuration missing for cassandra keyspace')
# XXX tofix : define strategy and replication_factor in configuration
create_keyspace_simple(keyspace, 1)
for name, kls in core_registry.items():
log.info('Creating cassandra model %s' % name)
if hasattr(kls._model_class, 'pk'):
# XXX find a better way to detect model from udt
sync_table(kls._model_class) | [
"def",
"setup_storage",
"(",
"settings",
"=",
"None",
")",
":",
"from",
"caliopen_storage",
".",
"core",
"import",
"core_registry",
"# Make discovery happen",
"from",
"caliopen_main",
".",
"user",
".",
"core",
"import",
"User",
"from",
"caliopen_main",
".",
"user",
".",
"core",
"import",
"(",
"UserIdentity",
",",
"IdentityLookup",
",",
"IdentityTypeLookup",
")",
"from",
"caliopen_main",
".",
"contact",
".",
"objects",
".",
"contact",
"import",
"Contact",
"from",
"caliopen_main",
".",
"message",
".",
"objects",
".",
"message",
"import",
"Message",
"from",
"caliopen_main",
".",
"common",
".",
"objects",
".",
"tag",
"import",
"ResourceTag",
"from",
"caliopen_main",
".",
"device",
".",
"core",
"import",
"Device",
"from",
"caliopen_main",
".",
"notification",
".",
"core",
"import",
"Notification",
",",
"NotificationTtl",
"from",
"caliopen_main",
".",
"protocol",
".",
"core",
"import",
"Provider",
"from",
"cassandra",
".",
"cqlengine",
".",
"management",
"import",
"sync_table",
",",
"create_keyspace_simple",
"keyspace",
"=",
"Configuration",
"(",
"'global'",
")",
".",
"get",
"(",
"'cassandra.keyspace'",
")",
"if",
"not",
"keyspace",
":",
"raise",
"Exception",
"(",
"'Configuration missing for cassandra keyspace'",
")",
"# XXX tofix : define strategy and replication_factor in configuration",
"create_keyspace_simple",
"(",
"keyspace",
",",
"1",
")",
"for",
"name",
",",
"kls",
"in",
"core_registry",
".",
"items",
"(",
")",
":",
"log",
".",
"info",
"(",
"'Creating cassandra model %s'",
"%",
"name",
")",
"if",
"hasattr",
"(",
"kls",
".",
"_model_class",
",",
"'pk'",
")",
":",
"# XXX find a better way to detect model from udt",
"sync_table",
"(",
"kls",
".",
"_model_class",
")"
] | https://github.com/CaliOpen/Caliopen/blob/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8/src/backend/tools/py.CLI/caliopen_cli/commands/setup_storage.py#L9-L35 |
||
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.AdjustMidlIncludeDirs | (self, midl_include_dirs, config) | return [self.ConvertVSMacros(p, config=config) for p in includes] | Updates midl_include_dirs to expand VS specific paths, and adds the
system include dirs used for platform SDK and similar. | Updates midl_include_dirs to expand VS specific paths, and adds the
system include dirs used for platform SDK and similar. | [
"Updates",
"midl_include_dirs",
"to",
"expand",
"VS",
"specific",
"paths",
"and",
"adds",
"the",
"system",
"include",
"dirs",
"used",
"for",
"platform",
"SDK",
"and",
"similar",
"."
] | def AdjustMidlIncludeDirs(self, midl_include_dirs, config):
"""Updates midl_include_dirs to expand VS specific paths, and adds the
system include dirs used for platform SDK and similar."""
config = self._TargetConfig(config)
includes = midl_include_dirs + self.msvs_system_include_dirs[config]
includes.extend(self._Setting(
('VCMIDLTool', 'AdditionalIncludeDirectories'), config, default=[]))
return [self.ConvertVSMacros(p, config=config) for p in includes] | [
"def",
"AdjustMidlIncludeDirs",
"(",
"self",
",",
"midl_include_dirs",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"includes",
"=",
"midl_include_dirs",
"+",
"self",
".",
"msvs_system_include_dirs",
"[",
"config",
"]",
"includes",
".",
"extend",
"(",
"self",
".",
"_Setting",
"(",
"(",
"'VCMIDLTool'",
",",
"'AdditionalIncludeDirectories'",
")",
",",
"config",
",",
"default",
"=",
"[",
"]",
")",
")",
"return",
"[",
"self",
".",
"ConvertVSMacros",
"(",
"p",
",",
"config",
"=",
"config",
")",
"for",
"p",
"in",
"includes",
"]"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L349-L356 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/smtplib.py | python | SMTP.starttls | (self, keyfile=None, certfile=None) | return (resp, reply) | Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked. This,
however, depends on whether the socket module really checks the
certificates.
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
the helo greeting. | Puts the connection to the SMTP server into TLS mode. | [
"Puts",
"the",
"connection",
"to",
"the",
"SMTP",
"server",
"into",
"TLS",
"mode",
"."
] | def starttls(self, keyfile=None, certfile=None):
"""Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked. This,
however, depends on whether the socket module really checks the
certificates.
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
the helo greeting.
"""
self.ehlo_or_helo_if_needed()
if not self.has_extn("starttls"):
raise SMTPException("STARTTLS extension not supported by server.")
(resp, reply) = self.docmd("STARTTLS")
if resp == 220:
if not _have_ssl:
raise RuntimeError("No SSL support included in this Python")
self.sock = ssl.wrap_socket(self.sock, keyfile, certfile)
self.file = SSLFakeFile(self.sock)
# RFC 3207:
# The client MUST discard any knowledge obtained from
# the server, such as the list of SMTP service extensions,
# which was not obtained from the TLS negotiation itself.
self.helo_resp = None
self.ehlo_resp = None
self.esmtp_features = {}
self.does_esmtp = 0
return (resp, reply) | [
"def",
"starttls",
"(",
"self",
",",
"keyfile",
"=",
"None",
",",
"certfile",
"=",
"None",
")",
":",
"self",
".",
"ehlo_or_helo_if_needed",
"(",
")",
"if",
"not",
"self",
".",
"has_extn",
"(",
"\"starttls\"",
")",
":",
"raise",
"SMTPException",
"(",
"\"STARTTLS extension not supported by server.\"",
")",
"(",
"resp",
",",
"reply",
")",
"=",
"self",
".",
"docmd",
"(",
"\"STARTTLS\"",
")",
"if",
"resp",
"==",
"220",
":",
"if",
"not",
"_have_ssl",
":",
"raise",
"RuntimeError",
"(",
"\"No SSL support included in this Python\"",
")",
"self",
".",
"sock",
"=",
"ssl",
".",
"wrap_socket",
"(",
"self",
".",
"sock",
",",
"keyfile",
",",
"certfile",
")",
"self",
".",
"file",
"=",
"SSLFakeFile",
"(",
"self",
".",
"sock",
")",
"# RFC 3207:",
"# The client MUST discard any knowledge obtained from",
"# the server, such as the list of SMTP service extensions,",
"# which was not obtained from the TLS negotiation itself.",
"self",
".",
"helo_resp",
"=",
"None",
"self",
".",
"ehlo_resp",
"=",
"None",
"self",
".",
"esmtp_features",
"=",
"{",
"}",
"self",
".",
"does_esmtp",
"=",
"0",
"return",
"(",
"resp",
",",
"reply",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/smtplib.py#L607-L641 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/collections.py | python | Counter.__missing__ | (self, key) | return 0 | The count of elements not in the Counter is zero. | The count of elements not in the Counter is zero. | [
"The",
"count",
"of",
"elements",
"not",
"in",
"the",
"Counter",
"is",
"zero",
"."
] | def __missing__(self, key):
'The count of elements not in the Counter is zero.'
# Needed so that self[missing_item] does not raise KeyError
return 0 | [
"def",
"__missing__",
"(",
"self",
",",
"key",
")",
":",
"# Needed so that self[missing_item] does not raise KeyError",
"return",
"0"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/collections.py#L420-L423 |
|
nkrode/RedisLive | e1d7763baee558ce4681b7764025d38df5ee5798 | src/dataprovider/redisprovider.py | python | RedisStatsProvider.save_info_command | (self, server, timestamp, info) | Save Redis info command dump
Args:
server (str): id of server
timestamp (datetime): Timestamp.
info (dict): The result of a Redis INFO command. | Save Redis info command dump | [
"Save",
"Redis",
"info",
"command",
"dump"
] | def save_info_command(self, server, timestamp, info):
"""Save Redis info command dump
Args:
server (str): id of server
timestamp (datetime): Timestamp.
info (dict): The result of a Redis INFO command.
"""
self.conn.set(server + ":Info", json.dumps(info)) | [
"def",
"save_info_command",
"(",
"self",
",",
"server",
",",
"timestamp",
",",
"info",
")",
":",
"self",
".",
"conn",
".",
"set",
"(",
"server",
"+",
"\":Info\"",
",",
"json",
".",
"dumps",
"(",
"info",
")",
")"
] | https://github.com/nkrode/RedisLive/blob/e1d7763baee558ce4681b7764025d38df5ee5798/src/dataprovider/redisprovider.py#L32-L40 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/random.py | python | WichmannHill.seed | (self, a=None) | Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclusive are guaranteed to yield distinct
internal states (this guarantee is specific to the default
Wichmann-Hill generator). | Initialize internal state from hashable object. | [
"Initialize",
"internal",
"state",
"from",
"hashable",
"object",
"."
] | def seed(self, a=None):
"""Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclusive are guaranteed to yield distinct
internal states (this guarantee is specific to the default
Wichmann-Hill generator).
"""
if a is None:
try:
a = long(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
a = long(time.time() * 256) # use fractional seconds
if not isinstance(a, (int, long)):
a = hash(a)
a, x = divmod(a, 30268)
a, y = divmod(a, 30306)
a, z = divmod(a, 30322)
self._seed = int(x)+1, int(y)+1, int(z)+1
self.gauss_next = None | [
"def",
"seed",
"(",
"self",
",",
"a",
"=",
"None",
")",
":",
"if",
"a",
"is",
"None",
":",
"try",
":",
"a",
"=",
"long",
"(",
"_hexlify",
"(",
"_urandom",
"(",
"16",
")",
")",
",",
"16",
")",
"except",
"NotImplementedError",
":",
"import",
"time",
"a",
"=",
"long",
"(",
"time",
".",
"time",
"(",
")",
"*",
"256",
")",
"# use fractional seconds",
"if",
"not",
"isinstance",
"(",
"a",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"a",
"=",
"hash",
"(",
"a",
")",
"a",
",",
"x",
"=",
"divmod",
"(",
"a",
",",
"30268",
")",
"a",
",",
"y",
"=",
"divmod",
"(",
"a",
",",
"30306",
")",
"a",
",",
"z",
"=",
"divmod",
"(",
"a",
",",
"30322",
")",
"self",
".",
"_seed",
"=",
"int",
"(",
"x",
")",
"+",
"1",
",",
"int",
"(",
"y",
")",
"+",
"1",
",",
"int",
"(",
"z",
")",
"+",
"1",
"self",
".",
"gauss_next",
"=",
"None"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/random.py#L657-L686 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/user32.py | python | Point._as_parameter_ | (self) | return POINT(self.x, self.y) | Compatibility with ctypes.
Allows passing transparently a Point object to an API call. | Compatibility with ctypes.
Allows passing transparently a Point object to an API call. | [
"Compatibility",
"with",
"ctypes",
".",
"Allows",
"passing",
"transparently",
"a",
"Point",
"object",
"to",
"an",
"API",
"call",
"."
] | def _as_parameter_(self):
"""
Compatibility with ctypes.
Allows passing transparently a Point object to an API call.
"""
return POINT(self.x, self.y) | [
"def",
"_as_parameter_",
"(",
"self",
")",
":",
"return",
"POINT",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/user32.py#L438-L443 |
|
TeamvisionCorp/TeamVision | aa2a57469e430ff50cce21174d8f280efa0a83a7 | distribute/0.0.4/build_shell/teamvision/teamvision/issue/views/dashboard_view.py | python | index | (request,env_id) | return page_worker.get_dashboard_index(request,"all") | index page | index page | [
"index",
"page"
] | def index(request,env_id):
''' index page'''
page_worker=ENVDashBoardPageWorker(request)
return page_worker.get_dashboard_index(request,"all") | [
"def",
"index",
"(",
"request",
",",
"env_id",
")",
":",
"page_worker",
"=",
"ENVDashBoardPageWorker",
"(",
"request",
")",
"return",
"page_worker",
".",
"get_dashboard_index",
"(",
"request",
",",
"\"all\"",
")"
] | https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.4/build_shell/teamvision/teamvision/issue/views/dashboard_view.py#L18-L21 |
|
aaPanel/aaPanel | d2a66661dbd66948cce5a074214257550aec91ee | class/pyotp/totp.py | python | TOTP.__init__ | (self, *args, **kwargs) | :param interval: the time interval in seconds
for OTP. This defaults to 30.
:type interval: int | :param interval: the time interval in seconds
for OTP. This defaults to 30.
:type interval: int | [
":",
"param",
"interval",
":",
"the",
"time",
"interval",
"in",
"seconds",
"for",
"OTP",
".",
"This",
"defaults",
"to",
"30",
".",
":",
"type",
"interval",
":",
"int"
] | def __init__(self, *args, **kwargs):
"""
:param interval: the time interval in seconds
for OTP. This defaults to 30.
:type interval: int
"""
self.interval = kwargs.pop('interval', 30)
super(TOTP, self).__init__(*args, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"interval",
"=",
"kwargs",
".",
"pop",
"(",
"'interval'",
",",
"30",
")",
"super",
"(",
"TOTP",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aaPanel/aaPanel/blob/d2a66661dbd66948cce5a074214257550aec91ee/class/pyotp/totp.py#L14-L21 |
||
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/Zelenium/zuite.py | python | Zuite._getZipFile | ( self, include_selenium=True ) | return stream.getvalue() | Generate a zip file containing both tests and scaffolding. | Generate a zip file containing both tests and scaffolding. | [
"Generate",
"a",
"zip",
"file",
"containing",
"both",
"tests",
"and",
"scaffolding",
"."
] | def _getZipFile( self, include_selenium=True ):
""" Generate a zip file containing both tests and scaffolding.
"""
stream = StringIO.StringIO()
archive = zipfile.ZipFile( stream, 'w' )
def convertToBytes(body):
if isinstance(body, types.UnicodeType):
return body.encode(_DEFAULTENCODING)
else:
return body
archive.writestr( 'index.html'
, convertToBytes(self.index_html( suite_name='testSuite.html' ) ) )
test_cases = self.listTestCases()
paths = { '' : [] }
def _ensurePath( prefix, element ):
elements = paths.setdefault( prefix, [] )
if element not in elements:
elements.append( element )
for info in test_cases:
# ensure suffixes
path = self._getFilename( info[ 'path' ] )
info[ 'path' ] = path
info[ 'url' ] = self._getFilename( info[ 'url' ] )
elements = path.split( os.path.sep )
_ensurePath( '', elements[ 0 ] )
for i in range( 1, len( elements ) ):
prefix = '/'.join( elements[ : i ] )
_ensurePath( prefix, elements[ i ] )
archive.writestr( 'testSuite.html'
, convertToBytes(self.test_suite_html( test_cases=test_cases ) ) )
for pathname, filenames in paths.items():
if pathname == '':
filename = '.objects'
else:
filename = '%s/.objects' % pathname
archive.writestr( convertToBytes(filename)
, convertToBytes(u'\n'.join( filenames ) ) )
for info in test_cases:
test_case = info[ 'test_case' ]
if getattr( test_case, '__call__', None ) is not None:
body = test_case() # XXX: DTML?
else:
body = test_case.manage_FTPget()
archive.writestr( convertToBytes(info[ 'path' ])
, convertToBytes(body) )
if include_selenium:
for k, v in _SUPPORT_FILES.items():
archive.writestr( convertToBytes(k),
convertToBytes(v.__of__(self).manage_FTPget() ) )
archive.close()
return stream.getvalue() | [
"def",
"_getZipFile",
"(",
"self",
",",
"include_selenium",
"=",
"True",
")",
":",
"stream",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"archive",
"=",
"zipfile",
".",
"ZipFile",
"(",
"stream",
",",
"'w'",
")",
"def",
"convertToBytes",
"(",
"body",
")",
":",
"if",
"isinstance",
"(",
"body",
",",
"types",
".",
"UnicodeType",
")",
":",
"return",
"body",
".",
"encode",
"(",
"_DEFAULTENCODING",
")",
"else",
":",
"return",
"body",
"archive",
".",
"writestr",
"(",
"'index.html'",
",",
"convertToBytes",
"(",
"self",
".",
"index_html",
"(",
"suite_name",
"=",
"'testSuite.html'",
")",
")",
")",
"test_cases",
"=",
"self",
".",
"listTestCases",
"(",
")",
"paths",
"=",
"{",
"''",
":",
"[",
"]",
"}",
"def",
"_ensurePath",
"(",
"prefix",
",",
"element",
")",
":",
"elements",
"=",
"paths",
".",
"setdefault",
"(",
"prefix",
",",
"[",
"]",
")",
"if",
"element",
"not",
"in",
"elements",
":",
"elements",
".",
"append",
"(",
"element",
")",
"for",
"info",
"in",
"test_cases",
":",
"# ensure suffixes",
"path",
"=",
"self",
".",
"_getFilename",
"(",
"info",
"[",
"'path'",
"]",
")",
"info",
"[",
"'path'",
"]",
"=",
"path",
"info",
"[",
"'url'",
"]",
"=",
"self",
".",
"_getFilename",
"(",
"info",
"[",
"'url'",
"]",
")",
"elements",
"=",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"_ensurePath",
"(",
"''",
",",
"elements",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"elements",
")",
")",
":",
"prefix",
"=",
"'/'",
".",
"join",
"(",
"elements",
"[",
":",
"i",
"]",
")",
"_ensurePath",
"(",
"prefix",
",",
"elements",
"[",
"i",
"]",
")",
"archive",
".",
"writestr",
"(",
"'testSuite.html'",
",",
"convertToBytes",
"(",
"self",
".",
"test_suite_html",
"(",
"test_cases",
"=",
"test_cases",
")",
")",
")",
"for",
"pathname",
",",
"filenames",
"in",
"paths",
".",
"items",
"(",
")",
":",
"if",
"pathname",
"==",
"''",
":",
"filename",
"=",
"'.objects'",
"else",
":",
"filename",
"=",
"'%s/.objects'",
"%",
"pathname",
"archive",
".",
"writestr",
"(",
"convertToBytes",
"(",
"filename",
")",
",",
"convertToBytes",
"(",
"u'\\n'",
".",
"join",
"(",
"filenames",
")",
")",
")",
"for",
"info",
"in",
"test_cases",
":",
"test_case",
"=",
"info",
"[",
"'test_case'",
"]",
"if",
"getattr",
"(",
"test_case",
",",
"'__call__'",
",",
"None",
")",
"is",
"not",
"None",
":",
"body",
"=",
"test_case",
"(",
")",
"# XXX: DTML?",
"else",
":",
"body",
"=",
"test_case",
".",
"manage_FTPget",
"(",
")",
"archive",
".",
"writestr",
"(",
"convertToBytes",
"(",
"info",
"[",
"'path'",
"]",
")",
",",
"convertToBytes",
"(",
"body",
")",
")",
"if",
"include_selenium",
":",
"for",
"k",
",",
"v",
"in",
"_SUPPORT_FILES",
".",
"items",
"(",
")",
":",
"archive",
".",
"writestr",
"(",
"convertToBytes",
"(",
"k",
")",
",",
"convertToBytes",
"(",
"v",
".",
"__of__",
"(",
"self",
")",
".",
"manage_FTPget",
"(",
")",
")",
")",
"archive",
".",
"close",
"(",
")",
"return",
"stream",
".",
"getvalue",
"(",
")"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/Zelenium/zuite.py#L497-L566 |
|
carlosperate/ardublockly | 04fa48273b5651386d0ef1ce6dd446795ffc2594 | ardublocklyserver/local-packages/serial/threaded/__init__.py | python | LineReader.handle_line | (self, line) | Process one line - to be overridden by subclassing | Process one line - to be overridden by subclassing | [
"Process",
"one",
"line",
"-",
"to",
"be",
"overridden",
"by",
"subclassing"
] | def handle_line(self, line):
"""Process one line - to be overridden by subclassing"""
raise NotImplementedError('please implement functionality in handle_line') | [
"def",
"handle_line",
"(",
"self",
",",
"line",
")",
":",
"raise",
"NotImplementedError",
"(",
"'please implement functionality in handle_line'",
")"
] | https://github.com/carlosperate/ardublockly/blob/04fa48273b5651386d0ef1ce6dd446795ffc2594/ardublocklyserver/local-packages/serial/threaded/__init__.py#L134-L136 |
||
aws-samples/aws-lex-web-ui | 370f11286062957faf51448cb3bd93c5776be8e0 | templates/custom-resources/lex-manager.py | python | get_parsed_args | () | return args | Parse arguments passed when running as a shell script | Parse arguments passed when running as a shell script | [
"Parse",
"arguments",
"passed",
"when",
"running",
"as",
"a",
"shell",
"script"
] | def get_parsed_args():
""" Parse arguments passed when running as a shell script
"""
parser = argparse.ArgumentParser(
description='Lex bot manager. Import, export or delete a Lex bot.'
' Used to import/export/delete Lex bots and associated resources'
' (i.e. intents, slot types).'
)
format_group = parser.add_mutually_exclusive_group()
format_group.add_argument('-i', '--import',
nargs='?',
default=argparse.SUPPRESS,
const=BOT_DEFINITION_FILENAME,
metavar='file',
help='Import bot definition from file into account. Defaults to: {}'
.format(BOT_DEFINITION_FILENAME),
)
format_group.add_argument('-e', '--export',
nargs='?',
default=argparse.SUPPRESS,
metavar='botname',
help='Export bot definition as JSON to stdout'
' Defaults to reading the botname from the definition file: {}'
.format(BOT_DEFINITION_FILENAME),
)
format_group.add_argument('-d', '--delete',
nargs=1,
default=argparse.SUPPRESS,
metavar='botname',
help='Deletes the bot passed as argument and its associated resources.'
)
args = parser.parse_args()
if not bool(vars(args)):
parser.print_help()
sys.exit(1)
return args | [
"def",
"get_parsed_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Lex bot manager. Import, export or delete a Lex bot.'",
"' Used to import/export/delete Lex bots and associated resources'",
"' (i.e. intents, slot types).'",
")",
"format_group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"format_group",
".",
"add_argument",
"(",
"'-i'",
",",
"'--import'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"argparse",
".",
"SUPPRESS",
",",
"const",
"=",
"BOT_DEFINITION_FILENAME",
",",
"metavar",
"=",
"'file'",
",",
"help",
"=",
"'Import bot definition from file into account. Defaults to: {}'",
".",
"format",
"(",
"BOT_DEFINITION_FILENAME",
")",
",",
")",
"format_group",
".",
"add_argument",
"(",
"'-e'",
",",
"'--export'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"argparse",
".",
"SUPPRESS",
",",
"metavar",
"=",
"'botname'",
",",
"help",
"=",
"'Export bot definition as JSON to stdout'",
"' Defaults to reading the botname from the definition file: {}'",
".",
"format",
"(",
"BOT_DEFINITION_FILENAME",
")",
",",
")",
"format_group",
".",
"add_argument",
"(",
"'-d'",
",",
"'--delete'",
",",
"nargs",
"=",
"1",
",",
"default",
"=",
"argparse",
".",
"SUPPRESS",
",",
"metavar",
"=",
"'botname'",
",",
"help",
"=",
"'Deletes the bot passed as argument and its associated resources.'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"not",
"bool",
"(",
"vars",
"(",
"args",
")",
")",
":",
"parser",
".",
"print_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"args"
] | https://github.com/aws-samples/aws-lex-web-ui/blob/370f11286062957faf51448cb3bd93c5776be8e0/templates/custom-resources/lex-manager.py#L105-L142 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/unclosured/lib/python2.7/ftplib.py | python | FTP.size | (self, filename) | Retrieve the size of a file. | Retrieve the size of a file. | [
"Retrieve",
"the",
"size",
"of",
"a",
"file",
"."
] | def size(self, filename):
'''Retrieve the size of a file.'''
# The SIZE command is defined in RFC-3659
resp = self.sendcmd('SIZE ' + filename)
if resp[:3] == '213':
s = resp[3:].strip()
try:
return int(s)
except (OverflowError, ValueError):
return long(s) | [
"def",
"size",
"(",
"self",
",",
"filename",
")",
":",
"# The SIZE command is defined in RFC-3659",
"resp",
"=",
"self",
".",
"sendcmd",
"(",
"'SIZE '",
"+",
"filename",
")",
"if",
"resp",
"[",
":",
"3",
"]",
"==",
"'213'",
":",
"s",
"=",
"resp",
"[",
"3",
":",
"]",
".",
"strip",
"(",
")",
"try",
":",
"return",
"int",
"(",
"s",
")",
"except",
"(",
"OverflowError",
",",
"ValueError",
")",
":",
"return",
"long",
"(",
"s",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/ftplib.py#L545-L554 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _ValidateSourcesForMSVSProject | (spec, version) | Makes sure if duplicate basenames are not specified in the source list.
Arguments:
spec: The target dictionary containing the properties of the target.
version: The VisualStudioVersion object. | Makes sure if duplicate basenames are not specified in the source list. | [
"Makes",
"sure",
"if",
"duplicate",
"basenames",
"are",
"not",
"specified",
"in",
"the",
"source",
"list",
"."
] | def _ValidateSourcesForMSVSProject(spec, version):
"""Makes sure if duplicate basenames are not specified in the source list.
Arguments:
spec: The target dictionary containing the properties of the target.
version: The VisualStudioVersion object.
"""
# This validation should not be applied to MSVC2010 and later.
assert not version.UsesVcxproj()
# TODO: Check if MSVC allows this for loadable_module targets.
if spec.get('type', None) not in ('static_library', 'shared_library'):
return
sources = spec.get('sources', [])
basenames = {}
for source in sources:
name, ext = os.path.splitext(source)
is_compiled_file = ext in [
'.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S']
if not is_compiled_file:
continue
basename = os.path.basename(name) # Don't include extension.
basenames.setdefault(basename, []).append(source)
error = ''
for basename, files in basenames.iteritems():
if len(files) > 1:
error += ' %s: %s\n' % (basename, ' '.join(files))
if error:
print('static library %s has several files with the same basename:\n' %
spec['target_name'] + error + 'MSVC08 cannot handle that.')
raise GypError('Duplicate basenames in sources section, see list above') | [
"def",
"_ValidateSourcesForMSVSProject",
"(",
"spec",
",",
"version",
")",
":",
"# This validation should not be applied to MSVC2010 and later.",
"assert",
"not",
"version",
".",
"UsesVcxproj",
"(",
")",
"# TODO: Check if MSVC allows this for loadable_module targets.",
"if",
"spec",
".",
"get",
"(",
"'type'",
",",
"None",
")",
"not",
"in",
"(",
"'static_library'",
",",
"'shared_library'",
")",
":",
"return",
"sources",
"=",
"spec",
".",
"get",
"(",
"'sources'",
",",
"[",
"]",
")",
"basenames",
"=",
"{",
"}",
"for",
"source",
"in",
"sources",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"source",
")",
"is_compiled_file",
"=",
"ext",
"in",
"[",
"'.c'",
",",
"'.cc'",
",",
"'.cpp'",
",",
"'.cxx'",
",",
"'.m'",
",",
"'.mm'",
",",
"'.s'",
",",
"'.S'",
"]",
"if",
"not",
"is_compiled_file",
":",
"continue",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"name",
")",
"# Don't include extension.",
"basenames",
".",
"setdefault",
"(",
"basename",
",",
"[",
"]",
")",
".",
"append",
"(",
"source",
")",
"error",
"=",
"''",
"for",
"basename",
",",
"files",
"in",
"basenames",
".",
"iteritems",
"(",
")",
":",
"if",
"len",
"(",
"files",
")",
">",
"1",
":",
"error",
"+=",
"' %s: %s\\n'",
"%",
"(",
"basename",
",",
"' '",
".",
"join",
"(",
"files",
")",
")",
"if",
"error",
":",
"print",
"(",
"'static library %s has several files with the same basename:\\n'",
"%",
"spec",
"[",
"'target_name'",
"]",
"+",
"error",
"+",
"'MSVC08 cannot handle that.'",
")",
"raise",
"GypError",
"(",
"'Duplicate basenames in sources section, see list above'",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L947-L979 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/PythonTools/visualstudio_py_repl.py | python | ReplBackend.run_command | (self, command) | runs the specified command which is a string containing code | runs the specified command which is a string containing code | [
"runs",
"the",
"specified",
"command",
"which",
"is",
"a",
"string",
"containing",
"code"
] | def run_command(self, command):
"""runs the specified command which is a string containing code"""
raise NotImplementedError | [
"def",
"run_command",
"(",
"self",
",",
"command",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/PythonTools/visualstudio_py_repl.py#L469-L471 |
||
depjs/dep | cb8def92812d80b1fd8e5ffbbc1ae129a207fff6 | node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.GypPathToNinja | (self, path, env=None) | return os.path.normpath(os.path.join(self.build_to_base, path)) | Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|.
See the above discourse on path conversions. | Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|. | [
"Translate",
"a",
"gyp",
"path",
"to",
"a",
"ninja",
"path",
"optionally",
"expanding",
"environment",
"variable",
"references",
"in",
"|path|",
"with",
"|env|",
"."
] | def GypPathToNinja(self, path, env=None):
"""Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|.
See the above discourse on path conversions."""
if env:
if self.flavor == "mac":
path = gyp.xcode_emulation.ExpandEnvVars(path, env)
elif self.flavor == "win":
path = gyp.msvs_emulation.ExpandMacros(path, env)
if path.startswith("$!"):
expanded = self.ExpandSpecial(path)
if self.flavor == "win":
expanded = os.path.normpath(expanded)
return expanded
if "$|" in path:
path = self.ExpandSpecial(path)
assert "$" not in path, path
return os.path.normpath(os.path.join(self.build_to_base, path)) | [
"def",
"GypPathToNinja",
"(",
"self",
",",
"path",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
":",
"if",
"self",
".",
"flavor",
"==",
"\"mac\"",
":",
"path",
"=",
"gyp",
".",
"xcode_emulation",
".",
"ExpandEnvVars",
"(",
"path",
",",
"env",
")",
"elif",
"self",
".",
"flavor",
"==",
"\"win\"",
":",
"path",
"=",
"gyp",
".",
"msvs_emulation",
".",
"ExpandMacros",
"(",
"path",
",",
"env",
")",
"if",
"path",
".",
"startswith",
"(",
"\"$!\"",
")",
":",
"expanded",
"=",
"self",
".",
"ExpandSpecial",
"(",
"path",
")",
"if",
"self",
".",
"flavor",
"==",
"\"win\"",
":",
"expanded",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"expanded",
")",
"return",
"expanded",
"if",
"\"$|\"",
"in",
"path",
":",
"path",
"=",
"self",
".",
"ExpandSpecial",
"(",
"path",
")",
"assert",
"\"$\"",
"not",
"in",
"path",
",",
"path",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"build_to_base",
",",
"path",
")",
")"
] | https://github.com/depjs/dep/blob/cb8def92812d80b1fd8e5ffbbc1ae129a207fff6/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L304-L322 |
|
ipython-contrib/jupyter_contrib_nbextensions | a186b18efaa1f55fba64f08cd9d8bf85cba56d25 | src/jupyter_contrib_nbextensions/application.py | python | BaseContribNbextensionsApp._log_datefmt_default | (self) | return "%H:%M:%S" | Exclude date from timestamp. | Exclude date from timestamp. | [
"Exclude",
"date",
"from",
"timestamp",
"."
] | def _log_datefmt_default(self):
"""Exclude date from timestamp."""
return "%H:%M:%S" | [
"def",
"_log_datefmt_default",
"(",
"self",
")",
":",
"return",
"\"%H:%M:%S\""
] | https://github.com/ipython-contrib/jupyter_contrib_nbextensions/blob/a186b18efaa1f55fba64f08cd9d8bf85cba56d25/src/jupyter_contrib_nbextensions/application.py#L28-L30 |
|
ivendrov/order-embedding | 2057e6056a887ea00d304fc43a8a7e4810f4d669 | utils.py | python | ortho_weight | (ndim) | return u.astype('float32') | Orthogonal weight init, for recurrent layers | Orthogonal weight init, for recurrent layers | [
"Orthogonal",
"weight",
"init",
"for",
"recurrent",
"layers"
] | def ortho_weight(ndim):
"""
Orthogonal weight init, for recurrent layers
"""
W = numpy.random.randn(ndim, ndim)
u, s, v = numpy.linalg.svd(W)
return u.astype('float32') | [
"def",
"ortho_weight",
"(",
"ndim",
")",
":",
"W",
"=",
"numpy",
".",
"random",
".",
"randn",
"(",
"ndim",
",",
"ndim",
")",
"u",
",",
"s",
",",
"v",
"=",
"numpy",
".",
"linalg",
".",
"svd",
"(",
"W",
")",
"return",
"u",
".",
"astype",
"(",
"'float32'",
")"
] | https://github.com/ivendrov/order-embedding/blob/2057e6056a887ea00d304fc43a8a7e4810f4d669/utils.py#L61-L67 |
|
wtx358/wtxlog | 5e0dd09309ff98b26009a9eac48b01afd344cd99 | wtxlog/main/views.py | python | upload | () | return json.dumps(result) | 文件上传函数 | 文件上传函数 | [
"文件上传函数"
] | def upload():
''' 文件上传函数 '''
result = {"err": "", "msg": {"url": "", "localfile": ""}}
fname = ''
fext = ''
data = None
if request.method == 'POST' and 'filedata' in request.files:
# 传统上传模式,IE浏览器使用这种模式
fileobj = request.files['filedata']
result["msg"]["localfile"] = fileobj.filename
fname, fext = os.path.splitext(fileobj.filename)
data = fileobj.read()
elif 'CONTENT_DISPOSITION' in request.headers:
# HTML5上传模式,FIREFOX等默认使用此模式
pattern = re.compile(r"""\s.*?\s?filename\s*=\s*['|"]?([^\s'"]+).*?""", re.I)
_d = request.headers.get('CONTENT_DISPOSITION').encode('utf-8')
if urllib.quote(_d).count('%25') > 0:
_d = urllib.unquote(_d)
filenames = pattern.findall(_d)
if len(filenames) == 1:
result["msg"]["localfile"] = urllib.unquote(filenames[0])
fname, fext = os.path.splitext(filenames[0])
data = request.data
ONLINE = False
if ONLINE:
obj = SaveUploadFile(fext, data)
url = obj.save()
result["msg"]["url"] = '!%s' % url
else:
obj = SaveUploadFile(fext, data)
url = obj.save()
result["msg"]["url"] = '!%s' % url
pass
return json.dumps(result) | [
"def",
"upload",
"(",
")",
":",
"result",
"=",
"{",
"\"err\"",
":",
"\"\"",
",",
"\"msg\"",
":",
"{",
"\"url\"",
":",
"\"\"",
",",
"\"localfile\"",
":",
"\"\"",
"}",
"}",
"fname",
"=",
"''",
"fext",
"=",
"''",
"data",
"=",
"None",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"'filedata'",
"in",
"request",
".",
"files",
":",
"# 传统上传模式,IE浏览器使用这种模式",
"fileobj",
"=",
"request",
".",
"files",
"[",
"'filedata'",
"]",
"result",
"[",
"\"msg\"",
"]",
"[",
"\"localfile\"",
"]",
"=",
"fileobj",
".",
"filename",
"fname",
",",
"fext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fileobj",
".",
"filename",
")",
"data",
"=",
"fileobj",
".",
"read",
"(",
")",
"elif",
"'CONTENT_DISPOSITION'",
"in",
"request",
".",
"headers",
":",
"# HTML5上传模式,FIREFOX等默认使用此模式",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"\\s.*?\\s?filename\\s*=\\s*['|\"]?([^\\s'\"]+).*?\"\"\"",
",",
"re",
".",
"I",
")",
"_d",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'CONTENT_DISPOSITION'",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"urllib",
".",
"quote",
"(",
"_d",
")",
".",
"count",
"(",
"'%25'",
")",
">",
"0",
":",
"_d",
"=",
"urllib",
".",
"unquote",
"(",
"_d",
")",
"filenames",
"=",
"pattern",
".",
"findall",
"(",
"_d",
")",
"if",
"len",
"(",
"filenames",
")",
"==",
"1",
":",
"result",
"[",
"\"msg\"",
"]",
"[",
"\"localfile\"",
"]",
"=",
"urllib",
".",
"unquote",
"(",
"filenames",
"[",
"0",
"]",
")",
"fname",
",",
"fext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filenames",
"[",
"0",
"]",
")",
"data",
"=",
"request",
".",
"data",
"ONLINE",
"=",
"False",
"if",
"ONLINE",
":",
"obj",
"=",
"SaveUploadFile",
"(",
"fext",
",",
"data",
")",
"url",
"=",
"obj",
".",
"save",
"(",
")",
"result",
"[",
"\"msg\"",
"]",
"[",
"\"url\"",
"]",
"=",
"'!%s'",
"%",
"url",
"else",
":",
"obj",
"=",
"SaveUploadFile",
"(",
"fext",
",",
"data",
")",
"url",
"=",
"obj",
".",
"save",
"(",
")",
"result",
"[",
"\"msg\"",
"]",
"[",
"\"url\"",
"]",
"=",
"'!%s'",
"%",
"url",
"pass",
"return",
"json",
".",
"dumps",
"(",
"result",
")"
] | https://github.com/wtx358/wtxlog/blob/5e0dd09309ff98b26009a9eac48b01afd344cd99/wtxlog/main/views.py#L311-L348 |
|
liftoff/GateOne | 6ae1d01f7fe21e2703bdf982df7353e7bb81a500 | termio/termio.py | python | MultiplexPOSIXIOLoop._write | (self, chars) | Writes *chars* to `self.fd` (pretty straightforward). If IOError or
OSError exceptions are encountered, will run `terminate`. All other
exceptions are logged but no action will be taken. | Writes *chars* to `self.fd` (pretty straightforward). If IOError or
OSError exceptions are encountered, will run `terminate`. All other
exceptions are logged but no action will be taken. | [
"Writes",
"*",
"chars",
"*",
"to",
"self",
".",
"fd",
"(",
"pretty",
"straightforward",
")",
".",
"If",
"IOError",
"or",
"OSError",
"exceptions",
"are",
"encountered",
"will",
"run",
"terminate",
".",
"All",
"other",
"exceptions",
"are",
"logged",
"but",
"no",
"action",
"will",
"be",
"taken",
"."
] | def _write(self, chars):
"""
Writes *chars* to `self.fd` (pretty straightforward). If IOError or
OSError exceptions are encountered, will run `terminate`. All other
exceptions are logged but no action will be taken.
"""
#logging.debug("MultiplexPOSIXIOLoop._write(%s)" % repr(chars))
try:
with io.open(
self.fd, 'wt', encoding='UTF-8', closefd=False) as writer:
writer.write(chars)
if self.ratelimiter_engaged:
if u'\x03' in chars: # Ctrl-C
# This will force self._read() to discard the buffer
self.ctrl_c_pressed = True
# Reattach the fd so the user can continue immediately
self._reenable_output()
except OSError as e:
logging.error(_(
"Encountered error writing to terminal program: %s") % e)
if self.isalive():
self.terminate()
except IOError as e:
# We can safely ignore most of these... They tend to crop up when
# writing big chunks of data to dtach'd terminals.
if not 'raw write()' in e.message:
logging.error("write() exception: %s" % e)
except Exception as e:
logging.error("write() exception: %s" % e) | [
"def",
"_write",
"(",
"self",
",",
"chars",
")",
":",
"#logging.debug(\"MultiplexPOSIXIOLoop._write(%s)\" % repr(chars))",
"try",
":",
"with",
"io",
".",
"open",
"(",
"self",
".",
"fd",
",",
"'wt'",
",",
"encoding",
"=",
"'UTF-8'",
",",
"closefd",
"=",
"False",
")",
"as",
"writer",
":",
"writer",
".",
"write",
"(",
"chars",
")",
"if",
"self",
".",
"ratelimiter_engaged",
":",
"if",
"u'\\x03'",
"in",
"chars",
":",
"# Ctrl-C",
"# This will force self._read() to discard the buffer",
"self",
".",
"ctrl_c_pressed",
"=",
"True",
"# Reattach the fd so the user can continue immediately",
"self",
".",
"_reenable_output",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"_",
"(",
"\"Encountered error writing to terminal program: %s\"",
")",
"%",
"e",
")",
"if",
"self",
".",
"isalive",
"(",
")",
":",
"self",
".",
"terminate",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"# We can safely ignore most of these... They tend to crop up when",
"# writing big chunks of data to dtach'd terminals.",
"if",
"not",
"'raw write()'",
"in",
"e",
".",
"message",
":",
"logging",
".",
"error",
"(",
"\"write() exception: %s\"",
"%",
"e",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"write() exception: %s\"",
"%",
"e",
")"
] | https://github.com/liftoff/GateOne/blob/6ae1d01f7fe21e2703bdf982df7353e7bb81a500/termio/termio.py#L1750-L1778 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/unclosured/lib/python2.7/mailbox.py | python | Babyl.__setitem__ | (self, key, message) | Replace the keyed message; raise KeyError if it doesn't exist. | Replace the keyed message; raise KeyError if it doesn't exist. | [
"Replace",
"the",
"keyed",
"message",
";",
"raise",
"KeyError",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def __setitem__(self, key, message):
"""Replace the keyed message; raise KeyError if it doesn't exist."""
_singlefileMailbox.__setitem__(self, key, message)
if isinstance(message, BabylMessage):
self._labels[key] = message.get_labels() | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
":",
"_singlefileMailbox",
".",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
"if",
"isinstance",
"(",
"message",
",",
"BabylMessage",
")",
":",
"self",
".",
"_labels",
"[",
"key",
"]",
"=",
"message",
".",
"get_labels",
"(",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/mailbox.py#L1192-L1196 |
||
liftoff/GateOne | 6ae1d01f7fe21e2703bdf982df7353e7bb81a500 | termio/termio.py | python | MultiplexPOSIXIOLoop._read | (self, bytes=-1) | return result | Reads at most *bytes* from the incoming stream, writes the result to
the terminal emulator using `term_write`, and returns what was read.
If *bytes* is -1 (default) it will read `self.fd` until there's no more
output.
Returns the result of all that reading.
.. note:: Non-blocking. | Reads at most *bytes* from the incoming stream, writes the result to
the terminal emulator using `term_write`, and returns what was read.
If *bytes* is -1 (default) it will read `self.fd` until there's no more
output. | [
"Reads",
"at",
"most",
"*",
"bytes",
"*",
"from",
"the",
"incoming",
"stream",
"writes",
"the",
"result",
"to",
"the",
"terminal",
"emulator",
"using",
"term_write",
"and",
"returns",
"what",
"was",
"read",
".",
"If",
"*",
"bytes",
"*",
"is",
"-",
"1",
"(",
"default",
")",
"it",
"will",
"read",
"self",
".",
"fd",
"until",
"there",
"s",
"no",
"more",
"output",
"."
] | def _read(self, bytes=-1):
"""
Reads at most *bytes* from the incoming stream, writes the result to
the terminal emulator using `term_write`, and returns what was read.
If *bytes* is -1 (default) it will read `self.fd` until there's no more
output.
Returns the result of all that reading.
.. note:: Non-blocking.
"""
# Commented out because it can be really noisy. Uncomment only if you
# *really* need to debug this method.
#logging.debug("MultiplexPOSIXIOLoop._read()")
result = b""
def restore_capture_limit():
self.capture_limit = -1
self.restore_rate = None
try:
with io.open(self.fd, 'rb', closefd=False, buffering=0) as reader:
if bytes == -1:
# 2 seconds of blocking is too much.
timeout = timedelta(seconds=2)
loop_start = datetime.now()
if self.ctrl_c_pressed:
# If the user pressed Ctrl-C and the ratelimiter was
# engaged then we'd best discard the (possibly huge)
# buffer so we don't waste CPU cyles processing it.
reader.read(-1)
self.ctrl_c_pressed = False
return u'^C\n' # Let the user know what happened
if self.restore_rate:
# Need at least three seconds of inactivity to go back
# to unlimited reads
self.io_loop.remove_timeout(self.restore_rate)
self.restore_rate = self.io_loop.add_timeout(
timedelta(seconds=6), restore_capture_limit)
while True:
updated = reader.read(self.capture_limit)
if not updated:
break
result += updated
self.term_write(updated)
if self.ratelimiter_engaged or self.capture_ratelimiter:
break # Only allow one read per IOLoop loop
if self.capture_limit == 2048:
# Block for a little while: Enough to keep things
# moving but not fast enough to slow everyone else
# down
self._blocked_io_handler(wait=1000)
break
if datetime.now() - loop_start > timeout:
# Engage the rate limiter
if self.term.capture:
self.capture_ratelimiter = True
self.capture_limit = 65536
# Make sure we eventually get back to defaults:
self.io_loop.add_timeout(
timedelta(seconds=10),
restore_capture_limit)
# NOTE: The capture_ratelimiter doesn't remove
# self.fd from the IOLoop (that's the diff)
else:
# Set the capture limit to a smaller value so
# when we re-start output again the noisy
# program won't be able to take over again.
self.capture_limit = 2048
self.restore_rate = self.io_loop.add_timeout(
timedelta(seconds=6),
restore_capture_limit)
self._blocked_io_handler()
break
elif bytes:
result = reader.read(bytes)
self.term_write(result)
except IOError as e:
# IOErrors can happen when self.fd is closed before we finish
# reading from it. Not a big deal.
pass
except OSError as e:
logging.error("Got exception in read: %s" % repr(e))
# This can be useful in debugging:
#except Exception as e:
#import traceback
#logging.error(
#"Got unhandled exception in read (???): %s" % repr(e))
#traceback.print_exc(file=sys.stdout)
#if self.isalive():
#self.terminate()
if self.debug:
if result:
print("_read(): %s" % repr(result))
return result | [
"def",
"_read",
"(",
"self",
",",
"bytes",
"=",
"-",
"1",
")",
":",
"# Commented out because it can be really noisy. Uncomment only if you",
"# *really* need to debug this method.",
"#logging.debug(\"MultiplexPOSIXIOLoop._read()\")",
"result",
"=",
"b\"\"",
"def",
"restore_capture_limit",
"(",
")",
":",
"self",
".",
"capture_limit",
"=",
"-",
"1",
"self",
".",
"restore_rate",
"=",
"None",
"try",
":",
"with",
"io",
".",
"open",
"(",
"self",
".",
"fd",
",",
"'rb'",
",",
"closefd",
"=",
"False",
",",
"buffering",
"=",
"0",
")",
"as",
"reader",
":",
"if",
"bytes",
"==",
"-",
"1",
":",
"# 2 seconds of blocking is too much.",
"timeout",
"=",
"timedelta",
"(",
"seconds",
"=",
"2",
")",
"loop_start",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"self",
".",
"ctrl_c_pressed",
":",
"# If the user pressed Ctrl-C and the ratelimiter was",
"# engaged then we'd best discard the (possibly huge)",
"# buffer so we don't waste CPU cyles processing it.",
"reader",
".",
"read",
"(",
"-",
"1",
")",
"self",
".",
"ctrl_c_pressed",
"=",
"False",
"return",
"u'^C\\n'",
"# Let the user know what happened",
"if",
"self",
".",
"restore_rate",
":",
"# Need at least three seconds of inactivity to go back",
"# to unlimited reads",
"self",
".",
"io_loop",
".",
"remove_timeout",
"(",
"self",
".",
"restore_rate",
")",
"self",
".",
"restore_rate",
"=",
"self",
".",
"io_loop",
".",
"add_timeout",
"(",
"timedelta",
"(",
"seconds",
"=",
"6",
")",
",",
"restore_capture_limit",
")",
"while",
"True",
":",
"updated",
"=",
"reader",
".",
"read",
"(",
"self",
".",
"capture_limit",
")",
"if",
"not",
"updated",
":",
"break",
"result",
"+=",
"updated",
"self",
".",
"term_write",
"(",
"updated",
")",
"if",
"self",
".",
"ratelimiter_engaged",
"or",
"self",
".",
"capture_ratelimiter",
":",
"break",
"# Only allow one read per IOLoop loop",
"if",
"self",
".",
"capture_limit",
"==",
"2048",
":",
"# Block for a little while: Enough to keep things",
"# moving but not fast enough to slow everyone else",
"# down",
"self",
".",
"_blocked_io_handler",
"(",
"wait",
"=",
"1000",
")",
"break",
"if",
"datetime",
".",
"now",
"(",
")",
"-",
"loop_start",
">",
"timeout",
":",
"# Engage the rate limiter",
"if",
"self",
".",
"term",
".",
"capture",
":",
"self",
".",
"capture_ratelimiter",
"=",
"True",
"self",
".",
"capture_limit",
"=",
"65536",
"# Make sure we eventually get back to defaults:",
"self",
".",
"io_loop",
".",
"add_timeout",
"(",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
",",
"restore_capture_limit",
")",
"# NOTE: The capture_ratelimiter doesn't remove",
"# self.fd from the IOLoop (that's the diff)",
"else",
":",
"# Set the capture limit to a smaller value so",
"# when we re-start output again the noisy",
"# program won't be able to take over again.",
"self",
".",
"capture_limit",
"=",
"2048",
"self",
".",
"restore_rate",
"=",
"self",
".",
"io_loop",
".",
"add_timeout",
"(",
"timedelta",
"(",
"seconds",
"=",
"6",
")",
",",
"restore_capture_limit",
")",
"self",
".",
"_blocked_io_handler",
"(",
")",
"break",
"elif",
"bytes",
":",
"result",
"=",
"reader",
".",
"read",
"(",
"bytes",
")",
"self",
".",
"term_write",
"(",
"result",
")",
"except",
"IOError",
"as",
"e",
":",
"# IOErrors can happen when self.fd is closed before we finish",
"# reading from it. Not a big deal.",
"pass",
"except",
"OSError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"Got exception in read: %s\"",
"%",
"repr",
"(",
"e",
")",
")",
"# This can be useful in debugging:",
"#except Exception as e:",
"#import traceback",
"#logging.error(",
"#\"Got unhandled exception in read (???): %s\" % repr(e))",
"#traceback.print_exc(file=sys.stdout)",
"#if self.isalive():",
"#self.terminate()",
"if",
"self",
".",
"debug",
":",
"if",
"result",
":",
"print",
"(",
"\"_read(): %s\"",
"%",
"repr",
"(",
"result",
")",
")",
"return",
"result"
] | https://github.com/liftoff/GateOne/blob/6ae1d01f7fe21e2703bdf982df7353e7bb81a500/termio/termio.py#L1583-L1675 |
|
romanvm/django-tinymce4-lite | eef7af8ff6e9de844e14e89b084b86c4b2ba8eba | tinymce/views.py | python | spell_check | (request) | return JsonResponse(output, status=status) | Implements the TinyMCE 4 spellchecker protocol
:param request: Django http request with JSON-RPC payload from TinyMCE 4
containing a language code and a text to check for errors.
:type request: django.http.request.HttpRequest
:return: Django http response containing JSON-RPC payload
with spellcheck results for TinyMCE 4
:rtype: django.http.JsonResponse | Implements the TinyMCE 4 spellchecker protocol | [
"Implements",
"the",
"TinyMCE",
"4",
"spellchecker",
"protocol"
] | def spell_check(request):
"""
Implements the TinyMCE 4 spellchecker protocol
:param request: Django http request with JSON-RPC payload from TinyMCE 4
containing a language code and a text to check for errors.
:type request: django.http.request.HttpRequest
:return: Django http response containing JSON-RPC payload
with spellcheck results for TinyMCE 4
:rtype: django.http.JsonResponse
"""
data = json.loads(request.body.decode('utf-8'))
output = {'id': data['id']}
error = None
status = 200
try:
if data['params']['lang'] not in list_languages():
error = 'Missing {0} dictionary!'.format(data['params']['lang'])
raise LookupError(error)
spell_checker = checker.SpellChecker(data['params']['lang'])
spell_checker.set_text(strip_tags(data['params']['text']))
output['result'] = {spell_checker.word: spell_checker.suggest()
for err in spell_checker}
except NameError:
error = 'The pyenchant package is not installed!'
logger.exception(error)
except LookupError:
logger.exception(error)
except Exception:
error = 'Unknown error!'
logger.exception(error)
if error is not None:
output['error'] = error
status = 500
return JsonResponse(output, status=status) | [
"def",
"spell_check",
"(",
"request",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"output",
"=",
"{",
"'id'",
":",
"data",
"[",
"'id'",
"]",
"}",
"error",
"=",
"None",
"status",
"=",
"200",
"try",
":",
"if",
"data",
"[",
"'params'",
"]",
"[",
"'lang'",
"]",
"not",
"in",
"list_languages",
"(",
")",
":",
"error",
"=",
"'Missing {0} dictionary!'",
".",
"format",
"(",
"data",
"[",
"'params'",
"]",
"[",
"'lang'",
"]",
")",
"raise",
"LookupError",
"(",
"error",
")",
"spell_checker",
"=",
"checker",
".",
"SpellChecker",
"(",
"data",
"[",
"'params'",
"]",
"[",
"'lang'",
"]",
")",
"spell_checker",
".",
"set_text",
"(",
"strip_tags",
"(",
"data",
"[",
"'params'",
"]",
"[",
"'text'",
"]",
")",
")",
"output",
"[",
"'result'",
"]",
"=",
"{",
"spell_checker",
".",
"word",
":",
"spell_checker",
".",
"suggest",
"(",
")",
"for",
"err",
"in",
"spell_checker",
"}",
"except",
"NameError",
":",
"error",
"=",
"'The pyenchant package is not installed!'",
"logger",
".",
"exception",
"(",
"error",
")",
"except",
"LookupError",
":",
"logger",
".",
"exception",
"(",
"error",
")",
"except",
"Exception",
":",
"error",
"=",
"'Unknown error!'",
"logger",
".",
"exception",
"(",
"error",
")",
"if",
"error",
"is",
"not",
"None",
":",
"output",
"[",
"'error'",
"]",
"=",
"error",
"status",
"=",
"500",
"return",
"JsonResponse",
"(",
"output",
",",
"status",
"=",
"status",
")"
] | https://github.com/romanvm/django-tinymce4-lite/blob/eef7af8ff6e9de844e14e89b084b86c4b2ba8eba/tinymce/views.py#L25-L59 |
|
KevinFasusi/supplychainpy | 5bffccf9383045eace82ee1d21ca49e1ecdd7d22 | supplychainpy/bot/_controller.py | python | revenue_controller | (uri: str, direction: str = None, sku_id: str = None) | return tuple(result) | Retrieves SKUs which generate revenue.
Args:
uri (str): Database connection string.
direction (str): Indication of sort direction.
sku_id (str): SKU unique id.
Returns:
tuple: Result. | Retrieves SKUs which generate revenue. | [
"Retrieves",
"SKUs",
"which",
"generate",
"revenue",
"."
] | def revenue_controller(uri: str, direction: str = None, sku_id: str = None) -> tuple:
""" Retrieves SKUs which generate revenue.
Args:
uri (str): Database connection string.
direction (str): Indication of sort direction.
sku_id (str): SKU unique id.
Returns:
tuple: Result.
"""
meta = MetaData()
connection = engine(uri)
inventory_analysis = Table('inventory_analysis', meta, autoload=True, autoload_with=connection)
if direction == 'smallest':
skus = select([inventory_analysis.columns.sku_id, inventory_analysis.columns.revenue,
func.min(inventory_analysis.columns.revenue)])
else:
skus = select([inventory_analysis.columns.sku_id, inventory_analysis.columns.revenue,
func.max(inventory_analysis.columns.revenue)])
rp = connection.execute(skus)
result = []
sku_id = ""
for i in rp:
sku_id = str(i['sku_id'])
result.append((i['sku_id'], i['revenue']))
rp.close()
# print(sku_id)
msk_table = Table('master_sku_list', meta, autoload=True, autoload_with=connection)
skus = select([msk_table.columns.id, msk_table.columns.sku_id]).where(msk_table.columns.id == sku_id)
rp = connection.execute(skus)
for i in rp:
result.append(i['sku_id'])
rp.close()
return tuple(result) | [
"def",
"revenue_controller",
"(",
"uri",
":",
"str",
",",
"direction",
":",
"str",
"=",
"None",
",",
"sku_id",
":",
"str",
"=",
"None",
")",
"->",
"tuple",
":",
"meta",
"=",
"MetaData",
"(",
")",
"connection",
"=",
"engine",
"(",
"uri",
")",
"inventory_analysis",
"=",
"Table",
"(",
"'inventory_analysis'",
",",
"meta",
",",
"autoload",
"=",
"True",
",",
"autoload_with",
"=",
"connection",
")",
"if",
"direction",
"==",
"'smallest'",
":",
"skus",
"=",
"select",
"(",
"[",
"inventory_analysis",
".",
"columns",
".",
"sku_id",
",",
"inventory_analysis",
".",
"columns",
".",
"revenue",
",",
"func",
".",
"min",
"(",
"inventory_analysis",
".",
"columns",
".",
"revenue",
")",
"]",
")",
"else",
":",
"skus",
"=",
"select",
"(",
"[",
"inventory_analysis",
".",
"columns",
".",
"sku_id",
",",
"inventory_analysis",
".",
"columns",
".",
"revenue",
",",
"func",
".",
"max",
"(",
"inventory_analysis",
".",
"columns",
".",
"revenue",
")",
"]",
")",
"rp",
"=",
"connection",
".",
"execute",
"(",
"skus",
")",
"result",
"=",
"[",
"]",
"sku_id",
"=",
"\"\"",
"for",
"i",
"in",
"rp",
":",
"sku_id",
"=",
"str",
"(",
"i",
"[",
"'sku_id'",
"]",
")",
"result",
".",
"append",
"(",
"(",
"i",
"[",
"'sku_id'",
"]",
",",
"i",
"[",
"'revenue'",
"]",
")",
")",
"rp",
".",
"close",
"(",
")",
"# print(sku_id)",
"msk_table",
"=",
"Table",
"(",
"'master_sku_list'",
",",
"meta",
",",
"autoload",
"=",
"True",
",",
"autoload_with",
"=",
"connection",
")",
"skus",
"=",
"select",
"(",
"[",
"msk_table",
".",
"columns",
".",
"id",
",",
"msk_table",
".",
"columns",
".",
"sku_id",
"]",
")",
".",
"where",
"(",
"msk_table",
".",
"columns",
".",
"id",
"==",
"sku_id",
")",
"rp",
"=",
"connection",
".",
"execute",
"(",
"skus",
")",
"for",
"i",
"in",
"rp",
":",
"result",
".",
"append",
"(",
"i",
"[",
"'sku_id'",
"]",
")",
"rp",
".",
"close",
"(",
")",
"return",
"tuple",
"(",
"result",
")"
] | https://github.com/KevinFasusi/supplychainpy/blob/5bffccf9383045eace82ee1d21ca49e1ecdd7d22/supplychainpy/bot/_controller.py#L157-L195 |
|
fusionbox/django-widgy | e524e1c5bf14b056a4baf01298e39c0873d6130f | widgy/models/base.py | python | Content.valid_parent_of | (self, cls, obj=None) | return self.accepting_children | Given a content class, can it be _added_ as our child?
Note: this does not apply to _existing_ children (adoption) | Given a content class, can it be _added_ as our child?
Note: this does not apply to _existing_ children (adoption) | [
"Given",
"a",
"content",
"class",
"can",
"it",
"be",
"_added_",
"as",
"our",
"child?",
"Note",
":",
"this",
"does",
"not",
"apply",
"to",
"_existing_",
"children",
"(",
"adoption",
")"
] | def valid_parent_of(self, cls, obj=None):
"""
Given a content class, can it be _added_ as our child?
Note: this does not apply to _existing_ children (adoption)
"""
return self.accepting_children | [
"def",
"valid_parent_of",
"(",
"self",
",",
"cls",
",",
"obj",
"=",
"None",
")",
":",
"return",
"self",
".",
"accepting_children"
] | https://github.com/fusionbox/django-widgy/blob/e524e1c5bf14b056a4baf01298e39c0873d6130f/widgy/models/base.py#L587-L592 |
|
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | tools/inspector_protocol/jinja2/idtracking.py | python | FrameSymbolVisitor.visit_Name | (self, node, store_as_param=False, **kwargs) | All assignments to names go through this function. | All assignments to names go through this function. | [
"All",
"assignments",
"to",
"names",
"go",
"through",
"this",
"function",
"."
] | def visit_Name(self, node, store_as_param=False, **kwargs):
"""All assignments to names go through this function."""
if store_as_param or node.ctx == 'param':
self.symbols.declare_parameter(node.name)
elif node.ctx == 'store':
self.symbols.store(node.name)
elif node.ctx == 'load':
self.symbols.load(node.name) | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
",",
"store_as_param",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"store_as_param",
"or",
"node",
".",
"ctx",
"==",
"'param'",
":",
"self",
".",
"symbols",
".",
"declare_parameter",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'store'",
":",
"self",
".",
"symbols",
".",
"store",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'load'",
":",
"self",
".",
"symbols",
".",
"load",
"(",
"node",
".",
"name",
")"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/tools/inspector_protocol/jinja2/idtracking.py#L209-L216 |
||
microsoft/pai | b3c196f3355a265322c3804cabfcea82cbffa2db | src/job-exporter/src/collector.py | python | ContainerCollector.infer_service_name | (cls, container_name) | return None | try to infer service name from container_name, if it's container not belongs
to pai service, will return None | try to infer service name from container_name, if it's container not belongs
to pai service, will return None | [
"try",
"to",
"infer",
"service",
"name",
"from",
"container_name",
"if",
"it",
"s",
"container",
"not",
"belongs",
"to",
"pai",
"service",
"will",
"return",
"None"
] | def infer_service_name(cls, container_name):
""" try to infer service name from container_name, if it's container not belongs
to pai service, will return None """
if container_name.startswith("k8s_POD_"):
# this is empty container created by k8s for pod
return None
# TODO speed this up, since this is O(n^2)
for service_name in cls.pai_services:
if container_name.startswith(service_name):
return service_name[4:] # remove "k8s_" prefix
return None | [
"def",
"infer_service_name",
"(",
"cls",
",",
"container_name",
")",
":",
"if",
"container_name",
".",
"startswith",
"(",
"\"k8s_POD_\"",
")",
":",
"# this is empty container created by k8s for pod",
"return",
"None",
"# TODO speed this up, since this is O(n^2)",
"for",
"service_name",
"in",
"cls",
".",
"pai_services",
":",
"if",
"container_name",
".",
"startswith",
"(",
"service_name",
")",
":",
"return",
"service_name",
"[",
"4",
":",
"]",
"# remove \"k8s_\" prefix",
"return",
"None"
] | https://github.com/microsoft/pai/blob/b3c196f3355a265322c3804cabfcea82cbffa2db/src/job-exporter/src/collector.py#L649-L661 |
|
xl7dev/BurpSuite | d1d4bd4981a87f2f4c0c9744ad7c476336c813da | Extender/Sqlmap/lib/core/common.py | python | paramToDict | (place, parameters=None) | return testableParameters | Split the parameters into names and values, check if these parameters
are within the testable parameters and return in a dictionary. | Split the parameters into names and values, check if these parameters
are within the testable parameters and return in a dictionary. | [
"Split",
"the",
"parameters",
"into",
"names",
"and",
"values",
"check",
"if",
"these",
"parameters",
"are",
"within",
"the",
"testable",
"parameters",
"and",
"return",
"in",
"a",
"dictionary",
"."
] | def paramToDict(place, parameters=None):
"""
Split the parameters into names and values, check if these parameters
are within the testable parameters and return in a dictionary.
"""
testableParameters = OrderedDict()
if place in conf.parameters and not parameters:
parameters = conf.parameters[place]
parameters = parameters.replace(", ", ",")
parameters = re.sub(r"&(\w{1,4});", r"%s\g<1>%s" % (PARAMETER_AMP_MARKER, PARAMETER_SEMICOLON_MARKER), parameters)
if place == PLACE.COOKIE:
splitParams = parameters.split(conf.cookieDel or DEFAULT_COOKIE_DELIMITER)
else:
splitParams = parameters.split(conf.paramDel or DEFAULT_GET_POST_DELIMITER)
for element in splitParams:
element = re.sub(r"%s(.+?)%s" % (PARAMETER_AMP_MARKER, PARAMETER_SEMICOLON_MARKER), r"&\g<1>;", element)
parts = element.split("=")
if len(parts) >= 2:
parameter = urldecode(parts[0].replace(" ", ""))
if not parameter:
continue
if conf.paramDel and conf.paramDel == '\n':
parts[-1] = parts[-1].rstrip()
condition = not conf.testParameter
condition |= parameter in conf.testParameter
condition |= place == PLACE.COOKIE and len(intersect((PLACE.COOKIE,), conf.testParameter, True)) > 0
if condition:
testableParameters[parameter] = "=".join(parts[1:])
if not conf.multipleTargets and not (conf.csrfToken and parameter == conf.csrfToken):
_ = urldecode(testableParameters[parameter], convall=True)
if (_.strip(DUMMY_SQL_INJECTION_CHARS) != _\
or re.search(r'\A9{3,}', _) or re.search(DUMMY_USER_INJECTION, _))\
and not parameter.upper().startswith(GOOGLE_ANALYTICS_COOKIE_PREFIX):
warnMsg = "it appears that you have provided tainted parameter values "
warnMsg += "('%s') with most probably leftover " % element
warnMsg += "chars/statements from manual SQL injection test(s). "
warnMsg += "Please, always use only valid parameter values "
warnMsg += "so sqlmap could be able to run properly"
logger.warn(warnMsg)
message = "are you sure you want to continue? [y/N] "
test = readInput(message, default="N")
if test[0] not in ("y", "Y"):
raise SqlmapSilentQuitException
elif not _:
warnMsg = "provided value for parameter '%s' is empty. " % parameter
warnMsg += "Please, always use only valid parameter values "
warnMsg += "so sqlmap could be able to run properly"
logger.warn(warnMsg)
if conf.testParameter and not testableParameters:
paramStr = ", ".join(test for test in conf.testParameter)
if len(conf.testParameter) > 1:
warnMsg = "provided parameters '%s' " % paramStr
warnMsg += "are not inside the %s" % place
logger.warn(warnMsg)
else:
parameter = conf.testParameter[0]
if not intersect(USER_AGENT_ALIASES + REFERER_ALIASES + HOST_ALIASES, parameter, True):
debugMsg = "provided parameter '%s' " % paramStr
debugMsg += "is not inside the %s" % place
logger.debug(debugMsg)
elif len(conf.testParameter) != len(testableParameters.keys()):
for parameter in conf.testParameter:
if parameter not in testableParameters:
debugMsg = "provided parameter '%s' " % parameter
debugMsg += "is not inside the %s" % place
logger.debug(debugMsg)
if testableParameters:
for parameter, value in testableParameters.items():
if value and not value.isdigit():
for encoding in ("hex", "base64"):
try:
decoded = value.decode(encoding)
if len(decoded) > MIN_ENCODED_LEN_CHECK and all(_ in string.printable for _ in decoded):
warnMsg = "provided parameter '%s' " % parameter
warnMsg += "seems to be '%s' encoded" % encoding
logger.warn(warnMsg)
break
except:
pass
return testableParameters | [
"def",
"paramToDict",
"(",
"place",
",",
"parameters",
"=",
"None",
")",
":",
"testableParameters",
"=",
"OrderedDict",
"(",
")",
"if",
"place",
"in",
"conf",
".",
"parameters",
"and",
"not",
"parameters",
":",
"parameters",
"=",
"conf",
".",
"parameters",
"[",
"place",
"]",
"parameters",
"=",
"parameters",
".",
"replace",
"(",
"\", \"",
",",
"\",\"",
")",
"parameters",
"=",
"re",
".",
"sub",
"(",
"r\"&(\\w{1,4});\"",
",",
"r\"%s\\g<1>%s\"",
"%",
"(",
"PARAMETER_AMP_MARKER",
",",
"PARAMETER_SEMICOLON_MARKER",
")",
",",
"parameters",
")",
"if",
"place",
"==",
"PLACE",
".",
"COOKIE",
":",
"splitParams",
"=",
"parameters",
".",
"split",
"(",
"conf",
".",
"cookieDel",
"or",
"DEFAULT_COOKIE_DELIMITER",
")",
"else",
":",
"splitParams",
"=",
"parameters",
".",
"split",
"(",
"conf",
".",
"paramDel",
"or",
"DEFAULT_GET_POST_DELIMITER",
")",
"for",
"element",
"in",
"splitParams",
":",
"element",
"=",
"re",
".",
"sub",
"(",
"r\"%s(.+?)%s\"",
"%",
"(",
"PARAMETER_AMP_MARKER",
",",
"PARAMETER_SEMICOLON_MARKER",
")",
",",
"r\"&\\g<1>;\"",
",",
"element",
")",
"parts",
"=",
"element",
".",
"split",
"(",
"\"=\"",
")",
"if",
"len",
"(",
"parts",
")",
">=",
"2",
":",
"parameter",
"=",
"urldecode",
"(",
"parts",
"[",
"0",
"]",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
")",
"if",
"not",
"parameter",
":",
"continue",
"if",
"conf",
".",
"paramDel",
"and",
"conf",
".",
"paramDel",
"==",
"'\\n'",
":",
"parts",
"[",
"-",
"1",
"]",
"=",
"parts",
"[",
"-",
"1",
"]",
".",
"rstrip",
"(",
")",
"condition",
"=",
"not",
"conf",
".",
"testParameter",
"condition",
"|=",
"parameter",
"in",
"conf",
".",
"testParameter",
"condition",
"|=",
"place",
"==",
"PLACE",
".",
"COOKIE",
"and",
"len",
"(",
"intersect",
"(",
"(",
"PLACE",
".",
"COOKIE",
",",
")",
",",
"conf",
".",
"testParameter",
",",
"True",
")",
")",
">",
"0",
"if",
"condition",
":",
"testableParameters",
"[",
"parameter",
"]",
"=",
"\"=\"",
".",
"join",
"(",
"parts",
"[",
"1",
":",
"]",
")",
"if",
"not",
"conf",
".",
"multipleTargets",
"and",
"not",
"(",
"conf",
".",
"csrfToken",
"and",
"parameter",
"==",
"conf",
".",
"csrfToken",
")",
":",
"_",
"=",
"urldecode",
"(",
"testableParameters",
"[",
"parameter",
"]",
",",
"convall",
"=",
"True",
")",
"if",
"(",
"_",
".",
"strip",
"(",
"DUMMY_SQL_INJECTION_CHARS",
")",
"!=",
"_",
"or",
"re",
".",
"search",
"(",
"r'\\A9{3,}'",
",",
"_",
")",
"or",
"re",
".",
"search",
"(",
"DUMMY_USER_INJECTION",
",",
"_",
")",
")",
"and",
"not",
"parameter",
".",
"upper",
"(",
")",
".",
"startswith",
"(",
"GOOGLE_ANALYTICS_COOKIE_PREFIX",
")",
":",
"warnMsg",
"=",
"\"it appears that you have provided tainted parameter values \"",
"warnMsg",
"+=",
"\"('%s') with most probably leftover \"",
"%",
"element",
"warnMsg",
"+=",
"\"chars/statements from manual SQL injection test(s). \"",
"warnMsg",
"+=",
"\"Please, always use only valid parameter values \"",
"warnMsg",
"+=",
"\"so sqlmap could be able to run properly\"",
"logger",
".",
"warn",
"(",
"warnMsg",
")",
"message",
"=",
"\"are you sure you want to continue? [y/N] \"",
"test",
"=",
"readInput",
"(",
"message",
",",
"default",
"=",
"\"N\"",
")",
"if",
"test",
"[",
"0",
"]",
"not",
"in",
"(",
"\"y\"",
",",
"\"Y\"",
")",
":",
"raise",
"SqlmapSilentQuitException",
"elif",
"not",
"_",
":",
"warnMsg",
"=",
"\"provided value for parameter '%s' is empty. \"",
"%",
"parameter",
"warnMsg",
"+=",
"\"Please, always use only valid parameter values \"",
"warnMsg",
"+=",
"\"so sqlmap could be able to run properly\"",
"logger",
".",
"warn",
"(",
"warnMsg",
")",
"if",
"conf",
".",
"testParameter",
"and",
"not",
"testableParameters",
":",
"paramStr",
"=",
"\", \"",
".",
"join",
"(",
"test",
"for",
"test",
"in",
"conf",
".",
"testParameter",
")",
"if",
"len",
"(",
"conf",
".",
"testParameter",
")",
">",
"1",
":",
"warnMsg",
"=",
"\"provided parameters '%s' \"",
"%",
"paramStr",
"warnMsg",
"+=",
"\"are not inside the %s\"",
"%",
"place",
"logger",
".",
"warn",
"(",
"warnMsg",
")",
"else",
":",
"parameter",
"=",
"conf",
".",
"testParameter",
"[",
"0",
"]",
"if",
"not",
"intersect",
"(",
"USER_AGENT_ALIASES",
"+",
"REFERER_ALIASES",
"+",
"HOST_ALIASES",
",",
"parameter",
",",
"True",
")",
":",
"debugMsg",
"=",
"\"provided parameter '%s' \"",
"%",
"paramStr",
"debugMsg",
"+=",
"\"is not inside the %s\"",
"%",
"place",
"logger",
".",
"debug",
"(",
"debugMsg",
")",
"elif",
"len",
"(",
"conf",
".",
"testParameter",
")",
"!=",
"len",
"(",
"testableParameters",
".",
"keys",
"(",
")",
")",
":",
"for",
"parameter",
"in",
"conf",
".",
"testParameter",
":",
"if",
"parameter",
"not",
"in",
"testableParameters",
":",
"debugMsg",
"=",
"\"provided parameter '%s' \"",
"%",
"parameter",
"debugMsg",
"+=",
"\"is not inside the %s\"",
"%",
"place",
"logger",
".",
"debug",
"(",
"debugMsg",
")",
"if",
"testableParameters",
":",
"for",
"parameter",
",",
"value",
"in",
"testableParameters",
".",
"items",
"(",
")",
":",
"if",
"value",
"and",
"not",
"value",
".",
"isdigit",
"(",
")",
":",
"for",
"encoding",
"in",
"(",
"\"hex\"",
",",
"\"base64\"",
")",
":",
"try",
":",
"decoded",
"=",
"value",
".",
"decode",
"(",
"encoding",
")",
"if",
"len",
"(",
"decoded",
")",
">",
"MIN_ENCODED_LEN_CHECK",
"and",
"all",
"(",
"_",
"in",
"string",
".",
"printable",
"for",
"_",
"in",
"decoded",
")",
":",
"warnMsg",
"=",
"\"provided parameter '%s' \"",
"%",
"parameter",
"warnMsg",
"+=",
"\"seems to be '%s' encoded\"",
"%",
"encoding",
"logger",
".",
"warn",
"(",
"warnMsg",
")",
"break",
"except",
":",
"pass",
"return",
"testableParameters"
] | https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/lib/core/common.py#L537-L632 |
|
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.AdjustIncludeDirs | (self, include_dirs, config) | return [self.ConvertVSMacros(p, config=config) for p in includes] | Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar. | Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar. | [
"Updates",
"include_dirs",
"to",
"expand",
"VS",
"specific",
"paths",
"and",
"adds",
"the",
"system",
"include",
"dirs",
"used",
"for",
"platform",
"SDK",
"and",
"similar",
"."
] | def AdjustIncludeDirs(self, include_dirs, config):
"""Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar."""
config = self._TargetConfig(config)
includes = include_dirs + self.msvs_system_include_dirs[config]
includes.extend(self._Setting(
('VCCLCompilerTool', 'AdditionalIncludeDirectories'), config, default=[]))
return [self.ConvertVSMacros(p, config=config) for p in includes] | [
"def",
"AdjustIncludeDirs",
"(",
"self",
",",
"include_dirs",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"includes",
"=",
"include_dirs",
"+",
"self",
".",
"msvs_system_include_dirs",
"[",
"config",
"]",
"includes",
".",
"extend",
"(",
"self",
".",
"_Setting",
"(",
"(",
"'VCCLCompilerTool'",
",",
"'AdditionalIncludeDirectories'",
")",
",",
"config",
",",
"default",
"=",
"[",
"]",
")",
")",
"return",
"[",
"self",
".",
"ConvertVSMacros",
"(",
"p",
",",
"config",
"=",
"config",
")",
"for",
"p",
"in",
"includes",
"]"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L332-L339 |
|
Opentrons/opentrons | 466e0567065d8773a81c25cd1b5c7998e00adf2c | api/src/opentrons/hardware_control/pipette.py | python | Pipette.working_volume | (self, tip_volume: float) | The working volume is the current tip max volume | The working volume is the current tip max volume | [
"The",
"working",
"volume",
"is",
"the",
"current",
"tip",
"max",
"volume"
] | def working_volume(self, tip_volume: float):
"""The working volume is the current tip max volume"""
self._working_volume = min(self.config.max_volume, tip_volume) | [
"def",
"working_volume",
"(",
"self",
",",
"tip_volume",
":",
"float",
")",
":",
"self",
".",
"_working_volume",
"=",
"min",
"(",
"self",
".",
"config",
".",
"max_volume",
",",
"tip_volume",
")"
] | https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/src/opentrons/hardware_control/pipette.py#L238-L240 |
||
phith0n/Minos | 1c98fb367121df1e8b8e7a20ea7de391df583e8f | extends/torndsession/session.py | python | SessionManager.expires | (self) | return self._expires | The session object lifetime on server.
this property could not be used to cookie expires setting. | The session object lifetime on server.
this property could not be used to cookie expires setting. | [
"The",
"session",
"object",
"lifetime",
"on",
"server",
".",
"this",
"property",
"could",
"not",
"be",
"used",
"to",
"cookie",
"expires",
"setting",
"."
] | def expires(self):
"""
The session object lifetime on server.
this property could not be used to cookie expires setting.
"""
if not hasattr(self, '_expires'):
self.__init_session_object()
return self._expires | [
"def",
"expires",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_expires'",
")",
":",
"self",
".",
"__init_session_object",
"(",
")",
"return",
"self",
".",
"_expires"
] | https://github.com/phith0n/Minos/blob/1c98fb367121df1e8b8e7a20ea7de391df583e8f/extends/torndsession/session.py#L213-L220 |
|
patrickfuller/jgraph | 7297450f26ae8cba21914668a5aaa755de8aa14d | python/notebook.py | python | draw | (data, size=(600, 400), node_size=2.0, edge_size=0.25,
default_node_color=0x5bc0de, default_edge_color=0xaaaaaa, z=100,
shader='basic', optimize=True, directed=True, display_html=True,
show_save=False) | Draws an interactive 3D visualization of the inputted graph.
Args:
data: Either an adjacency list of tuples (ie. [(1,2),...]) or object
size: (Optional) Dimensions of visualization, in pixels
node_size: (Optional) Defaults to 2.0
edge_size: (Optional) Defaults to 0.25
default_node_color: (Optional) If loading data without specified
'color' properties, this will be used. Default is 0x5bc0de
default_edge_color: (Optional) If loading data without specified
'color' properties, this will be used. Default is 0xaaaaaa
z: (Optional) Starting z position of the camera. Default is 100.
shader: (Optional) Specifies shading algorithm to use. Can be 'toon',
'basic', 'phong', or 'lambert'. Default is 'basic'.
optimize: (Optional) Runs a force-directed layout algorithm on the
graph. Default True.
directed: (Optional) Includes arrows on edges to indicate direction.
Default True.
display_html: If True (default), embed the html in a IPython display.
If False, return the html as a string.
show_save: If True, displays a save icon for rendering graph as an
image.
Inputting an adjacency list into `data` results in a 'default' graph type.
For more customization, use the more expressive object format. | Draws an interactive 3D visualization of the inputted graph. | [
"Draws",
"an",
"interactive",
"3D",
"visualization",
"of",
"the",
"inputted",
"graph",
"."
] | def draw(data, size=(600, 400), node_size=2.0, edge_size=0.25,
default_node_color=0x5bc0de, default_edge_color=0xaaaaaa, z=100,
shader='basic', optimize=True, directed=True, display_html=True,
show_save=False):
"""Draws an interactive 3D visualization of the inputted graph.
Args:
data: Either an adjacency list of tuples (ie. [(1,2),...]) or object
size: (Optional) Dimensions of visualization, in pixels
node_size: (Optional) Defaults to 2.0
edge_size: (Optional) Defaults to 0.25
default_node_color: (Optional) If loading data without specified
'color' properties, this will be used. Default is 0x5bc0de
default_edge_color: (Optional) If loading data without specified
'color' properties, this will be used. Default is 0xaaaaaa
z: (Optional) Starting z position of the camera. Default is 100.
shader: (Optional) Specifies shading algorithm to use. Can be 'toon',
'basic', 'phong', or 'lambert'. Default is 'basic'.
optimize: (Optional) Runs a force-directed layout algorithm on the
graph. Default True.
directed: (Optional) Includes arrows on edges to indicate direction.
Default True.
display_html: If True (default), embed the html in a IPython display.
If False, return the html as a string.
show_save: If True, displays a save icon for rendering graph as an
image.
Inputting an adjacency list into `data` results in a 'default' graph type.
For more customization, use the more expressive object format.
"""
# Catch errors on string-based input before getting js involved
shader_options = ['toon', 'basic', 'phong', 'lambert']
if shader not in shader_options:
raise Exception('Invalid shader! Please use one of: ' +
', '.join(shader_options))
if isinstance(default_edge_color, int):
default_edge_color = hex(default_edge_color)
if isinstance(default_node_color, int):
default_node_color = hex(default_node_color)
# Guess the input format and handle accordingly
if isinstance(data, list):
graph = json_formatter.dumps(generate(data, iterations=1))
elif isinstance(data, dict):
# Convert color hex to string for json handling
for node_key in data['nodes']:
node = data['nodes'][node_key]
if 'color' in node and isinstance(node['color'], int):
node['color'] = hex(node['color'])
for edge in data['edges']:
if 'color' in edge and isinstance(edge['color'], int):
edge['color'] = hex(edge['color'])
graph = json_formatter.dumps(data)
else:
# Support both files and strings
try:
with open(data) as in_file:
graph = in_file.read()
except:
graph = data
div_id = uuid.uuid4()
html = '''<div id="graph-%(id)s"></div>
<script type="text/javascript">
require.config({baseUrl: '/',
paths: {jgraph: ['%(local)s', '%(remote)s']}});
require(['jgraph'], function () {
var $d = $('#graph-%(id)s');
$d.width(%(w)d); $d.height(%(h)d);
$d.jgraph = jQuery.extend({}, jgraph);
$d.jgraph.create($d, {nodeSize: %(node_size)f,
edgeSize: %(edge_size)f,
defaultNodeColor: '%(node_color)s',
defaultEdgeColor: '%(edge_color)s',
shader: '%(shader)s',
z: %(z)d,
runOptimization: %(optimize)s,
directed: %(directed)s,
showSave: %(show_save)s});
$d.jgraph.draw(%(graph)s);
$d.resizable({
aspectRatio: %(w)d / %(h)d,
resize: function (evt, ui) {
$d.jgraph.renderer.setSize(ui.size.width,
ui.size.height);
}
});
});
</script>''' % dict(id=div_id, local=local_path[:-3],
remote=remote_path[:-3], w=size[0], h=size[1],
node_size=node_size, edge_size=edge_size,
node_color=default_node_color,
edge_color=default_edge_color, shader=shader,
z=z, graph=graph,
optimize='true' if optimize else 'false',
directed='true' if directed else 'false',
show_save='true' if show_save else 'false')
# Execute js and display the results in a div (see script for more)
if display_html:
display(HTML(html))
else:
return html | [
"def",
"draw",
"(",
"data",
",",
"size",
"=",
"(",
"600",
",",
"400",
")",
",",
"node_size",
"=",
"2.0",
",",
"edge_size",
"=",
"0.25",
",",
"default_node_color",
"=",
"0x5bc0de",
",",
"default_edge_color",
"=",
"0xaaaaaa",
",",
"z",
"=",
"100",
",",
"shader",
"=",
"'basic'",
",",
"optimize",
"=",
"True",
",",
"directed",
"=",
"True",
",",
"display_html",
"=",
"True",
",",
"show_save",
"=",
"False",
")",
":",
"# Catch errors on string-based input before getting js involved",
"shader_options",
"=",
"[",
"'toon'",
",",
"'basic'",
",",
"'phong'",
",",
"'lambert'",
"]",
"if",
"shader",
"not",
"in",
"shader_options",
":",
"raise",
"Exception",
"(",
"'Invalid shader! Please use one of: '",
"+",
"', '",
".",
"join",
"(",
"shader_options",
")",
")",
"if",
"isinstance",
"(",
"default_edge_color",
",",
"int",
")",
":",
"default_edge_color",
"=",
"hex",
"(",
"default_edge_color",
")",
"if",
"isinstance",
"(",
"default_node_color",
",",
"int",
")",
":",
"default_node_color",
"=",
"hex",
"(",
"default_node_color",
")",
"# Guess the input format and handle accordingly",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"graph",
"=",
"json_formatter",
".",
"dumps",
"(",
"generate",
"(",
"data",
",",
"iterations",
"=",
"1",
")",
")",
"elif",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"# Convert color hex to string for json handling",
"for",
"node_key",
"in",
"data",
"[",
"'nodes'",
"]",
":",
"node",
"=",
"data",
"[",
"'nodes'",
"]",
"[",
"node_key",
"]",
"if",
"'color'",
"in",
"node",
"and",
"isinstance",
"(",
"node",
"[",
"'color'",
"]",
",",
"int",
")",
":",
"node",
"[",
"'color'",
"]",
"=",
"hex",
"(",
"node",
"[",
"'color'",
"]",
")",
"for",
"edge",
"in",
"data",
"[",
"'edges'",
"]",
":",
"if",
"'color'",
"in",
"edge",
"and",
"isinstance",
"(",
"edge",
"[",
"'color'",
"]",
",",
"int",
")",
":",
"edge",
"[",
"'color'",
"]",
"=",
"hex",
"(",
"edge",
"[",
"'color'",
"]",
")",
"graph",
"=",
"json_formatter",
".",
"dumps",
"(",
"data",
")",
"else",
":",
"# Support both files and strings",
"try",
":",
"with",
"open",
"(",
"data",
")",
"as",
"in_file",
":",
"graph",
"=",
"in_file",
".",
"read",
"(",
")",
"except",
":",
"graph",
"=",
"data",
"div_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
"html",
"=",
"'''<div id=\"graph-%(id)s\"></div>\n <script type=\"text/javascript\">\n require.config({baseUrl: '/',\n paths: {jgraph: ['%(local)s', '%(remote)s']}});\n require(['jgraph'], function () {\n var $d = $('#graph-%(id)s');\n $d.width(%(w)d); $d.height(%(h)d);\n $d.jgraph = jQuery.extend({}, jgraph);\n $d.jgraph.create($d, {nodeSize: %(node_size)f,\n edgeSize: %(edge_size)f,\n defaultNodeColor: '%(node_color)s',\n defaultEdgeColor: '%(edge_color)s',\n shader: '%(shader)s',\n z: %(z)d,\n runOptimization: %(optimize)s,\n directed: %(directed)s,\n showSave: %(show_save)s});\n $d.jgraph.draw(%(graph)s);\n\n $d.resizable({\n aspectRatio: %(w)d / %(h)d,\n resize: function (evt, ui) {\n $d.jgraph.renderer.setSize(ui.size.width,\n ui.size.height);\n }\n });\n });\n </script>'''",
"%",
"dict",
"(",
"id",
"=",
"div_id",
",",
"local",
"=",
"local_path",
"[",
":",
"-",
"3",
"]",
",",
"remote",
"=",
"remote_path",
"[",
":",
"-",
"3",
"]",
",",
"w",
"=",
"size",
"[",
"0",
"]",
",",
"h",
"=",
"size",
"[",
"1",
"]",
",",
"node_size",
"=",
"node_size",
",",
"edge_size",
"=",
"edge_size",
",",
"node_color",
"=",
"default_node_color",
",",
"edge_color",
"=",
"default_edge_color",
",",
"shader",
"=",
"shader",
",",
"z",
"=",
"z",
",",
"graph",
"=",
"graph",
",",
"optimize",
"=",
"'true'",
"if",
"optimize",
"else",
"'false'",
",",
"directed",
"=",
"'true'",
"if",
"directed",
"else",
"'false'",
",",
"show_save",
"=",
"'true'",
"if",
"show_save",
"else",
"'false'",
")",
"# Execute js and display the results in a div (see script for more)",
"if",
"display_html",
":",
"display",
"(",
"HTML",
"(",
"html",
")",
")",
"else",
":",
"return",
"html"
] | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/notebook.py#L29-L133 |
||
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_validateRelation.py | python | checkSameKeys | (a , b) | return same | Checks if the two lists contain
the same values | Checks if the two lists contain
the same values | [
"Checks",
"if",
"the",
"two",
"lists",
"contain",
"the",
"same",
"values"
] | def checkSameKeys(a , b):
"""
Checks if the two lists contain
the same values
"""
same = 1
for ka in a:
if not ka in b:
same = 0
for kb in b:
if not kb in a:
same = 0
return same | [
"def",
"checkSameKeys",
"(",
"a",
",",
"b",
")",
":",
"same",
"=",
"1",
"for",
"ka",
"in",
"a",
":",
"if",
"not",
"ka",
"in",
"b",
":",
"same",
"=",
"0",
"for",
"kb",
"in",
"b",
":",
"if",
"not",
"kb",
"in",
"a",
":",
"same",
"=",
"0",
"return",
"same"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_validateRelation.py#L25-L37 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/compiler/visitor.py | python | ASTVisitor.preorder | (self, tree, visitor, *args) | Do preorder walk of tree using visitor | Do preorder walk of tree using visitor | [
"Do",
"preorder",
"walk",
"of",
"tree",
"using",
"visitor"
] | def preorder(self, tree, visitor, *args):
"""Do preorder walk of tree using visitor"""
self.visitor = visitor
visitor.visit = self.dispatch
self.dispatch(tree, *args) | [
"def",
"preorder",
"(",
"self",
",",
"tree",
",",
"visitor",
",",
"*",
"args",
")",
":",
"self",
".",
"visitor",
"=",
"visitor",
"visitor",
".",
"visit",
"=",
"self",
".",
"dispatch",
"self",
".",
"dispatch",
"(",
"tree",
",",
"*",
"args",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/compiler/visitor.py#L59-L63 |
||
enkimute/ganja.js | db26a33e34190f1578881a34f4e5bd467907ba87 | codegen/python/mink.py | python | MINK.Involute | (a) | return MINK.fromarray(res) | MINK.Involute
Main involution | MINK.Involute
Main involution | [
"MINK",
".",
"Involute",
"Main",
"involution"
] | def Involute(a):
"""MINK.Involute
Main involution
"""
res = a.mvec.copy()
res[0]=a[0]
res[1]=-a[1]
res[2]=-a[2]
res[3]=a[3]
return MINK.fromarray(res) | [
"def",
"Involute",
"(",
"a",
")",
":",
"res",
"=",
"a",
".",
"mvec",
".",
"copy",
"(",
")",
"res",
"[",
"0",
"]",
"=",
"a",
"[",
"0",
"]",
"res",
"[",
"1",
"]",
"=",
"-",
"a",
"[",
"1",
"]",
"res",
"[",
"2",
"]",
"=",
"-",
"a",
"[",
"2",
"]",
"res",
"[",
"3",
"]",
"=",
"a",
"[",
"3",
"]",
"return",
"MINK",
".",
"fromarray",
"(",
"res",
")"
] | https://github.com/enkimute/ganja.js/blob/db26a33e34190f1578881a34f4e5bd467907ba87/codegen/python/mink.py#L95-L105 |
|
nodejs/node-convergence-archive | e11fe0c2777561827cdb7207d46b0917ef3c42a7 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py | python | OrderedDict.setdefault | (self, key, default=None) | return default | od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od | od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od | [
"od",
".",
"setdefault",
"(",
"k",
"[",
"d",
"]",
")",
"-",
">",
"od",
".",
"get",
"(",
"k",
"d",
")",
"also",
"set",
"od",
"[",
"k",
"]",
"=",
"d",
"if",
"k",
"not",
"in",
"od"
] | def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default | [
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
":",
"return",
"self",
"[",
"key",
"]",
"self",
"[",
"key",
"]",
"=",
"default",
"return",
"default"
] | https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L219-L224 |
|
facebookarchive/nuclide | 2a2a0a642d136768b7d2a6d35a652dc5fb77d70a | modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/fixer_util.py | python | find_root | (node) | return node | Find the top level namespace. | Find the top level namespace. | [
"Find",
"the",
"top",
"level",
"namespace",
"."
] | def find_root(node):
"""Find the top level namespace."""
# Scamper up to the top level namespace
while node.type != syms.file_input:
node = node.parent
if not node:
raise ValueError("root found before file_input node was found.")
return node | [
"def",
"find_root",
"(",
"node",
")",
":",
"# Scamper up to the top level namespace",
"while",
"node",
".",
"type",
"!=",
"syms",
".",
"file_input",
":",
"node",
"=",
"node",
".",
"parent",
"if",
"not",
"node",
":",
"raise",
"ValueError",
"(",
"\"root found before file_input node was found.\"",
")",
"return",
"node"
] | 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/lib2to3/lib2to3/fixer_util.py#L273-L280 |
|
opentraveldata/geobases | e9ef3708155cb320684aa710a11d5a228a7d80c0 | GeoBaseMain.py | python | scan_coords | (u_input, geob, verbose) | This function tries to interpret the main
argument as either coordinates (lat, lng) or
a key like ORY. | This function tries to interpret the main
argument as either coordinates (lat, lng) or
a key like ORY. | [
"This",
"function",
"tries",
"to",
"interpret",
"the",
"main",
"argument",
"as",
"either",
"coordinates",
"(",
"lat",
"lng",
")",
"or",
"a",
"key",
"like",
"ORY",
"."
] | def scan_coords(u_input, geob, verbose):
"""
This function tries to interpret the main
argument as either coordinates (lat, lng) or
a key like ORY.
"""
# First we try input a direct key
if u_input in geob:
coords = geob.getLocation(u_input)
if coords is None:
error('geocode_unknown', u_input)
return coords
# Then we try input as geocode
try:
free_geo = u_input.strip('()')
for char in '\\', '"', "'":
free_geo = free_geo.replace(char, '')
for sep in '^', ';', ',':
free_geo = free_geo.replace(sep, ' ')
coords = tuple(float(l) for l in free_geo.split())
except ValueError:
pass
else:
if len(coords) == 2 and \
-90 <= coords[0] <= 90 and \
-180 <= coords[1] <= 180:
if verbose:
print 'Geocode recognized: (%.3f, %.3f)' % coords
return coords
error('geocode_format', u_input)
# All cases failed
warn('key', u_input, geob.data, geob.loaded)
exit(1) | [
"def",
"scan_coords",
"(",
"u_input",
",",
"geob",
",",
"verbose",
")",
":",
"# First we try input a direct key",
"if",
"u_input",
"in",
"geob",
":",
"coords",
"=",
"geob",
".",
"getLocation",
"(",
"u_input",
")",
"if",
"coords",
"is",
"None",
":",
"error",
"(",
"'geocode_unknown'",
",",
"u_input",
")",
"return",
"coords",
"# Then we try input as geocode",
"try",
":",
"free_geo",
"=",
"u_input",
".",
"strip",
"(",
"'()'",
")",
"for",
"char",
"in",
"'\\\\'",
",",
"'\"'",
",",
"\"'\"",
":",
"free_geo",
"=",
"free_geo",
".",
"replace",
"(",
"char",
",",
"''",
")",
"for",
"sep",
"in",
"'^'",
",",
"';'",
",",
"','",
":",
"free_geo",
"=",
"free_geo",
".",
"replace",
"(",
"sep",
",",
"' '",
")",
"coords",
"=",
"tuple",
"(",
"float",
"(",
"l",
")",
"for",
"l",
"in",
"free_geo",
".",
"split",
"(",
")",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"if",
"len",
"(",
"coords",
")",
"==",
"2",
"and",
"-",
"90",
"<=",
"coords",
"[",
"0",
"]",
"<=",
"90",
"and",
"-",
"180",
"<=",
"coords",
"[",
"1",
"]",
"<=",
"180",
":",
"if",
"verbose",
":",
"print",
"'Geocode recognized: (%.3f, %.3f)'",
"%",
"coords",
"return",
"coords",
"error",
"(",
"'geocode_format'",
",",
"u_input",
")",
"# All cases failed",
"warn",
"(",
"'key'",
",",
"u_input",
",",
"geob",
".",
"data",
",",
"geob",
".",
"loaded",
")",
"exit",
"(",
"1",
")"
] | https://github.com/opentraveldata/geobases/blob/e9ef3708155cb320684aa710a11d5a228a7d80c0/GeoBaseMain.py#L583-L626 |
||
harvard-lil/perma | c54ff21b3eee931f5094a7654fdddc9ad90fc29c | perma_web/fabfile/dev.py | python | read_playback_tests | (*filepaths) | Aggregate files from the test_playbacks() task and report count for each type of error. | Aggregate files from the test_playbacks() task and report count for each type of error. | [
"Aggregate",
"files",
"from",
"the",
"test_playbacks",
"()",
"task",
"and",
"report",
"count",
"for",
"each",
"type",
"of",
"error",
"."
] | def read_playback_tests(*filepaths):
"""
Aggregate files from the test_playbacks() task and report count for each type of error.
"""
from collections import defaultdict
errs = defaultdict(list)
prefixes = [
"'ascii' codec can't encode character",
"No Captures found for:",
"'ascii' codec can't decode byte",
"Self Redirect:",
"No such file or directory:",
"u'",
"Skipping Already Failed",
"cdx format"
]
for filepath in filepaths:
for line in open(filepath):
parts = line.strip().split("\t", 2)
if len(parts) < 3:
continue
key = parts[2]
for prefix in prefixes:
if prefix in key:
key = prefix
break
errs[key].append(parts)
err_count = 0
for err_type, sub_errs in errs.items():
err_count += len(sub_errs)
print(f"{err_type}: {len(sub_errs)}")
print("Total:", err_count) | [
"def",
"read_playback_tests",
"(",
"*",
"filepaths",
")",
":",
"from",
"collections",
"import",
"defaultdict",
"errs",
"=",
"defaultdict",
"(",
"list",
")",
"prefixes",
"=",
"[",
"\"'ascii' codec can't encode character\"",
",",
"\"No Captures found for:\"",
",",
"\"'ascii' codec can't decode byte\"",
",",
"\"Self Redirect:\"",
",",
"\"No such file or directory:\"",
",",
"\"u'\"",
",",
"\"Skipping Already Failed\"",
",",
"\"cdx format\"",
"]",
"for",
"filepath",
"in",
"filepaths",
":",
"for",
"line",
"in",
"open",
"(",
"filepath",
")",
":",
"parts",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
",",
"2",
")",
"if",
"len",
"(",
"parts",
")",
"<",
"3",
":",
"continue",
"key",
"=",
"parts",
"[",
"2",
"]",
"for",
"prefix",
"in",
"prefixes",
":",
"if",
"prefix",
"in",
"key",
":",
"key",
"=",
"prefix",
"break",
"errs",
"[",
"key",
"]",
".",
"append",
"(",
"parts",
")",
"err_count",
"=",
"0",
"for",
"err_type",
",",
"sub_errs",
"in",
"errs",
".",
"items",
"(",
")",
":",
"err_count",
"+=",
"len",
"(",
"sub_errs",
")",
"print",
"(",
"f\"{err_type}: {len(sub_errs)}\"",
")",
"print",
"(",
"\"Total:\"",
",",
"err_count",
")"
] | https://github.com/harvard-lil/perma/blob/c54ff21b3eee931f5094a7654fdddc9ad90fc29c/perma_web/fabfile/dev.py#L469-L501 |
||
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | src/tactic/ui/cgapp/checkin_wdg.py | python | AssetCheckinWdg.get_checkin | (self) | return widget | the button which initiates the checkin | the button which initiates the checkin | [
"the",
"button",
"which",
"initiates",
"the",
"checkin"
] | def get_checkin(self):
'''the button which initiates the checkin'''
# create the button with the javascript function
widget = Widget()
#button = TextBtnWdg(label=self.PUBLISH_BUTTON, size='large', width='100', side_padding='20', vert_offset='-5')
button = ActionButtonWdg(title=self.PUBLISH_BUTTON, tip='Publish the selected assets')
button.add_style('margin-bottom: 10px')
#button.get_top_el().add_class('smaller')
hidden = HiddenWdg(self.PUBLISH_BUTTON, '')
button.add( hidden )
'''
status_sel = SelectWdg('checkin_status', label='Status: ')
status_sel.set_option('setting', 'checkin_status')
status_sel.set_persist_on_submit()
status_sel.add_empty_option('-- Checkin Status --')
widget.add(status_sel)
'''
widget.add(button)
# custom defined
server_cbk = "pyasm.prod.web.AssetCheckinCbk"
#TODO: make other Publish Buttons call their own handle_input function
exec( Common.get_import_from_class_path(server_cbk) )
exec( "%s.handle_input(button, self.search_type, self.texture_search_type)" % server_cbk)
return widget | [
"def",
"get_checkin",
"(",
"self",
")",
":",
"# create the button with the javascript function",
"widget",
"=",
"Widget",
"(",
")",
"#button = TextBtnWdg(label=self.PUBLISH_BUTTON, size='large', width='100', side_padding='20', vert_offset='-5')",
"button",
"=",
"ActionButtonWdg",
"(",
"title",
"=",
"self",
".",
"PUBLISH_BUTTON",
",",
"tip",
"=",
"'Publish the selected assets'",
")",
"button",
".",
"add_style",
"(",
"'margin-bottom: 10px'",
")",
"#button.get_top_el().add_class('smaller')",
"hidden",
"=",
"HiddenWdg",
"(",
"self",
".",
"PUBLISH_BUTTON",
",",
"''",
")",
"button",
".",
"add",
"(",
"hidden",
")",
"'''\n status_sel = SelectWdg('checkin_status', label='Status: ')\n status_sel.set_option('setting', 'checkin_status')\n status_sel.set_persist_on_submit()\n status_sel.add_empty_option('-- Checkin Status --')\n widget.add(status_sel)\n '''",
"widget",
".",
"add",
"(",
"button",
")",
"# custom defined ",
"server_cbk",
"=",
"\"pyasm.prod.web.AssetCheckinCbk\"",
"#TODO: make other Publish Buttons call their own handle_input function",
"exec",
"(",
"Common",
".",
"get_import_from_class_path",
"(",
"server_cbk",
")",
")",
"exec",
"(",
"\"%s.handle_input(button, self.search_type, self.texture_search_type)\"",
"%",
"server_cbk",
")",
"return",
"widget"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/tactic/ui/cgapp/checkin_wdg.py#L909-L935 |
|
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Backup/20170602095117/mdpopups/st3/mdpopups/__init__.py | python | scope2style | (view, scope, selected=False, explicit_background=False) | return style | Convert the scope to a style. | Convert the scope to a style. | [
"Convert",
"the",
"scope",
"to",
"a",
"style",
"."
] | def scope2style(view, scope, selected=False, explicit_background=False):
"""Convert the scope to a style."""
style = {
'color': None,
'background': None,
'style': ''
}
obj = _get_scheme(view)[0]
style_obj = obj.guess_style(scope, selected, explicit_background)
style['color'] = style_obj.fg_simulated
style['background'] = style_obj.bg_simulated
style['style'] = style_obj.style
return style | [
"def",
"scope2style",
"(",
"view",
",",
"scope",
",",
"selected",
"=",
"False",
",",
"explicit_background",
"=",
"False",
")",
":",
"style",
"=",
"{",
"'color'",
":",
"None",
",",
"'background'",
":",
"None",
",",
"'style'",
":",
"''",
"}",
"obj",
"=",
"_get_scheme",
"(",
"view",
")",
"[",
"0",
"]",
"style_obj",
"=",
"obj",
".",
"guess_style",
"(",
"scope",
",",
"selected",
",",
"explicit_background",
")",
"style",
"[",
"'color'",
"]",
"=",
"style_obj",
".",
"fg_simulated",
"style",
"[",
"'background'",
"]",
"=",
"style_obj",
".",
"bg_simulated",
"style",
"[",
"'style'",
"]",
"=",
"style_obj",
".",
"style",
"return",
"style"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Backup/20170602095117/mdpopups/st3/mdpopups/__init__.py#L493-L506 |
|
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 | LeafPattern.__init__ | (self, type=None, content=None, name=None) | Initializer. Takes optional type, content, and name.
The type, if given must be a token type (< 256). If not given,
this matches any *leaf* node; the content may still be required.
The content, if given, must be a string.
If a name is given, the matching node is stored in the results
dict under that key. | Initializer. Takes optional type, content, and name. | [
"Initializer",
".",
"Takes",
"optional",
"type",
"content",
"and",
"name",
"."
] | def __init__(self, type=None, content=None, name=None):
"""
Initializer. Takes optional type, content, and name.
The type, if given must be a token type (< 256). If not given,
this matches any *leaf* node; the content may still be required.
The content, if given, must be a string.
If a name is given, the matching node is stored in the results
dict under that key.
"""
if type is not None:
assert 0 <= type < 256, type
if content is not None:
assert isinstance(content, basestring), repr(content)
self.type = type
self.content = content
self.name = name | [
"def",
"__init__",
"(",
"self",
",",
"type",
"=",
"None",
",",
"content",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"type",
"is",
"not",
"None",
":",
"assert",
"0",
"<=",
"type",
"<",
"256",
",",
"type",
"if",
"content",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"content",
",",
"basestring",
")",
",",
"repr",
"(",
"content",
")",
"self",
".",
"type",
"=",
"type",
"self",
".",
"content",
"=",
"content",
"self",
".",
"name",
"=",
"name"
] | 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#L536-L554 |
||
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py | python | OrderedDict.viewvalues | (self) | return ValuesView(self) | od.viewvalues() -> an object providing a view on od's values | od.viewvalues() -> an object providing a view on od's values | [
"od",
".",
"viewvalues",
"()",
"-",
">",
"an",
"object",
"providing",
"a",
"view",
"on",
"od",
"s",
"values"
] | def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self) | [
"def",
"viewvalues",
"(",
"self",
")",
":",
"return",
"ValuesView",
"(",
"self",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L282-L284 |
|
xl7dev/BurpSuite | d1d4bd4981a87f2f4c0c9744ad7c476336c813da | Extender/PT-Manager/XlsxWriter-0.7.3/xlsxwriter/chartsheet.py | python | Chartsheet.protect | (self, password='', options=None) | Set the password and protection options of the worksheet.
Args:
password: An optional password string.
options: A dictionary of worksheet objects to protect.
Returns:
Nothing. | Set the password and protection options of the worksheet. | [
"Set",
"the",
"password",
"and",
"protection",
"options",
"of",
"the",
"worksheet",
"."
] | def protect(self, password='', options=None):
"""
Set the password and protection options of the worksheet.
Args:
password: An optional password string.
options: A dictionary of worksheet objects to protect.
Returns:
Nothing.
"""
# Overridden from parent worksheet class.
if self.chart:
self.chart.protection = True
else:
self.protection = True
if not options:
options = {}
options = options.copy()
options['sheet'] = False
options['content'] = True
options['scenarios'] = True
# Call the parent method.
super(Chartsheet, self).protect(password, options) | [
"def",
"protect",
"(",
"self",
",",
"password",
"=",
"''",
",",
"options",
"=",
"None",
")",
":",
"# Overridden from parent worksheet class.",
"if",
"self",
".",
"chart",
":",
"self",
".",
"chart",
".",
"protection",
"=",
"True",
"else",
":",
"self",
".",
"protection",
"=",
"True",
"if",
"not",
"options",
":",
"options",
"=",
"{",
"}",
"options",
"=",
"options",
".",
"copy",
"(",
")",
"options",
"[",
"'sheet'",
"]",
"=",
"False",
"options",
"[",
"'content'",
"]",
"=",
"True",
"options",
"[",
"'scenarios'",
"]",
"=",
"True",
"# Call the parent method.",
"super",
"(",
"Chartsheet",
",",
"self",
")",
".",
"protect",
"(",
"password",
",",
"options",
")"
] | https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/PT-Manager/XlsxWriter-0.7.3/xlsxwriter/chartsheet.py#L55-L83 |
||
defunctzombie/libuv.js | 04a76a470dfdcad14ea8f19b6f215f205a9214f8 | tools/gyp/pylib/gyp/generator/msvs.py | python | _GenerateMSBuildRulePropsFile | (props_path, msbuild_rules) | Generate the .props file. | Generate the .props file. | [
"Generate",
"the",
".",
"props",
"file",
"."
] | def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules):
"""Generate the .props file."""
content = ['Project',
{'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'}]
for rule in msbuild_rules:
content.extend([
['PropertyGroup',
{'Condition': "'$(%s)' == '' and '$(%s)' == '' and "
"'$(ConfigurationType)' != 'Makefile'" % (rule.before_targets,
rule.after_targets)
},
[rule.before_targets, 'Midl'],
[rule.after_targets, 'CustomBuild'],
],
['PropertyGroup',
[rule.depends_on,
{'Condition': "'$(ConfigurationType)' != 'Makefile'"},
'_SelectedFiles;$(%s)' % rule.depends_on
],
],
['ItemDefinitionGroup',
[rule.rule_name,
['CommandLineTemplate', rule.command],
['Outputs', rule.outputs],
['ExecutionDescription', rule.description],
['AdditionalDependencies', rule.additional_dependencies],
],
]
])
easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True) | [
"def",
"_GenerateMSBuildRulePropsFile",
"(",
"props_path",
",",
"msbuild_rules",
")",
":",
"content",
"=",
"[",
"'Project'",
",",
"{",
"'xmlns'",
":",
"'http://schemas.microsoft.com/developer/msbuild/2003'",
"}",
"]",
"for",
"rule",
"in",
"msbuild_rules",
":",
"content",
".",
"extend",
"(",
"[",
"[",
"'PropertyGroup'",
",",
"{",
"'Condition'",
":",
"\"'$(%s)' == '' and '$(%s)' == '' and \"",
"\"'$(ConfigurationType)' != 'Makefile'\"",
"%",
"(",
"rule",
".",
"before_targets",
",",
"rule",
".",
"after_targets",
")",
"}",
",",
"[",
"rule",
".",
"before_targets",
",",
"'Midl'",
"]",
",",
"[",
"rule",
".",
"after_targets",
",",
"'CustomBuild'",
"]",
",",
"]",
",",
"[",
"'PropertyGroup'",
",",
"[",
"rule",
".",
"depends_on",
",",
"{",
"'Condition'",
":",
"\"'$(ConfigurationType)' != 'Makefile'\"",
"}",
",",
"'_SelectedFiles;$(%s)'",
"%",
"rule",
".",
"depends_on",
"]",
",",
"]",
",",
"[",
"'ItemDefinitionGroup'",
",",
"[",
"rule",
".",
"rule_name",
",",
"[",
"'CommandLineTemplate'",
",",
"rule",
".",
"command",
"]",
",",
"[",
"'Outputs'",
",",
"rule",
".",
"outputs",
"]",
",",
"[",
"'ExecutionDescription'",
",",
"rule",
".",
"description",
"]",
",",
"[",
"'AdditionalDependencies'",
",",
"rule",
".",
"additional_dependencies",
"]",
",",
"]",
",",
"]",
"]",
")",
"easy_xml",
".",
"WriteXmlIfChanged",
"(",
"content",
",",
"props_path",
",",
"pretty",
"=",
"True",
",",
"win32",
"=",
"True",
")"
] | https://github.com/defunctzombie/libuv.js/blob/04a76a470dfdcad14ea8f19b6f215f205a9214f8/tools/gyp/pylib/gyp/generator/msvs.py#L2115-L2144 |
||
googlearchive/ChromeWebLab | 60f964b3f283c15704b7a04b7bb50cb15791e2e4 | Sketchbots/sw/labqueue/lask/core/model.py | python | LabDataContainer.__get_new | (cls, *args, **kwargs) | return LabDataContainer(
random_block=random.random(),
**kwargs
) | This is a convenience method for constructing a new LabDataContainer which
has a random block assigned. | This is a convenience method for constructing a new LabDataContainer which
has a random block assigned. | [
"This",
"is",
"a",
"convenience",
"method",
"for",
"constructing",
"a",
"new",
"LabDataContainer",
"which",
"has",
"a",
"random",
"block",
"assigned",
"."
] | def __get_new(cls, *args, **kwargs):
"""This is a convenience method for constructing a new LabDataContainer which
has a random block assigned.
"""
# all new objects use the latest version of the model
kwargs['model_version_used'] = LabDataContainer.LATEST_MODEL_VERSION
if 'random_block' in kwargs:
del kwargs['random_block']
return LabDataContainer(
random_block=random.random(),
**kwargs
) | [
"def",
"__get_new",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# all new objects use the latest version of the model",
"kwargs",
"[",
"'model_version_used'",
"]",
"=",
"LabDataContainer",
".",
"LATEST_MODEL_VERSION",
"if",
"'random_block'",
"in",
"kwargs",
":",
"del",
"kwargs",
"[",
"'random_block'",
"]",
"return",
"LabDataContainer",
"(",
"random_block",
"=",
"random",
".",
"random",
"(",
")",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/googlearchive/ChromeWebLab/blob/60f964b3f283c15704b7a04b7bb50cb15791e2e4/Sketchbots/sw/labqueue/lask/core/model.py#L2478-L2490 |
|
jxcore/jxcore | b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410 | tools/gyp/pylib/gyp/generator/msvs.py | python | _GetMSVSConfigurationType | (spec, build_file) | return config_type | Returns the configuration type for this project.
It's a number defined by Microsoft. May raise an exception.
Args:
spec: The target dictionary containing the properties of the target.
build_file: The path of the gyp file.
Returns:
An integer, the configuration type. | Returns the configuration type for this project. | [
"Returns",
"the",
"configuration",
"type",
"for",
"this",
"project",
"."
] | def _GetMSVSConfigurationType(spec, build_file):
"""Returns the configuration type for this project.
It's a number defined by Microsoft. May raise an exception.
Args:
spec: The target dictionary containing the properties of the target.
build_file: The path of the gyp file.
Returns:
An integer, the configuration type.
"""
try:
config_type = {
'executable': '1', # .exe
'shared_library': '2', # .dll
'loadable_module': '2', # .dll
'static_library': '4', # .lib
'none': '10', # Utility type
}[spec['type']]
except KeyError:
if spec.get('type'):
raise GypError('Target type %s is not a valid target type for '
'target %s in %s.' %
(spec['type'], spec['target_name'], build_file))
else:
raise GypError('Missing type field for target %s in %s.' %
(spec['target_name'], build_file))
return config_type | [
"def",
"_GetMSVSConfigurationType",
"(",
"spec",
",",
"build_file",
")",
":",
"try",
":",
"config_type",
"=",
"{",
"'executable'",
":",
"'1'",
",",
"# .exe",
"'shared_library'",
":",
"'2'",
",",
"# .dll",
"'loadable_module'",
":",
"'2'",
",",
"# .dll",
"'static_library'",
":",
"'4'",
",",
"# .lib",
"'none'",
":",
"'10'",
",",
"# Utility type",
"}",
"[",
"spec",
"[",
"'type'",
"]",
"]",
"except",
"KeyError",
":",
"if",
"spec",
".",
"get",
"(",
"'type'",
")",
":",
"raise",
"GypError",
"(",
"'Target type %s is not a valid target type for '",
"'target %s in %s.'",
"%",
"(",
"spec",
"[",
"'type'",
"]",
",",
"spec",
"[",
"'target_name'",
"]",
",",
"build_file",
")",
")",
"else",
":",
"raise",
"GypError",
"(",
"'Missing type field for target %s in %s.'",
"%",
"(",
"spec",
"[",
"'target_name'",
"]",
",",
"build_file",
")",
")",
"return",
"config_type"
] | https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/tools/gyp/pylib/gyp/generator/msvs.py#L1058-L1085 |
|
pinterest/pinball | c54a206cf6e3dbadb056c189f741d75828c02f98 | pinball/persistence/store.py | python | Store.initialize | (self) | return | Initialize the token store. | Initialize the token store. | [
"Initialize",
"the",
"token",
"store",
"."
] | def initialize(self):
"""Initialize the token store."""
return | [
"def",
"initialize",
"(",
"self",
")",
":",
"return"
] | https://github.com/pinterest/pinball/blob/c54a206cf6e3dbadb056c189f741d75828c02f98/pinball/persistence/store.py#L66-L68 |
|
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | src/pyasm/web/html_wdg.py | python | HtmlElement.set_attribute | (self, name, value) | Set an attribute of the html element | Set an attribute of the html element | [
"Set",
"an",
"attribute",
"of",
"the",
"html",
"element"
] | def set_attribute(self, name, value):
'''Set an attribute of the html element'''
self.set_attr(name, value) | [
"def",
"set_attribute",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"set_attr",
"(",
"name",
",",
"value",
")"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/pyasm/web/html_wdg.py#L207-L209 |
||
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | tools/gyp/pylib/gyp/generator/msvs.py | python | _GetMSBuildPropertyGroup | (spec, label, properties) | return [group] | Returns a PropertyGroup definition for the specified properties.
Arguments:
spec: The target project dict.
label: An optional label for the PropertyGroup.
properties: The dictionary to be converted. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true. | Returns a PropertyGroup definition for the specified properties. | [
"Returns",
"a",
"PropertyGroup",
"definition",
"for",
"the",
"specified",
"properties",
"."
] | def _GetMSBuildPropertyGroup(spec, label, properties):
"""Returns a PropertyGroup definition for the specified properties.
Arguments:
spec: The target project dict.
label: An optional label for the PropertyGroup.
properties: The dictionary to be converted. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true.
"""
group = ['PropertyGroup']
if label:
group.append({'Label': label})
num_configurations = len(spec['configurations'])
def GetEdges(node):
# Use a definition of edges such that user_of_variable -> used_varible.
# This happens to be easier in this case, since a variable's
# definition contains all variables it references in a single string.
edges = set()
for value in sorted(properties[node].keys()):
# Add to edges all $(...) references to variables.
#
# Variable references that refer to names not in properties are excluded
# These can exist for instance to refer built in definitions like
# $(SolutionDir).
#
# Self references are ignored. Self reference is used in a few places to
# append to the default value. I.e. PATH=$(PATH);other_path
edges.update(set([v for v in MSVS_VARIABLE_REFERENCE.findall(value)
if v in properties and v != node]))
return edges
properties_ordered = gyp.common.TopologicallySorted(
properties.keys(), GetEdges)
# Walk properties in the reverse of a topological sort on
# user_of_variable -> used_variable as this ensures variables are
# defined before they are used.
# NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
for name in reversed(properties_ordered):
values = properties[name]
for value, conditions in sorted(values.iteritems()):
if len(conditions) == num_configurations:
# If the value is the same all configurations,
# just add one unconditional entry.
group.append([name, value])
else:
for condition in conditions:
group.append([name, {'Condition': condition}, value])
return [group] | [
"def",
"_GetMSBuildPropertyGroup",
"(",
"spec",
",",
"label",
",",
"properties",
")",
":",
"group",
"=",
"[",
"'PropertyGroup'",
"]",
"if",
"label",
":",
"group",
".",
"append",
"(",
"{",
"'Label'",
":",
"label",
"}",
")",
"num_configurations",
"=",
"len",
"(",
"spec",
"[",
"'configurations'",
"]",
")",
"def",
"GetEdges",
"(",
"node",
")",
":",
"# Use a definition of edges such that user_of_variable -> used_varible.",
"# This happens to be easier in this case, since a variable's",
"# definition contains all variables it references in a single string.",
"edges",
"=",
"set",
"(",
")",
"for",
"value",
"in",
"sorted",
"(",
"properties",
"[",
"node",
"]",
".",
"keys",
"(",
")",
")",
":",
"# Add to edges all $(...) references to variables.",
"#",
"# Variable references that refer to names not in properties are excluded",
"# These can exist for instance to refer built in definitions like",
"# $(SolutionDir).",
"#",
"# Self references are ignored. Self reference is used in a few places to",
"# append to the default value. I.e. PATH=$(PATH);other_path",
"edges",
".",
"update",
"(",
"set",
"(",
"[",
"v",
"for",
"v",
"in",
"MSVS_VARIABLE_REFERENCE",
".",
"findall",
"(",
"value",
")",
"if",
"v",
"in",
"properties",
"and",
"v",
"!=",
"node",
"]",
")",
")",
"return",
"edges",
"properties_ordered",
"=",
"gyp",
".",
"common",
".",
"TopologicallySorted",
"(",
"properties",
".",
"keys",
"(",
")",
",",
"GetEdges",
")",
"# Walk properties in the reverse of a topological sort on",
"# user_of_variable -> used_variable as this ensures variables are",
"# defined before they are used.",
"# NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))",
"for",
"name",
"in",
"reversed",
"(",
"properties_ordered",
")",
":",
"values",
"=",
"properties",
"[",
"name",
"]",
"for",
"value",
",",
"conditions",
"in",
"sorted",
"(",
"values",
".",
"iteritems",
"(",
")",
")",
":",
"if",
"len",
"(",
"conditions",
")",
"==",
"num_configurations",
":",
"# If the value is the same all configurations,",
"# just add one unconditional entry.",
"group",
".",
"append",
"(",
"[",
"name",
",",
"value",
"]",
")",
"else",
":",
"for",
"condition",
"in",
"conditions",
":",
"group",
".",
"append",
"(",
"[",
"name",
",",
"{",
"'Condition'",
":",
"condition",
"}",
",",
"value",
"]",
")",
"return",
"[",
"group",
"]"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/gyp/pylib/gyp/generator/msvs.py#L2985-L3032 |
|
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | tools/inspector_protocol/jinja2/environment.py | python | Template.from_module_dict | (cls, environment, module_dict, globals) | return cls._from_namespace(environment, module_dict, globals) | Creates a template object from a module. This is used by the
module loader to create a template object.
.. versionadded:: 2.4 | Creates a template object from a module. This is used by the
module loader to create a template object. | [
"Creates",
"a",
"template",
"object",
"from",
"a",
"module",
".",
"This",
"is",
"used",
"by",
"the",
"module",
"loader",
"to",
"create",
"a",
"template",
"object",
"."
] | def from_module_dict(cls, environment, module_dict, globals):
"""Creates a template object from a module. This is used by the
module loader to create a template object.
.. versionadded:: 2.4
"""
return cls._from_namespace(environment, module_dict, globals) | [
"def",
"from_module_dict",
"(",
"cls",
",",
"environment",
",",
"module_dict",
",",
"globals",
")",
":",
"return",
"cls",
".",
"_from_namespace",
"(",
"environment",
",",
"module_dict",
",",
"globals",
")"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/tools/inspector_protocol/jinja2/environment.py#L962-L968 |
|
xtk/X | 04c1aa856664a8517d23aefd94c470d47130aead | lib/selenium/selenium/webdriver/support/select.py | python | Select.deselect_all | (self) | Clear all selected entries. This is only valid when the SELECT supports multiple selections.
throws NotImplementedError If the SELECT does not support multiple selections | Clear all selected entries. This is only valid when the SELECT supports multiple selections.
throws NotImplementedError If the SELECT does not support multiple selections | [
"Clear",
"all",
"selected",
"entries",
".",
"This",
"is",
"only",
"valid",
"when",
"the",
"SELECT",
"supports",
"multiple",
"selections",
".",
"throws",
"NotImplementedError",
"If",
"the",
"SELECT",
"does",
"not",
"support",
"multiple",
"selections"
] | def deselect_all(self):
"""Clear all selected entries. This is only valid when the SELECT supports multiple selections.
throws NotImplementedError If the SELECT does not support multiple selections
"""
if not self.is_multiple:
raise NotImplementedError("You may only deselect all options of a multi-select")
for opt in self.options:
self._unsetSelected(opt) | [
"def",
"deselect_all",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_multiple",
":",
"raise",
"NotImplementedError",
"(",
"\"You may only deselect all options of a multi-select\"",
")",
"for",
"opt",
"in",
"self",
".",
"options",
":",
"self",
".",
"_unsetSelected",
"(",
"opt",
")"
] | https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/selenium/selenium/webdriver/support/select.py#L138-L145 |
||
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | tools/gyp/pylib/gyp/MSVSProject.py | python | Writer.__init__ | (self, project_path, version, name, guid=None, platforms=None) | Initializes the project.
Args:
project_path: Path to the project file.
version: Format version to emit.
name: Name of the project.
guid: GUID to use for project, if not None.
platforms: Array of string, the supported platforms. If null, ['Win32'] | Initializes the project. | [
"Initializes",
"the",
"project",
"."
] | def __init__(self, project_path, version, name, guid=None, platforms=None):
"""Initializes the project.
Args:
project_path: Path to the project file.
version: Format version to emit.
name: Name of the project.
guid: GUID to use for project, if not None.
platforms: Array of string, the supported platforms. If null, ['Win32']
"""
self.project_path = project_path
self.version = version
self.name = name
self.guid = guid
# Default to Win32 for platforms.
if not platforms:
platforms = ['Win32']
# Initialize the specifications of the various sections.
self.platform_section = ['Platforms']
for platform in platforms:
self.platform_section.append(['Platform', {'Name': platform}])
self.tool_files_section = ['ToolFiles']
self.configurations_section = ['Configurations']
self.files_section = ['Files']
# Keep a dict keyed on filename to speed up access.
self.files_dict = dict() | [
"def",
"__init__",
"(",
"self",
",",
"project_path",
",",
"version",
",",
"name",
",",
"guid",
"=",
"None",
",",
"platforms",
"=",
"None",
")",
":",
"self",
".",
"project_path",
"=",
"project_path",
"self",
".",
"version",
"=",
"version",
"self",
".",
"name",
"=",
"name",
"self",
".",
"guid",
"=",
"guid",
"# Default to Win32 for platforms.",
"if",
"not",
"platforms",
":",
"platforms",
"=",
"[",
"'Win32'",
"]",
"# Initialize the specifications of the various sections.",
"self",
".",
"platform_section",
"=",
"[",
"'Platforms'",
"]",
"for",
"platform",
"in",
"platforms",
":",
"self",
".",
"platform_section",
".",
"append",
"(",
"[",
"'Platform'",
",",
"{",
"'Name'",
":",
"platform",
"}",
"]",
")",
"self",
".",
"tool_files_section",
"=",
"[",
"'ToolFiles'",
"]",
"self",
".",
"configurations_section",
"=",
"[",
"'Configurations'",
"]",
"self",
".",
"files_section",
"=",
"[",
"'Files'",
"]",
"# Keep a dict keyed on filename to speed up access.",
"self",
".",
"files_dict",
"=",
"dict",
"(",
")"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/gyp/pylib/gyp/MSVSProject.py#L54-L82 |
||
jeff1evesque/machine-learning | 4c54e36f8ebf6a0b481c8aca71a6b3b4010dd4ff | brain/session/base.py | python | Base.validate_premodel_settings | (self) | This method validates the provided settings (not the dataset), that
describe the session. | [] | def validate_premodel_settings(self):
'''
This method validates the provided settings (not the dataset), that
describe the session.
'''
settings = self.premodel_data['properties']
error = Validator().validate_settings(
self.premodel_data['properties'],
self.session_type
)
session_type = settings.get('session_type', None)
stream = settings.get('stream', None)
if stream == 'True' and session_type in ['data_add', 'data_append']:
location = settings['session_name']
else:
location = session_type
if not self.list_error and error:
self.list_error.append({
'error': {
'validation': [{
'location': location,
'message': error
}]
}
})
elif self.list_error and error:
if not self.list_error['error']:
self.list_error.append({
'error': {
'validation': [{
'location': location,
'message': error
}]
}
})
elif not self.list_error['error']['validation']:
self.list_error['error']['validation'] = [{
'location': location,
'message': error
}]
else:
self.list_error['error']['validation'].append({
'location': location,
'message': error
}) | [
"def",
"validate_premodel_settings",
"(",
"self",
")",
":",
"settings",
"=",
"self",
".",
"premodel_data",
"[",
"'properties'",
"]",
"error",
"=",
"Validator",
"(",
")",
".",
"validate_settings",
"(",
"self",
".",
"premodel_data",
"[",
"'properties'",
"]",
",",
"self",
".",
"session_type",
")",
"session_type",
"=",
"settings",
".",
"get",
"(",
"'session_type'",
",",
"None",
")",
"stream",
"=",
"settings",
".",
"get",
"(",
"'stream'",
",",
"None",
")",
"if",
"stream",
"==",
"'True'",
"and",
"session_type",
"in",
"[",
"'data_add'",
",",
"'data_append'",
"]",
":",
"location",
"=",
"settings",
"[",
"'session_name'",
"]",
"else",
":",
"location",
"=",
"session_type",
"if",
"not",
"self",
".",
"list_error",
"and",
"error",
":",
"self",
".",
"list_error",
".",
"append",
"(",
"{",
"'error'",
":",
"{",
"'validation'",
":",
"[",
"{",
"'location'",
":",
"location",
",",
"'message'",
":",
"error",
"}",
"]",
"}",
"}",
")",
"elif",
"self",
".",
"list_error",
"and",
"error",
":",
"if",
"not",
"self",
".",
"list_error",
"[",
"'error'",
"]",
":",
"self",
".",
"list_error",
".",
"append",
"(",
"{",
"'error'",
":",
"{",
"'validation'",
":",
"[",
"{",
"'location'",
":",
"location",
",",
"'message'",
":",
"error",
"}",
"]",
"}",
"}",
")",
"elif",
"not",
"self",
".",
"list_error",
"[",
"'error'",
"]",
"[",
"'validation'",
"]",
":",
"self",
".",
"list_error",
"[",
"'error'",
"]",
"[",
"'validation'",
"]",
"=",
"[",
"{",
"'location'",
":",
"location",
",",
"'message'",
":",
"error",
"}",
"]",
"else",
":",
"self",
".",
"list_error",
"[",
"'error'",
"]",
"[",
"'validation'",
"]",
".",
"append",
"(",
"{",
"'location'",
":",
"location",
",",
"'message'",
":",
"error",
"}",
")"
] | https://github.com/jeff1evesque/machine-learning/blob/4c54e36f8ebf6a0b481c8aca71a6b3b4010dd4ff/brain/session/base.py#L58-L110 |
|||
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | 3rd_party/python2/site-packages/cherrypy/process/plugins.py | python | Monitor.graceful | (self) | Stop the callback's background task thread and restart it. | Stop the callback's background task thread and restart it. | [
"Stop",
"the",
"callback",
"s",
"background",
"task",
"thread",
"and",
"restart",
"it",
"."
] | def graceful(self):
"""Stop the callback's background task thread and restart it."""
self.stop()
self.start() | [
"def",
"graceful",
"(",
"self",
")",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"start",
"(",
")"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python2/site-packages/cherrypy/process/plugins.py#L578-L581 |
||
sherpa-ai/sherpa | ff6466e99717983f9f394ba72b63f17343e32bdc | sherpa/core.py | python | _Runner.update_results | (self) | Get rows from database and check if anything new needs to be added to
the results-table. | Get rows from database and check if anything new needs to be added to
the results-table. | [
"Get",
"rows",
"from",
"database",
"and",
"check",
"if",
"anything",
"new",
"needs",
"to",
"be",
"added",
"to",
"the",
"results",
"-",
"table",
"."
] | def update_results(self):
"""
Get rows from database and check if anything new needs to be added to
the results-table.
"""
results = self.database.get_new_results()
if results != [] and self._all_trials == {}:
logger.warning(results)
raise ValueError("Found unexpected results. Check the following\n"
"(1)\toutput_dir is empty\n"
"(2)\tno other database is running on this port.")
for r in results:
try:
# Check if trial has already been collected.
new_trial = (r.get('trial_id') not in
set(self.study.results['Trial-ID']))
except KeyError:
new_trial = True
if not new_trial:
trial_idxs = self.study.results['Trial-ID'] == r.get('trial_id')
trial_rows = self.study.results[trial_idxs]
new_observation = (r.get('iteration') not in
set(trial_rows['Iteration']))
else:
new_observation = True
if new_trial or new_observation:
# Retrieve the Trial object
tid = r.get('trial_id')
tdict = self._all_trials[tid]
t = tdict.get('trial')
self.study.add_observation(trial=t,
iteration=r.get('iteration'),
objective=r.get('objective'),
context=r.get('context')) | [
"def",
"update_results",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"database",
".",
"get_new_results",
"(",
")",
"if",
"results",
"!=",
"[",
"]",
"and",
"self",
".",
"_all_trials",
"==",
"{",
"}",
":",
"logger",
".",
"warning",
"(",
"results",
")",
"raise",
"ValueError",
"(",
"\"Found unexpected results. Check the following\\n\"",
"\"(1)\\toutput_dir is empty\\n\"",
"\"(2)\\tno other database is running on this port.\"",
")",
"for",
"r",
"in",
"results",
":",
"try",
":",
"# Check if trial has already been collected.",
"new_trial",
"=",
"(",
"r",
".",
"get",
"(",
"'trial_id'",
")",
"not",
"in",
"set",
"(",
"self",
".",
"study",
".",
"results",
"[",
"'Trial-ID'",
"]",
")",
")",
"except",
"KeyError",
":",
"new_trial",
"=",
"True",
"if",
"not",
"new_trial",
":",
"trial_idxs",
"=",
"self",
".",
"study",
".",
"results",
"[",
"'Trial-ID'",
"]",
"==",
"r",
".",
"get",
"(",
"'trial_id'",
")",
"trial_rows",
"=",
"self",
".",
"study",
".",
"results",
"[",
"trial_idxs",
"]",
"new_observation",
"=",
"(",
"r",
".",
"get",
"(",
"'iteration'",
")",
"not",
"in",
"set",
"(",
"trial_rows",
"[",
"'Iteration'",
"]",
")",
")",
"else",
":",
"new_observation",
"=",
"True",
"if",
"new_trial",
"or",
"new_observation",
":",
"# Retrieve the Trial object",
"tid",
"=",
"r",
".",
"get",
"(",
"'trial_id'",
")",
"tdict",
"=",
"self",
".",
"_all_trials",
"[",
"tid",
"]",
"t",
"=",
"tdict",
".",
"get",
"(",
"'trial'",
")",
"self",
".",
"study",
".",
"add_observation",
"(",
"trial",
"=",
"t",
",",
"iteration",
"=",
"r",
".",
"get",
"(",
"'iteration'",
")",
",",
"objective",
"=",
"r",
".",
"get",
"(",
"'objective'",
")",
",",
"context",
"=",
"r",
".",
"get",
"(",
"'context'",
")",
")"
] | https://github.com/sherpa-ai/sherpa/blob/ff6466e99717983f9f394ba72b63f17343e32bdc/sherpa/core.py#L454-L491 |
||
tuan3w/visual_search | 62665d4ac58669bad8e7f5ffed18d2914ffa8b01 | visual_search/lib/datasets/coco.py | python | coco._load_image_set_index | (self) | return image_ids | Load image ids. | Load image ids. | [
"Load",
"image",
"ids",
"."
] | def _load_image_set_index(self):
"""
Load image ids.
"""
image_ids = self._COCO.getImgIds()
return image_ids | [
"def",
"_load_image_set_index",
"(",
"self",
")",
":",
"image_ids",
"=",
"self",
".",
"_COCO",
".",
"getImgIds",
"(",
")",
"return",
"image_ids"
] | https://github.com/tuan3w/visual_search/blob/62665d4ac58669bad8e7f5ffed18d2914ffa8b01/visual_search/lib/datasets/coco.py#L92-L97 |