nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
pret/pokemon-reverse-engineering-tools
5e0715f2579adcfeb683448c9a7826cfd3afa57d
pokemontools/vba/vba.py
python
crystal.get_player_name
(self)
return name
Returns the 7 characters making up the player's name.
Returns the 7 characters making up the player's name.
[ "Returns", "the", "7", "characters", "making", "up", "the", "player", "s", "name", "." ]
def get_player_name(self): """ Returns the 7 characters making up the player's name. """ bytez = self.vba.memory[0xD47D:0xD47D + 7] name = translate_chars(bytez) return name
[ "def", "get_player_name", "(", "self", ")", ":", "bytez", "=", "self", ".", "vba", ".", "memory", "[", "0xD47D", ":", "0xD47D", "+", "7", "]", "name", "=", "translate_chars", "(", "bytez", ")", "return", "name" ]
https://github.com/pret/pokemon-reverse-engineering-tools/blob/5e0715f2579adcfeb683448c9a7826cfd3afa57d/pokemontools/vba/vba.py#L678-L684
toxygen-project/toxygen
0a54012cf5ee72434b923bcde7d8f1a4e575ce2f
toxygen/main.py
python
Toxygen.enter_pass
(self, data)
Show password screen
Show password screen
[ "Show", "password", "screen" ]
def enter_pass(self, data): """ Show password screen """ tmp = [data] p = PasswordScreen(toxes.ToxES.get_instance(), tmp) p.show() self.app.lastWindowClosed.connect(self.app.quit) self.app.exec_() if tmp[0] == data: raise SystemExit() else: return tmp[0]
[ "def", "enter_pass", "(", "self", ",", "data", ")", ":", "tmp", "=", "[", "data", "]", "p", "=", "PasswordScreen", "(", "toxes", ".", "ToxES", ".", "get_instance", "(", ")", ",", "tmp", ")", "p", ".", "show", "(", ")", "self", ".", "app", ".", ...
https://github.com/toxygen-project/toxygen/blob/0a54012cf5ee72434b923bcde7d8f1a4e575ce2f/toxygen/main.py#L32-L44
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/function_field/maps.py
python
MapVectorSpaceToFunctionField.codomain
(self)
return self._K
Return the function field which is the codomain of the isomorphism. EXAMPLES:: sage: K.<x> = FunctionField(QQ); R.<y> = K[] sage: L.<y> = K.extension(y^2 - x*y + 4*x^3) sage: V, f, t = L.vector_space() sage: f.codomain() Function field in y defined by y^2 - x*y + 4*x^3
Return the function field which is the codomain of the isomorphism.
[ "Return", "the", "function", "field", "which", "is", "the", "codomain", "of", "the", "isomorphism", "." ]
def codomain(self): """ Return the function field which is the codomain of the isomorphism. EXAMPLES:: sage: K.<x> = FunctionField(QQ); R.<y> = K[] sage: L.<y> = K.extension(y^2 - x*y + 4*x^3) sage: V, f, t = L.vector_space() sage: f.codomain() Function field in y defined by y^2 - x*y + 4*x^3 """ return self._K
[ "def", "codomain", "(", "self", ")", ":", "return", "self", ".", "_K" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/function_field/maps.py#L1268-L1280
learningequality/kolibri
d056dbc477aaf651ab843caa141a6a1e0a491046
kolibri/core/content/utils/import_export_content.py
python
retry_import
(e)
return False
When an exception occurs during channel/content import, if * there is an Internet connection error or timeout error, or HTTPError where the error code is one of the RETRY_STATUS_CODE, return return True to retry the file transfer return value: * True - needs retry. * False - Does not need retry.
When an exception occurs during channel/content import, if * there is an Internet connection error or timeout error, or HTTPError where the error code is one of the RETRY_STATUS_CODE, return return True to retry the file transfer return value: * True - needs retry. * False - Does not need retry.
[ "When", "an", "exception", "occurs", "during", "channel", "/", "content", "import", "if", "*", "there", "is", "an", "Internet", "connection", "error", "or", "timeout", "error", "or", "HTTPError", "where", "the", "error", "code", "is", "one", "of", "the", "...
def retry_import(e): """ When an exception occurs during channel/content import, if * there is an Internet connection error or timeout error, or HTTPError where the error code is one of the RETRY_STATUS_CODE, return return True to retry the file transfer return value: * True - needs retry. * False - Does not need retry. """ if ( isinstance(e, ConnectionError) or isinstance(e, Timeout) or isinstance(e, ChunkedEncodingError) or (isinstance(e, HTTPError) and e.response.status_code in RETRY_STATUS_CODE) or (isinstance(e, SSLERROR) and "decryption failed or bad record mac" in str(e)) ): return True return False
[ "def", "retry_import", "(", "e", ")", ":", "if", "(", "isinstance", "(", "e", ",", "ConnectionError", ")", "or", "isinstance", "(", "e", ",", "Timeout", ")", "or", "isinstance", "(", "e", ",", "ChunkedEncodingError", ")", "or", "(", "isinstance", "(", ...
https://github.com/learningequality/kolibri/blob/d056dbc477aaf651ab843caa141a6a1e0a491046/kolibri/core/content/utils/import_export_content.py#L214-L234
scrtlabs/catalyst
2e8029780f2381da7a0729f7b52505e5db5f535b
catalyst/pipeline/mixins.py
python
DownsampledMixin.compute_extra_rows
(self, all_dates, start_date, end_date, min_extra_rows)
return min_extra_rows + (current_start_pos - new_start_pos)
Ensure that min_extra_rows pushes us back to a computation date. Parameters ---------- all_dates : pd.DatetimeIndex The trading sessions against which ``self`` will be computed. start_date : pd.Timestamp The first date for which final output is requested. end_date : pd.Timestamp The last date for which final output is requested. min_extra_rows : int The minimum number of extra rows required of ``self``, as determined by other terms that depend on ``self``. Returns ------- extra_rows : int The number of extra rows to compute. This will be the minimum number of rows required to make our computed start_date fall on a recomputation date.
Ensure that min_extra_rows pushes us back to a computation date.
[ "Ensure", "that", "min_extra_rows", "pushes", "us", "back", "to", "a", "computation", "date", "." ]
def compute_extra_rows(self, all_dates, start_date, end_date, min_extra_rows): """ Ensure that min_extra_rows pushes us back to a computation date. Parameters ---------- all_dates : pd.DatetimeIndex The trading sessions against which ``self`` will be computed. start_date : pd.Timestamp The first date for which final output is requested. end_date : pd.Timestamp The last date for which final output is requested. min_extra_rows : int The minimum number of extra rows required of ``self``, as determined by other terms that depend on ``self``. Returns ------- extra_rows : int The number of extra rows to compute. This will be the minimum number of rows required to make our computed start_date fall on a recomputation date. """ try: current_start_pos = all_dates.get_loc(start_date) - min_extra_rows if current_start_pos < 0: raise NoFurtherDataError( initial_message="Insufficient data to compute Pipeline:", first_date=all_dates[0], lookback_start=start_date, lookback_length=min_extra_rows, ) except KeyError: before, after = nearest_unequal_elements(all_dates, start_date) raise ValueError( "Pipeline start_date {start_date} is not in calendar.\n" "Latest date before start_date is {before}.\n" "Earliest date after start_date is {after}.".format( start_date=start_date, before=before, after=after, ) ) # Our possible target dates are all the dates on or before the current # starting position. # TODO: Consider bounding this below by self.window_length candidates = all_dates[:current_start_pos + 1] # Choose the latest date in the candidates that is the start of a new # period at our frequency. choices = select_sampling_indices(candidates, self._frequency) # If we have choices, the last choice is the first date if the # period containing current_start_date. Choose it. new_start_date = candidates[choices[-1]] # Add the difference between the new and old start dates to get the # number of rows for the new start_date. new_start_pos = all_dates.get_loc(new_start_date) assert new_start_pos <= current_start_pos, \ "Computed negative extra rows!" return min_extra_rows + (current_start_pos - new_start_pos)
[ "def", "compute_extra_rows", "(", "self", ",", "all_dates", ",", "start_date", ",", "end_date", ",", "min_extra_rows", ")", ":", "try", ":", "current_start_pos", "=", "all_dates", ".", "get_loc", "(", "start_date", ")", "-", "min_extra_rows", "if", "current_star...
https://github.com/scrtlabs/catalyst/blob/2e8029780f2381da7a0729f7b52505e5db5f535b/catalyst/pipeline/mixins.py#L359-L426
MycroftAI/mycroft-core
3d963cee402e232174850f36918313e87313fb13
mycroft/skills/common_iot_skill.py
python
CommonIoTSkill.get_entities
(self)
return []
Get a list of custom entities. This is intended to be overridden by subclasses, though it it not required (the default implementation will return an empty list). The strings returned by this function will be registered as ENTITY values with the intent parser. Skills should provide group names, user aliases for specific devices, or anything else that might represent a THING or a set of THINGs, e.g. 'bedroom', 'lamp', 'front door.' This allows commands that don't explicitly include a THING to still be handled, e.g. "bedroom off" as opposed to "bedroom lights off."
Get a list of custom entities.
[ "Get", "a", "list", "of", "custom", "entities", "." ]
def get_entities(self) -> [str]: """ Get a list of custom entities. This is intended to be overridden by subclasses, though it it not required (the default implementation will return an empty list). The strings returned by this function will be registered as ENTITY values with the intent parser. Skills should provide group names, user aliases for specific devices, or anything else that might represent a THING or a set of THINGs, e.g. 'bedroom', 'lamp', 'front door.' This allows commands that don't explicitly include a THING to still be handled, e.g. "bedroom off" as opposed to "bedroom lights off." """ return []
[ "def", "get_entities", "(", "self", ")", "->", "[", "str", "]", ":", "return", "[", "]" ]
https://github.com/MycroftAI/mycroft-core/blob/3d963cee402e232174850f36918313e87313fb13/mycroft/skills/common_iot_skill.py#L491-L507
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/logging/__init__.py
python
Manager._fixupParents
(self, alogger)
Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy.
Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy.
[ "Ensure", "that", "there", "are", "either", "loggers", "or", "placeholders", "all", "the", "way", "from", "the", "specified", "logger", "to", "the", "root", "of", "the", "logger", "hierarchy", "." ]
def _fixupParents(self, alogger): """ Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy. """ name = alogger.name i = name.rfind(".") rv = None while (i > 0) and not rv: substr = name[:i] if substr not in self.loggerDict: self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] if isinstance(obj, Logger): rv = obj else: assert isinstance(obj, PlaceHolder) obj.append(alogger) i = name.rfind(".", 0, i - 1) if not rv: rv = self.root alogger.parent = rv
[ "def", "_fixupParents", "(", "self", ",", "alogger", ")", ":", "name", "=", "alogger", ".", "name", "i", "=", "name", ".", "rfind", "(", "\".\"", ")", "rv", "=", "None", "while", "(", "i", ">", "0", ")", "and", "not", "rv", ":", "substr", "=", ...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/logging/__init__.py#L1084-L1106
zhangxiaosong18/FreeAnchor
afad43a7c48034301d981d831fa61e42d9b6ddad
maskrcnn_benchmark/utils/miscellaneous.py
python
mkdir
(path)
[]
def mkdir(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise
[ "def", "mkdir", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise" ]
https://github.com/zhangxiaosong18/FreeAnchor/blob/afad43a7c48034301d981d831fa61e42d9b6ddad/maskrcnn_benchmark/utils/miscellaneous.py#L6-L11
boatbod/op25
b26209a72a3d9a263ccf16b0b2ab75d0f19cb550
op25/gr-op25_repeater/apps/tx/op25_c4fm_mod.py
python
p25_mod_bf.__init__
(self, output_sample_rate=_def_output_sample_rate, reverse=_def_reverse, verbose=_def_verbose, generator=transfer_function_tx, dstar=False, bt=_def_bt, rc=None, log=_def_log)
Hierarchical block for RRC-filtered P25 FM modulation. The input is a dibit (P25 symbol) stream (char, not packed) and the output is the float "C4FM" signal at baseband, suitable for application to an FM modulator stage Input is at the base symbol rate (4800), output sample rate is typically either 32000 (USRP TX chain) or 48000 (sound card) @param output_sample_rate: output sample rate @type output_sample_rate: integer @param reverse: reverse polarity flag @type reverse: bool @param verbose: Print information about modulator? @type verbose: bool @param debug: Print modulation data to files? @type debug: bool
Hierarchical block for RRC-filtered P25 FM modulation.
[ "Hierarchical", "block", "for", "RRC", "-", "filtered", "P25", "FM", "modulation", "." ]
def __init__(self, output_sample_rate=_def_output_sample_rate, reverse=_def_reverse, verbose=_def_verbose, generator=transfer_function_tx, dstar=False, bt=_def_bt, rc=None, log=_def_log): """ Hierarchical block for RRC-filtered P25 FM modulation. The input is a dibit (P25 symbol) stream (char, not packed) and the output is the float "C4FM" signal at baseband, suitable for application to an FM modulator stage Input is at the base symbol rate (4800), output sample rate is typically either 32000 (USRP TX chain) or 48000 (sound card) @param output_sample_rate: output sample rate @type output_sample_rate: integer @param reverse: reverse polarity flag @type reverse: bool @param verbose: Print information about modulator? @type verbose: bool @param debug: Print modulation data to files? @type debug: bool """ gr.hier_block2.__init__(self, "p25_c4fm_mod_bf", gr.io_signature(1, 1, gr.sizeof_char), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature input_sample_rate = 4800 # P25 baseband symbol rate intermediate_rate = 48000 self._interp_factor = intermediate_rate / input_sample_rate self.dstar = dstar self.bt = bt if self.dstar: self.C2S = digital.chunks_to_symbols_bf([-1, 1], 1) else: mod_map = [1.0/3.0, 1.0, -(1.0/3.0), -1.0] self.C2S = digital.chunks_to_symbols_bf(mod_map) if reverse: self.polarity = blocks.multiply_const_ff(-1) else: self.polarity = blocks.multiply_const_ff( 1) self.generator = generator assert rc is None or rc == 'rc' or rc == 'rrc' if rc: coeffs = filter.firdes.root_raised_cosine(1.0, intermediate_rate, input_sample_rate, 0.2, 91) if rc == 'rc': coeffs = c4fm_taps(sample_rate=intermediate_rate).generate() elif self.dstar: coeffs = gmsk_taps(sample_rate=intermediate_rate, bt=self.bt).generate() elif not rc: coeffs = c4fm_taps(sample_rate=intermediate_rate, generator=self.generator).generate() self.filter = filter.interp_fir_filter_fff(self._interp_factor, coeffs) if verbose: self._print_verbage() if log: self._setup_logging() self.connect(self, self.C2S, self.polarity, self.filter) if intermediate_rate != output_sample_rate: self.arb_resamp = filter.pfb.arb_resampler_fff(float(output_sample_rate)/intermediate_rate) self.connect(self.filter, self.arb_resamp, self) else: self.connect(self.filter, self)
[ "def", "__init__", "(", "self", ",", "output_sample_rate", "=", "_def_output_sample_rate", ",", "reverse", "=", "_def_reverse", ",", "verbose", "=", "_def_verbose", ",", "generator", "=", "transfer_function_tx", ",", "dstar", "=", "False", ",", "bt", "=", "_def_...
https://github.com/boatbod/op25/blob/b26209a72a3d9a263ccf16b0b2ab75d0f19cb550/op25/gr-op25_repeater/apps/tx/op25_c4fm_mod.py#L187-L261
Ghirensics/ghiro
c9ff33b6ed16eb1cd960822b8031baf9b84a8636
analyses/views.py
python
close_case
(request, case_id)
return HttpResponseRedirect(reverse("analyses.views.list_cases"))
Close a case.
Close a case.
[ "Close", "a", "case", "." ]
def close_case(request, case_id): """Close a case.""" case = get_object_or_404(Case, pk=case_id) # Security check. if request.user != case.owner and not request.user.is_superuser: return render_to_response("error.html", {"error": "You are not authorized to close this. Only owner can close the case."}, context_instance=RequestContext(request)) if case.state == "C": return render_to_response("error.html", {"error": "You cannot edit an already closed case."}, context_instance=RequestContext(request)) case.state = "C" case.updated_at = now() case.save() # Auditing. log_activity("C", "Closed case %s" % case.name, request) return HttpResponseRedirect(reverse("analyses.views.list_cases"))
[ "def", "close_case", "(", "request", ",", "case_id", ")", ":", "case", "=", "get_object_or_404", "(", "Case", ",", "pk", "=", "case_id", ")", "# Security check.", "if", "request", ".", "user", "!=", "case", ".", "owner", "and", "not", "request", ".", "us...
https://github.com/Ghirensics/ghiro/blob/c9ff33b6ed16eb1cd960822b8031baf9b84a8636/analyses/views.py#L111-L133
OCA/stock-logistics-warehouse
185c1b0cb9e31e3746a89ec269b4bc09c69b2411
stock_vertical_lift/models/vertical_lift_operation_pick.py
python
VerticalLiftOperationPick.button_release
(self)
return res
Release the operation, go to the next
Release the operation, go to the next
[ "Release", "the", "operation", "go", "to", "the", "next" ]
def button_release(self): """Release the operation, go to the next""" res = super().button_release() if self.step() == "noop": # we don't need to release (close) the tray until we have reached # the last line: the release is implicit when a next line is # fetched self.shuttle_id.release_vertical_lift_tray() # sorry not sorry res = self._rainbow_man() return res
[ "def", "button_release", "(", "self", ")", ":", "res", "=", "super", "(", ")", ".", "button_release", "(", ")", "if", "self", ".", "step", "(", ")", "==", "\"noop\"", ":", "# we don't need to release (close) the tray until we have reached", "# the last line: the rel...
https://github.com/OCA/stock-logistics-warehouse/blob/185c1b0cb9e31e3746a89ec269b4bc09c69b2411/stock_vertical_lift/models/vertical_lift_operation_pick.py#L123-L133
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/simplify/simplify.py
python
_denest_pow
(eq)
return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))
Denest powers. This is a helper function for powdenest that performs the actual transformation.
Denest powers.
[ "Denest", "powers", "." ]
def _denest_pow(eq): """ Denest powers. This is a helper function for powdenest that performs the actual transformation. """ b, e = eq.as_base_exp() # denest exp with log terms in exponent if b is S.Exp1 and e.is_Mul: logs = [] other = [] for ei in e.args: if any(ai.func is C.log for ai in Add.make_args(ei)): logs.append(ei) else: other.append(ei) logs = logcombine(Mul(*logs)) return Pow(exp(logs), Mul(*other)) _, be = b.as_base_exp() if be is S.One and not (b.is_Mul or b.is_Rational and b.q != 1 or b.is_positive): return eq # denest eq which is either pos**e or Pow**e or Mul**e or # Mul(b1**e1, b2**e2) # handle polar numbers specially polars, nonpolars = [], [] for bb in Mul.make_args(b): if bb.is_polar: polars.append(bb.as_base_exp()) else: nonpolars.append(bb) if len(polars) == 1 and not polars[0][0].is_Mul: return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e) elif polars: return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \ *powdenest(Mul(*nonpolars)**e) # see if there is a positive, non-Mul base at the very bottom exponents = [] kernel = eq while kernel.is_Pow: kernel, ex = kernel.as_base_exp() exponents.append(ex) if kernel.is_positive: e = Mul(*exponents) if kernel.is_Mul: b = kernel else: if kernel.is_Integer: # use log to see if there is a power here logkernel = expand_log(log(kernel)) if logkernel.is_Mul: c, logk = logkernel.args e *= c kernel = logk.args[0] return Pow(kernel, e) # if any factor is an atom then there is nothing to be done # but the kernel check may have created a new exponent if any(s.is_Atom for s in Mul.make_args(b)): if exponents: return b**e return eq # let log handle the case of the base of the argument being a mul, e.g. # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we # will take the log, expand it, and then factor out the common powers that # now appear as coefficient. We do this manually since terms_gcd pulls out # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2; # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but # we want 3*x. Neither work with noncommutatives. def nc_gcd(aa, bb): a, b = [i.as_coeff_Mul() for i in [aa, bb]] c = gcd(a[0], b[0]).as_numer_denom()[0] g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0])) return _keep_coeff(c, g) glogb = expand_log(log(b)) if glogb.is_Add: args = glogb.args g = reduce(nc_gcd, args) if g != 1: cg, rg = g.as_coeff_Mul() glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args])) # now put the log back together again if glogb.func is C.log or not glogb.is_Mul: if glogb.args[0].is_Pow or glogb.args[0].func is exp: glogb = _denest_pow(glogb.args[0]) if (abs(glogb.exp) < 1) is True: return Pow(glogb.base, glogb.exp*e) return eq # the log(b) was a Mul so join any adds with logcombine add = [] other = [] for a in glogb.args: if a.is_Add: add.append(a) else: other.append(a) return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))
[ "def", "_denest_pow", "(", "eq", ")", ":", "b", ",", "e", "=", "eq", ".", "as_base_exp", "(", ")", "# denest exp with log terms in exponent", "if", "b", "is", "S", ".", "Exp1", "and", "e", ".", "is_Mul", ":", "logs", "=", "[", "]", "other", "=", "[",...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/simplify/simplify.py#L2228-L2336
everydo/zcms
d389b764b0f5f55102faf0b331acafae3f8da9e3
zcms/frs.py
python
FRS.remove
(self, vPath)
remove a file path
remove a file path
[ "remove", "a", "file", "path" ]
def remove(self, vPath): """ remove a file path""" os.remove(self.ospath(vPath) )
[ "def", "remove", "(", "self", ",", "vPath", ")", ":", "os", ".", "remove", "(", "self", ".", "ospath", "(", "vPath", ")", ")" ]
https://github.com/everydo/zcms/blob/d389b764b0f5f55102faf0b331acafae3f8da9e3/zcms/frs.py#L158-L160
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/profiler/widgets/main_widget.py
python
ProfilerWidget.show_log
(self)
Show process output log.
Show process output log.
[ "Show", "process", "output", "log", "." ]
def show_log(self): """Show process output log.""" if self.output: output_dialog = TextEditor( self.output, title=_("Profiler output"), readonly=True, parent=self, ) output_dialog.resize(700, 500) output_dialog.exec_()
[ "def", "show_log", "(", "self", ")", ":", "if", "self", ".", "output", ":", "output_dialog", "=", "TextEditor", "(", "self", ".", "output", ",", "title", "=", "_", "(", "\"Profiler output\"", ")", ",", "readonly", "=", "True", ",", "parent", "=", "self...
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/profiler/widgets/main_widget.py#L467-L477
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/modules/common/structures/user.py
python
UserData.set_gid
(self, new_gid)
Set GID value and mode from a value which can be None. Prefer using this method instead of directly writing gid and gid_mode. :param new_gid: new GID :type new_gid: int or None
Set GID value and mode from a value which can be None.
[ "Set", "GID", "value", "and", "mode", "from", "a", "value", "which", "can", "be", "None", "." ]
def set_gid(self, new_gid): """Set GID value and mode from a value which can be None. Prefer using this method instead of directly writing gid and gid_mode. :param new_gid: new GID :type new_gid: int or None """ if new_gid is not None: self._gid = new_gid self._gid_mode = ID_MODE_USE_VALUE else: self._gid = 0 self._gid_mode = ID_MODE_USE_DEFAULT
[ "def", "set_gid", "(", "self", ",", "new_gid", ")", ":", "if", "new_gid", "is", "not", "None", ":", "self", ".", "_gid", "=", "new_gid", "self", ".", "_gid_mode", "=", "ID_MODE_USE_VALUE", "else", ":", "self", ".", "_gid", "=", "0", "self", ".", "_gi...
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/modules/common/structures/user.py#L193-L206
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/tf/util/data.py
python
Data.get_placeholder_as_time_major
(self)
return self.copy_as_time_major().placeholder
:rtype: tf.Tensor
:rtype: tf.Tensor
[ ":", "rtype", ":", "tf", ".", "Tensor" ]
def get_placeholder_as_time_major(self): """ :rtype: tf.Tensor """ assert self.placeholder is not None return self.copy_as_time_major().placeholder
[ "def", "get_placeholder_as_time_major", "(", "self", ")", ":", "assert", "self", ".", "placeholder", "is", "not", "None", "return", "self", ".", "copy_as_time_major", "(", ")", ".", "placeholder" ]
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/util/data.py#L4315-L4320
fossasia/open-event-legacy
82b585d276efb894a48919bec4f3bff49077e2e8
migrations/env.py
python
run_migrations_online
()
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
Run migrations in 'online' mode.
[ "Run", "migrations", "in", "online", "mode", "." ]
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: http://alembic.readthedocs.org/en/latest/cookbook.html def process_revision_directives(context, revision, directives): if getattr(config.cmd_opts, 'autogenerate', False): script = directives[0] if script.upgrade_ops.is_empty(): directives[:] = [] LOGGER.info('No changes in schema detected.') engine = engine_from_config(config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool) connection = engine.connect() context.configure(connection=connection, target_metadata=target_metadata, process_revision_directives=process_revision_directives, compare_type=True, **current_app.extensions['migrate'].configure_args) try: with context.begin_transaction(): context.run_migrations() finally: connection.close()
[ "def", "run_migrations_online", "(", ")", ":", "# this callback is used to prevent an auto-migration from being generated", "# when there are no changes to the schema", "# reference: http://alembic.readthedocs.org/en/latest/cookbook.html", "def", "process_revision_directives", "(", "context", ...
https://github.com/fossasia/open-event-legacy/blob/82b585d276efb894a48919bec4f3bff49077e2e8/migrations/env.py#L51-L84
asyml/texar
a23f021dae289a3d768dc099b220952111da04fd
texar/tf/utils/utils.py
python
get_instance_kwargs
(kwargs, hparams)
return kwargs_
Makes a dict of keyword arguments with the following structure: `kwargs_ = {'hparams': dict(hparams), **kwargs}`. This is typically used for constructing a module which takes a set of arguments as well as a argument named `hparams`. Args: kwargs (dict): A dict of keyword arguments. Can be `None`. hparams: A dict or an instance of :class:`~texar.tf.HParams` Can be `None`. Returns: A `dict` that contains the keyword arguments in :attr:`kwargs`, and an additional keyword argument named `hparams`.
Makes a dict of keyword arguments with the following structure:
[ "Makes", "a", "dict", "of", "keyword", "arguments", "with", "the", "following", "structure", ":" ]
def get_instance_kwargs(kwargs, hparams): """Makes a dict of keyword arguments with the following structure: `kwargs_ = {'hparams': dict(hparams), **kwargs}`. This is typically used for constructing a module which takes a set of arguments as well as a argument named `hparams`. Args: kwargs (dict): A dict of keyword arguments. Can be `None`. hparams: A dict or an instance of :class:`~texar.tf.HParams` Can be `None`. Returns: A `dict` that contains the keyword arguments in :attr:`kwargs`, and an additional keyword argument named `hparams`. """ if hparams is None or isinstance(hparams, dict): kwargs_ = {'hparams': hparams} elif isinstance(hparams, HParams): kwargs_ = {'hparams': hparams.todict()} else: raise ValueError( '`hparams` must be a dict, an instance of HParams, or a `None`.') kwargs_.update(kwargs or {}) return kwargs_
[ "def", "get_instance_kwargs", "(", "kwargs", ",", "hparams", ")", ":", "if", "hparams", "is", "None", "or", "isinstance", "(", "hparams", ",", "dict", ")", ":", "kwargs_", "=", "{", "'hparams'", ":", "hparams", "}", "elif", "isinstance", "(", "hparams", ...
https://github.com/asyml/texar/blob/a23f021dae289a3d768dc099b220952111da04fd/texar/tf/utils/utils.py#L439-L463
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/future/backports/email/_header_value_parser.py
python
get_parameter
(value)
return param, value
attribute [section] ["*"] [CFWS] "=" value The CFWS is implied by the RFC but not made explicit in the BNF. This simplified form of the BNF from the RFC is made to conform with the RFC BNF through some extra checks. We do it this way because it makes both error recovery and working with the resulting parse tree easier.
attribute [section] ["*"] [CFWS] "=" value
[ "attribute", "[", "section", "]", "[", "*", "]", "[", "CFWS", "]", "=", "value" ]
def get_parameter(value): """ attribute [section] ["*"] [CFWS] "=" value The CFWS is implied by the RFC but not made explicit in the BNF. This simplified form of the BNF from the RFC is made to conform with the RFC BNF through some extra checks. We do it this way because it makes both error recovery and working with the resulting parse tree easier. """ # It is possible CFWS would also be implicitly allowed between the section # and the 'extended-attribute' marker (the '*') , but we've never seen that # in the wild and we will therefore ignore the possibility. param = Parameter() token, value = get_attribute(value) param.append(token) if not value or value[0] == ';': param.defects.append(errors.InvalidHeaderDefect("Parameter contains " "name ({}) but no value".format(token))) return param, value if value[0] == '*': try: token, value = get_section(value) param.sectioned = True param.append(token) except errors.HeaderParseError: pass if not value: raise errors.HeaderParseError("Incomplete parameter") if value[0] == '*': param.append(ValueTerminal('*', 'extended-parameter-marker')) value = value[1:] param.extended = True if value[0] != '=': raise errors.HeaderParseError("Parameter not followed by '='") param.append(ValueTerminal('=', 'parameter-separator')) value = value[1:] leader = None if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) param.append(token) remainder = None appendto = param if param.extended and value and value[0] == '"': # Now for some serious hackery to handle the common invalid case of # double quotes around an extended value. We also accept (with defect) # a value marked as encoded that isn't really. qstring, remainder = get_quoted_string(value) inner_value = qstring.stripped_value semi_valid = False if param.section_number == 0: if inner_value and inner_value[0] == "'": semi_valid = True else: token, rest = get_attrtext(inner_value) if rest and rest[0] == "'": semi_valid = True else: try: token, rest = get_extended_attrtext(inner_value) except: pass else: if not rest: semi_valid = True if semi_valid: param.defects.append(errors.InvalidHeaderDefect( "Quoted string value for extended parameter is invalid")) param.append(qstring) for t in qstring: if t.token_type == 'bare-quoted-string': t[:] = [] appendto = t break value = inner_value else: remainder = None param.defects.append(errors.InvalidHeaderDefect( "Parameter marked as extended but appears to have a " "quoted string value that is non-encoded")) if value and value[0] == "'": token = None else: token, value = get_value(value) if not param.extended or param.section_number > 0: if not value or value[0] != "'": appendto.append(token) if remainder is not None: assert not value, value value = remainder return param, value param.defects.append(errors.InvalidHeaderDefect( "Apparent initial-extended-value but attribute " "was not marked as extended or was not initial section")) if not value: # Assume the charset/lang is missing and the token is the value. param.defects.append(errors.InvalidHeaderDefect( "Missing required charset/lang delimiters")) appendto.append(token) if remainder is None: return param, value else: if token is not None: for t in token: if t.token_type == 'extended-attrtext': break t.token_type == 'attrtext' appendto.append(t) param.charset = t.value if value[0] != "'": raise errors.HeaderParseError("Expected RFC2231 char/lang encoding " "delimiter, but found {!r}".format(value)) appendto.append(ValueTerminal("'", 'RFC2231 delimiter')) value = value[1:] if value and value[0] != "'": token, value = get_attrtext(value) appendto.append(token) param.lang = token.value if not value or value[0] != "'": raise errors.HeaderParseError("Expected RFC2231 char/lang encoding " "delimiter, but found {}".format(value)) appendto.append(ValueTerminal("'", 'RFC2231 delimiter')) value = value[1:] if remainder is not None: # Treat the rest of value as bare quoted string content. v = Value() while value: if value[0] in WSP: token, value = get_fws(value) else: token, value = get_qcontent(value) v.append(token) token = v else: token, value = get_value(value) appendto.append(token) if remainder is not None: assert not value, value value = remainder return param, value
[ "def", "get_parameter", "(", "value", ")", ":", "# It is possible CFWS would also be implicitly allowed between the section", "# and the 'extended-attribute' marker (the '*') , but we've never seen that", "# in the wild and we will therefore ignore the possibility.", "param", "=", "Parameter",...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/future/backports/email/_header_value_parser.py#L2642-L2779
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/ocr/v20181119/models.py
python
GeneralAccurateOCRResponse.__init__
(self)
r""" :param TextDetections: 检测到的文本信息,包括文本行内容、置信度、文本行坐标以及文本行旋转纠正后的坐标,具体内容请点击左侧链接。 :type TextDetections: list of TextDetection :param Angel: 图片旋转角度(角度制),文本的水平方向为0°;顺时针为正,逆时针为负。点击查看<a href="https://cloud.tencent.com/document/product/866/45139">如何纠正倾斜文本</a> :type Angel: float :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param TextDetections: 检测到的文本信息,包括文本行内容、置信度、文本行坐标以及文本行旋转纠正后的坐标,具体内容请点击左侧链接。 :type TextDetections: list of TextDetection :param Angel: 图片旋转角度(角度制),文本的水平方向为0°;顺时针为正,逆时针为负。点击查看<a href="https://cloud.tencent.com/document/product/866/45139">如何纠正倾斜文本</a> :type Angel: float :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "TextDetections", ":", "检测到的文本信息,包括文本行内容、置信度、文本行坐标以及文本行旋转纠正后的坐标,具体内容请点击左侧链接。", ":", "type", "TextDetections", ":", "list", "of", "TextDetection", ":", "param", "Angel", ":", "图片旋转角度(角度制),文本的水平方向为0°;顺时针为正,逆时针为负。点击查看<a", "href", "=", "https", ":", "//", ...
def __init__(self): r""" :param TextDetections: 检测到的文本信息,包括文本行内容、置信度、文本行坐标以及文本行旋转纠正后的坐标,具体内容请点击左侧链接。 :type TextDetections: list of TextDetection :param Angel: 图片旋转角度(角度制),文本的水平方向为0°;顺时针为正,逆时针为负。点击查看<a href="https://cloud.tencent.com/document/product/866/45139">如何纠正倾斜文本</a> :type Angel: float :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TextDetections = None self.Angel = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "TextDetections", "=", "None", "self", ".", "Angel", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ocr/v20181119/models.py#L2148-L2159
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/idlelib/parenmatch.py
python
ParenMatch.deactivate_restore
(self)
Remove restore event bindings.
Remove restore event bindings.
[ "Remove", "restore", "event", "bindings", "." ]
def deactivate_restore(self): "Remove restore event bindings." if self.is_restore_active: for seq in self.RESTORE_SEQUENCES: self.text.event_delete(self.RESTORE_VIRTUAL_EVENT_NAME, seq) self.is_restore_active = False
[ "def", "deactivate_restore", "(", "self", ")", ":", "if", "self", ".", "is_restore_active", ":", "for", "seq", "in", "self", ".", "RESTORE_SEQUENCES", ":", "self", ".", "text", ".", "event_delete", "(", "self", ".", "RESTORE_VIRTUAL_EVENT_NAME", ",", "seq", ...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/idlelib/parenmatch.py#L69-L74
CalebBell/fluids
dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80
fluids/safety_valve.py
python
API520_Kv
(Re)
return (0.9935 + 2.878/sqrt(Re) + 342.75/Re**1.5)**-1.0
r'''Calculates correction due to viscosity for liquid flow for use in API 520 relief valve sizing. .. math:: K_v = \left(0.9935 + \frac{2.878}{Re^{0.5}} + \frac{342.75} {Re^{1.5}}\right)^{-1} Parameters ---------- Re : float Reynolds number for flow out the valve [-] Returns ------- Kv : float Correction due to viscosity [-] Notes ----- Reynolds number in the standard is defined as follows, with Q in L/min, G1 as specific gravity, mu in centipoise, and area in mm^2: .. math:: Re = \frac{Q(18800G_1)}{\mu \sqrt{A}} It is unclear how this expression was derived with a constant of 18800; the following code demonstrates what the constant should be: >>> from scipy.constants import * >>> liter/minute*1000./(0.001*(milli**2)**0.5) 16666.666666666668 Examples -------- From [1]_, checked with example 5. >>> API520_Kv(100) 0.6157445891444229 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection.
r'''Calculates correction due to viscosity for liquid flow for use in API 520 relief valve sizing.
[ "r", "Calculates", "correction", "due", "to", "viscosity", "for", "liquid", "flow", "for", "use", "in", "API", "520", "relief", "valve", "sizing", "." ]
def API520_Kv(Re): r'''Calculates correction due to viscosity for liquid flow for use in API 520 relief valve sizing. .. math:: K_v = \left(0.9935 + \frac{2.878}{Re^{0.5}} + \frac{342.75} {Re^{1.5}}\right)^{-1} Parameters ---------- Re : float Reynolds number for flow out the valve [-] Returns ------- Kv : float Correction due to viscosity [-] Notes ----- Reynolds number in the standard is defined as follows, with Q in L/min, G1 as specific gravity, mu in centipoise, and area in mm^2: .. math:: Re = \frac{Q(18800G_1)}{\mu \sqrt{A}} It is unclear how this expression was derived with a constant of 18800; the following code demonstrates what the constant should be: >>> from scipy.constants import * >>> liter/minute*1000./(0.001*(milli**2)**0.5) 16666.666666666668 Examples -------- From [1]_, checked with example 5. >>> API520_Kv(100) 0.6157445891444229 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' return (0.9935 + 2.878/sqrt(Re) + 342.75/Re**1.5)**-1.0
[ "def", "API520_Kv", "(", "Re", ")", ":", "return", "(", "0.9935", "+", "2.878", "/", "sqrt", "(", "Re", ")", "+", "342.75", "/", "Re", "**", "1.5", ")", "**", "-", "1.0" ]
https://github.com/CalebBell/fluids/blob/dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80/fluids/safety_valve.py#L211-L255
fofix/fofix
7730d1503c66562b901f62b33a5bd46c3d5e5c34
fofix/core/Player.py
python
sortOptionsByKey
(opts)
return a
Deprecated: also in fofix.core.ConfigDefs
Deprecated: also in fofix.core.ConfigDefs
[ "Deprecated", ":", "also", "in", "fofix", ".", "core", ".", "ConfigDefs" ]
def sortOptionsByKey(opts): """ Deprecated: also in fofix.core.ConfigDefs """ a = {} for k, v in opts.items(): a[k] = ConfigOption(k, v) return a
[ "def", "sortOptionsByKey", "(", "opts", ")", ":", "a", "=", "{", "}", "for", "k", ",", "v", "in", "opts", ".", "items", "(", ")", ":", "a", "[", "k", "]", "=", "ConfigOption", "(", "k", ",", "v", ")", "return", "a" ]
https://github.com/fofix/fofix/blob/7730d1503c66562b901f62b33a5bd46c3d5e5c34/fofix/core/Player.py#L63-L68
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/heapq.py
python
heapify
(x)
Transform list into a heap, in-place, in O(len(x)) time.
Transform list into a heap, in-place, in O(len(x)) time.
[ "Transform", "list", "into", "a", "heap", "in", "-", "place", "in", "O", "(", "len", "(", "x", "))", "time", "." ]
def heapify(x): """Transform list into a heap, in-place, in O(len(x)) time.""" n = len(x) # Transform bottom-up. The largest index there's any point to looking at # is the largest with a child index in-range, so must have 2*i + 1 < n, # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1. for i in reversed(range(n//2)): _siftup(x, i)
[ "def", "heapify", "(", "x", ")", ":", "n", "=", "len", "(", "x", ")", "# Transform bottom-up. The largest index there's any point to looking at", "# is the largest with a child index in-range, so must have 2*i + 1 < n,", "# or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/heapq.py#L168-L177
deanishe/alfred-convert
97407f4ec8dbca5abbc6952b2b56cf3918624177
src/workflow/workflow.py
python
Workflow.last_version_run
(self)
return self._last_version_run
Return version of last version to run (or ``None``). .. versionadded:: 1.9.10 :returns: :class:`~workflow.update.Version` instance or ``None``
Return version of last version to run (or ``None``).
[ "Return", "version", "of", "last", "version", "to", "run", "(", "or", "None", ")", "." ]
def last_version_run(self): """Return version of last version to run (or ``None``). .. versionadded:: 1.9.10 :returns: :class:`~workflow.update.Version` instance or ``None`` """ if self._last_version_run is UNSET: version = self.settings.get('__workflow_last_version') if version: from update import Version version = Version(version) self._last_version_run = version self.logger.debug('last run version: %s', self._last_version_run) return self._last_version_run
[ "def", "last_version_run", "(", "self", ")", ":", "if", "self", ".", "_last_version_run", "is", "UNSET", ":", "version", "=", "self", ".", "settings", ".", "get", "(", "'__workflow_last_version'", ")", "if", "version", ":", "from", "update", "import", "Versi...
https://github.com/deanishe/alfred-convert/blob/97407f4ec8dbca5abbc6952b2b56cf3918624177/src/workflow/workflow.py#L2207-L2227
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pexpect/fdpexpect.py
python
fdspawn.send
(self, s)
return os.write(self.child_fd, b)
Write to fd, return number of bytes written
Write to fd, return number of bytes written
[ "Write", "to", "fd", "return", "number", "of", "bytes", "written" ]
def send(self, s): "Write to fd, return number of bytes written" s = self._coerce_send_string(s) self._log(s, 'send') b = self._encoder.encode(s, final=False) return os.write(self.child_fd, b)
[ "def", "send", "(", "self", ",", "s", ")", ":", "s", "=", "self", ".", "_coerce_send_string", "(", "s", ")", "self", ".", "_log", "(", "s", ",", "'send'", ")", "b", "=", "self", ".", "_encoder", ".", "encode", "(", "s", ",", "final", "=", "Fals...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pexpect/fdpexpect.py#L96-L102
mahmoud/boltons
270e974975984f662f998c8f6eb0ebebd964de82
boltons/ioutils.py
python
SpooledIOBase.pos
(self)
return self.tell()
[]
def pos(self): return self.tell()
[ "def", "pos", "(", "self", ")", ":", "return", "self", ".", "tell", "(", ")" ]
https://github.com/mahmoud/boltons/blob/270e974975984f662f998c8f6eb0ebebd964de82/boltons/ioutils.py#L163-L164
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/beetsplug/bpd/gstplayer.py
python
GstPlayer.play_file
(self, path)
Immediately begin playing the audio file at the given path.
Immediately begin playing the audio file at the given path.
[ "Immediately", "begin", "playing", "the", "audio", "file", "at", "the", "given", "path", "." ]
def play_file(self, path): """Immediately begin playing the audio file at the given path. """ self.player.set_state(Gst.State.NULL) if isinstance(path, six.text_type): path = path.encode('utf-8') uri = 'file://' + urllib.parse.quote(path) self.player.set_property("uri", uri) self.player.set_state(Gst.State.PLAYING) self.playing = True
[ "def", "play_file", "(", "self", ",", "path", ")", ":", "self", ".", "player", ".", "set_state", "(", "Gst", ".", "State", ".", "NULL", ")", "if", "isinstance", "(", "path", ",", "six", ".", "text_type", ")", ":", "path", "=", "path", ".", "encode"...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/beetsplug/bpd/gstplayer.py#L127-L137
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/parso/python/diff.py
python
DiffParser.update
(self, old_lines, new_lines)
return self._module
The algorithm works as follows: Equal: - Assure that the start is a newline, otherwise parse until we get one. - Copy from parsed_until_line + 1 to max(i2 + 1) - Make sure that the indentation is correct (e.g. add DEDENT) - Add old and change positions Insert: - Parse from parsed_until_line + 1 to min(j2 + 1), hopefully not much more. Returns the new module node.
The algorithm works as follows:
[ "The", "algorithm", "works", "as", "follows", ":" ]
def update(self, old_lines, new_lines): ''' The algorithm works as follows: Equal: - Assure that the start is a newline, otherwise parse until we get one. - Copy from parsed_until_line + 1 to max(i2 + 1) - Make sure that the indentation is correct (e.g. add DEDENT) - Add old and change positions Insert: - Parse from parsed_until_line + 1 to min(j2 + 1), hopefully not much more. Returns the new module node. ''' LOG.debug('diff parser start') # Reset the used names cache so they get regenerated. self._module._used_names = None self._parser_lines_new = new_lines self._reset() line_length = len(new_lines) sm = difflib.SequenceMatcher(None, old_lines, self._parser_lines_new) opcodes = sm.get_opcodes() LOG.debug('diff parser calculated') LOG.debug('diff: line_lengths old: %s, new: %s' % (len(old_lines), line_length)) for operation, i1, i2, j1, j2 in opcodes: LOG.debug('diff code[%s] old[%s:%s] new[%s:%s]', operation, i1 + 1, i2, j1 + 1, j2) if j2 == line_length and new_lines[-1] == '': # The empty part after the last newline is not relevant. j2 -= 1 if operation == 'equal': line_offset = j1 - i1 self._copy_from_old_parser(line_offset, i2, j2) elif operation == 'replace': self._parse(until_line=j2) elif operation == 'insert': self._parse(until_line=j2) else: assert operation == 'delete' # With this action all change will finally be applied and we have a # changed module. self._nodes_stack.close() last_pos = self._module.end_pos[0] if last_pos != line_length: current_lines = split_lines(self._module.get_code(), keepends=True) diff = difflib.unified_diff(current_lines, new_lines) raise Exception( "There's an issue (%s != %s) with the diff parser. Please report:\n%s" % (last_pos, line_length, ''.join(diff)) ) LOG.debug('diff parser end') return self._module
[ "def", "update", "(", "self", ",", "old_lines", ",", "new_lines", ")", ":", "LOG", ".", "debug", "(", "'diff parser start'", ")", "# Reset the used names cache so they get regenerated.", "self", ".", "_module", ".", "_used_names", "=", "None", "self", ".", "_parse...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/parso/python/diff.py#L112-L174
SpaceNetChallenge/RoadDetector
0a7391f546ab20c873dc6744920deef22c21ef3e
albu-solution/src/other_tools/apls_tools.py
python
create_buffer_geopandas
(geoJsonFileName, bufferDistanceMeters=2, bufferRoundness=1, projectToUTM=True)
return gdf_buffer
Create a buffer around the lines of the geojson. Return a geodataframe.
Create a buffer around the lines of the geojson. Return a geodataframe.
[ "Create", "a", "buffer", "around", "the", "lines", "of", "the", "geojson", ".", "Return", "a", "geodataframe", "." ]
def create_buffer_geopandas(geoJsonFileName, bufferDistanceMeters=2, bufferRoundness=1, projectToUTM=True): ''' Create a buffer around the lines of the geojson. Return a geodataframe. ''' if os.stat(geoJsonFileName).st_size == 0: return [] inGDF = gpd.read_file(geoJsonFileName) # set a few columns that we will need later inGDF['type'] = inGDF['road_type'].values inGDF['class'] = 'highway' inGDF['highway'] = 'highway' if len(inGDF) == 0: return [] # Transform gdf Roadlines into UTM so that Buffer makes sense if projectToUTM: tmpGDF = ox.project_gdf(inGDF) else: tmpGDF = inGDF gdf_utm_buffer = tmpGDF # perform Buffer to produce polygons from Line Segments gdf_utm_buffer['geometry'] = tmpGDF.buffer(bufferDistanceMeters, bufferRoundness) gdf_utm_dissolve = gdf_utm_buffer.dissolve(by='class') gdf_utm_dissolve.crs = gdf_utm_buffer.crs if projectToUTM: gdf_buffer = gdf_utm_dissolve.to_crs(inGDF.crs) else: gdf_buffer = gdf_utm_dissolve return gdf_buffer
[ "def", "create_buffer_geopandas", "(", "geoJsonFileName", ",", "bufferDistanceMeters", "=", "2", ",", "bufferRoundness", "=", "1", ",", "projectToUTM", "=", "True", ")", ":", "if", "os", ".", "stat", "(", "geoJsonFileName", ")", ".", "st_size", "==", "0", ":...
https://github.com/SpaceNetChallenge/RoadDetector/blob/0a7391f546ab20c873dc6744920deef22c21ef3e/albu-solution/src/other_tools/apls_tools.py#L321-L359
pyro-ppl/numpyro
6a0856b7cda82fc255e23adc797bb79f5b7fc904
numpyro/infer/elbo.py
python
ELBO.loss
(self, rng_key, param_map, model, guide, *args, **kwargs)
return self.loss_with_mutable_state( rng_key, param_map, model, guide, *args, **kwargs )["loss"]
Evaluates the ELBO with an estimator that uses num_particles many samples/particles. :param jax.random.PRNGKey rng_key: random number generator seed. :param dict param_map: dictionary of current parameter values keyed by site name. :param model: Python callable with NumPyro primitives for the model. :param guide: Python callable with NumPyro primitives for the guide. :param args: arguments to the model / guide (these can possibly vary during the course of fitting). :param kwargs: keyword arguments to the model / guide (these can possibly vary during the course of fitting). :return: negative of the Evidence Lower Bound (ELBO) to be minimized.
Evaluates the ELBO with an estimator that uses num_particles many samples/particles.
[ "Evaluates", "the", "ELBO", "with", "an", "estimator", "that", "uses", "num_particles", "many", "samples", "/", "particles", "." ]
def loss(self, rng_key, param_map, model, guide, *args, **kwargs): """ Evaluates the ELBO with an estimator that uses num_particles many samples/particles. :param jax.random.PRNGKey rng_key: random number generator seed. :param dict param_map: dictionary of current parameter values keyed by site name. :param model: Python callable with NumPyro primitives for the model. :param guide: Python callable with NumPyro primitives for the guide. :param args: arguments to the model / guide (these can possibly vary during the course of fitting). :param kwargs: keyword arguments to the model / guide (these can possibly vary during the course of fitting). :return: negative of the Evidence Lower Bound (ELBO) to be minimized. """ return self.loss_with_mutable_state( rng_key, param_map, model, guide, *args, **kwargs )["loss"]
[ "def", "loss", "(", "self", ",", "rng_key", ",", "param_map", ",", "model", ",", "guide", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "loss_with_mutable_state", "(", "rng_key", ",", "param_map", ",", "model", ",", "guide...
https://github.com/pyro-ppl/numpyro/blob/6a0856b7cda82fc255e23adc797bb79f5b7fc904/numpyro/infer/elbo.py#L39-L56
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/ilo.py
python
set_ssh_port
(port=22)
return __execute_cmd("Configure_SSH_Port", _xml)
Enable SSH on a user defined port CLI Example: .. code-block:: bash salt '*' ilo.set_ssh_port 2222
Enable SSH on a user defined port
[ "Enable", "SSH", "on", "a", "user", "defined", "port" ]
def set_ssh_port(port=22): """ Enable SSH on a user defined port CLI Example: .. code-block:: bash salt '*' ilo.set_ssh_port 2222 """ _current = global_settings() if _current["Global Settings"]["SSH_PORT"]["VALUE"] == port: return True _xml = """<RIBCL VERSION="2.0"> <LOGIN USER_LOGIN="adminname" PASSWORD="password"> <RIB_INFO MODE="write"> <MOD_GLOBAL_SETTINGS> <SSH_PORT value="{}"/> </MOD_GLOBAL_SETTINGS> </RIB_INFO> </LOGIN> </RIBCL>""".format( port ) return __execute_cmd("Configure_SSH_Port", _xml)
[ "def", "set_ssh_port", "(", "port", "=", "22", ")", ":", "_current", "=", "global_settings", "(", ")", "if", "_current", "[", "\"Global Settings\"", "]", "[", "\"SSH_PORT\"", "]", "[", "\"VALUE\"", "]", "==", "port", ":", "return", "True", "_xml", "=", "...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/ilo.py#L215-L242
GalSim-developers/GalSim
a05d4ec3b8d8574f99d3b0606ad882cbba53f345
galsim/config/stamp.py
python
StampBuilder.setup
(self, config, base, xsize, ysize, ignore, logger)
return xsize, ysize, image_pos, world_pos
Do the initialization and setup for building a postage stamp. In the base class, we check for and parse the appropriate size and position values in config (aka base['stamp'] or base['image']. Values given in base['stamp'] take precedence if these are given in both places (which would be confusing, so probably shouldn't do that, but there might be a use case where it would make sense). Parameters: config: The configuration dict for the stamp field. base: The base configuration dict. xsize: The xsize of the image to build (if known). ysize: The ysize of the image to build (if known). ignore: A list of parameters that are allowed to be in config that we can ignore here. i.e. it won't be an error if these parameters are present. logger: A logger object to log progress. Returns: xsize, ysize, image_pos, world_pos
Do the initialization and setup for building a postage stamp.
[ "Do", "the", "initialization", "and", "setup", "for", "building", "a", "postage", "stamp", "." ]
def setup(self, config, base, xsize, ysize, ignore, logger): """ Do the initialization and setup for building a postage stamp. In the base class, we check for and parse the appropriate size and position values in config (aka base['stamp'] or base['image']. Values given in base['stamp'] take precedence if these are given in both places (which would be confusing, so probably shouldn't do that, but there might be a use case where it would make sense). Parameters: config: The configuration dict for the stamp field. base: The base configuration dict. xsize: The xsize of the image to build (if known). ysize: The ysize of the image to build (if known). ignore: A list of parameters that are allowed to be in config that we can ignore here. i.e. it won't be an error if these parameters are present. logger: A logger object to log progress. Returns: xsize, ysize, image_pos, world_pos """ # Check for spurious parameters CheckAllParams(config, ignore=ignore) # Update the size if necessary image = base['image'] if not xsize: if 'xsize' in config: xsize = ParseValue(config,'xsize',base,int)[0] elif 'size' in config: xsize = ParseValue(config,'size',base,int)[0] elif 'stamp_xsize' in image: xsize = ParseValue(image,'stamp_xsize',base,int)[0] elif 'stamp_size' in image: xsize = ParseValue(image,'stamp_size',base,int)[0] if not ysize: if 'ysize' in config: ysize = ParseValue(config,'ysize',base,int)[0] elif 'size' in config: ysize = ParseValue(config,'size',base,int)[0] elif 'stamp_ysize' in image: ysize = ParseValue(image,'stamp_ysize',base,int)[0] elif 'stamp_size' in image: ysize = ParseValue(image,'stamp_size',base,int)[0] # Determine where this object is going to go: if 'image_pos' in config: image_pos = ParseValue(config, 'image_pos', base, PositionD)[0] elif 'image_pos' in image: image_pos = ParseValue(image, 'image_pos', base, PositionD)[0] else: image_pos = None if 'world_pos' in config: world_pos = ParseWorldPos(config, 'world_pos', base, logger) elif 'world_pos' in image: world_pos = ParseWorldPos(image, 'world_pos', base, logger) else: world_pos = None return xsize, ysize, image_pos, world_pos
[ "def", "setup", "(", "self", ",", "config", ",", "base", ",", "xsize", ",", "ysize", ",", "ignore", ",", "logger", ")", ":", "# Check for spurious parameters", "CheckAllParams", "(", "config", ",", "ignore", "=", "ignore", ")", "# Update the size if necessary", ...
https://github.com/GalSim-developers/GalSim/blob/a05d4ec3b8d8574f99d3b0606ad882cbba53f345/galsim/config/stamp.py#L584-L647
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/contour/_contours.py
python
Contours.showlabels
(self)
return self["showlabels"]
Determines whether to label the contour lines with their values. The 'showlabels' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether to label the contour lines with their values. The 'showlabels' property must be specified as a bool (either True, or False)
[ "Determines", "whether", "to", "label", "the", "contour", "lines", "with", "their", "values", ".", "The", "showlabels", "property", "must", "be", "specified", "as", "a", "bool", "(", "either", "True", "or", "False", ")" ]
def showlabels(self): """ Determines whether to label the contour lines with their values. The 'showlabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showlabels"]
[ "def", "showlabels", "(", "self", ")", ":", "return", "self", "[", "\"showlabels\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/contour/_contours.py#L175-L187
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/patches.py
python
Rectangle.set_height
(self, h)
Set the height of the rectangle.
Set the height of the rectangle.
[ "Set", "the", "height", "of", "the", "rectangle", "." ]
def set_height(self, h): "Set the height of the rectangle." self._height = h self._update_y1() self.stale = True
[ "def", "set_height", "(", "self", ",", "h", ")", ":", "self", ".", "_height", "=", "h", "self", ".", "_update_y1", "(", ")", "self", ".", "stale", "=", "True" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/patches.py#L763-L767
evhub/coconut
27a4af9dc06667870f736f20c862930001b8cbb2
coconut/compiler/compiler.py
python
Compiler.inner_parse_eval
( self, inputstring, parser=None, preargs={"strip": True}, postargs={"header": "none", "initial": "none", "final_endline": False}, )
Parse eval code in an inner environment.
Parse eval code in an inner environment.
[ "Parse", "eval", "code", "in", "an", "inner", "environment", "." ]
def inner_parse_eval( self, inputstring, parser=None, preargs={"strip": True}, postargs={"header": "none", "initial": "none", "final_endline": False}, ): """Parse eval code in an inner environment.""" if parser is None: parser = self.eval_parser with self.inner_environment(): pre_procd = self.pre(inputstring, **preargs) parsed = parse(parser, pre_procd, inner=True) return self.post(parsed, **postargs)
[ "def", "inner_parse_eval", "(", "self", ",", "inputstring", ",", "parser", "=", "None", ",", "preargs", "=", "{", "\"strip\"", ":", "True", "}", ",", "postargs", "=", "{", "\"header\"", ":", "\"none\"", ",", "\"initial\"", ":", "\"none\"", ",", "\"final_en...
https://github.com/evhub/coconut/blob/27a4af9dc06667870f736f20c862930001b8cbb2/coconut/compiler/compiler.py#L733-L746
stanfordnlp/stanza
e44d1c88340e33bf9813e6f5a6bd24387eefc4b2
stanza/pipeline/multilingual.py
python
MultilingualPipeline._update_pipeline_cache
(self, lang)
Do any necessary updates to the pipeline cache for this language. This includes building a new pipeline for the lang, and possibly clearing out a language with the old last access date.
Do any necessary updates to the pipeline cache for this language. This includes building a new pipeline for the lang, and possibly clearing out a language with the old last access date.
[ "Do", "any", "necessary", "updates", "to", "the", "pipeline", "cache", "for", "this", "language", ".", "This", "includes", "building", "a", "new", "pipeline", "for", "the", "lang", "and", "possibly", "clearing", "out", "a", "language", "with", "the", "old", ...
def _update_pipeline_cache(self, lang): """ Do any necessary updates to the pipeline cache for this language. This includes building a new pipeline for the lang, and possibly clearing out a language with the old last access date. """ # update request history if lang in self.lang_request_history: self.lang_request_history.remove(lang) self.lang_request_history.append(lang) # update language configs if lang not in self.lang_configs: self.lang_configs[lang] = {'lang': lang} # update pipeline cache if lang not in self.pipeline_cache: # clear least recently used lang from pipeline cache if len(self.pipeline_cache) == self.max_cache_size: lru_lang = self.lang_request_history[0] self.pipeline_cache.remove(lru_lang) self.lang_request_history.remove(lru_lang) self.pipeline_cache[lang] = Pipeline(dir=self.model_dir, **self.lang_configs[lang])
[ "def", "_update_pipeline_cache", "(", "self", ",", "lang", ")", ":", "# update request history", "if", "lang", "in", "self", ".", "lang_request_history", ":", "self", ".", "lang_request_history", ".", "remove", "(", "lang", ")", "self", ".", "lang_request_history"...
https://github.com/stanfordnlp/stanza/blob/e44d1c88340e33bf9813e6f5a6bd24387eefc4b2/stanza/pipeline/multilingual.py#L46-L68
ellmetha/django-machina
b38e3fdee9b5f7ea7f6ef980f764c563b67f719a
machina/apps/forum_conversation/forum_polls/urls.py
python
ForumPollsURLPatternsFactory.get_urlpatterns
(self)
return [ path('poll/<int:pk>/vote/', self.poll_vote_view.as_view(), name='topic_poll_vote'), ]
Returns the URL patterns managed by the considered factory / application.
Returns the URL patterns managed by the considered factory / application.
[ "Returns", "the", "URL", "patterns", "managed", "by", "the", "considered", "factory", "/", "application", "." ]
def get_urlpatterns(self): """ Returns the URL patterns managed by the considered factory / application. """ return [ path('poll/<int:pk>/vote/', self.poll_vote_view.as_view(), name='topic_poll_vote'), ]
[ "def", "get_urlpatterns", "(", "self", ")", ":", "return", "[", "path", "(", "'poll/<int:pk>/vote/'", ",", "self", ".", "poll_vote_view", ".", "as_view", "(", ")", ",", "name", "=", "'topic_poll_vote'", ")", ",", "]" ]
https://github.com/ellmetha/django-machina/blob/b38e3fdee9b5f7ea7f6ef980f764c563b67f719a/machina/apps/forum_conversation/forum_polls/urls.py#L21-L25
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/bloomsky/sensor.py
python
setup_platform
( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, )
Set up the available BloomSky weather sensors.
Set up the available BloomSky weather sensors.
[ "Set", "up", "the", "available", "BloomSky", "weather", "sensors", "." ]
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the available BloomSky weather sensors.""" # Default needed in case of discovery if discovery_info is not None: return sensors = config[CONF_MONITORED_CONDITIONS] bloomsky = hass.data[DOMAIN] for device in bloomsky.devices.values(): for variable in sensors: add_entities([BloomSkySensor(bloomsky, device, variable)], True)
[ "def", "setup_platform", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "ConfigType", ",", "add_entities", ":", "AddEntitiesCallback", ",", "discovery_info", ":", "DiscoveryInfoType", "|", "None", "=", "None", ",", ")", "->", "None", ":", "# Default need...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/bloomsky/sensor.py#L73-L89
inkcut/inkcut
d3dea58e13de9f9babb5ed9b562c7326b4efdcd7
inkcut/cli/plugin.py
python
CliPlugin._refresh_commands
(self, change=None)
Reload all CliCommands registered by any Plugins Any plugin can add to this list by providing a CliCommand extension in the PluginManifest. If the system arguments match the command it will be invoked with the given arguments as soon as the plugin that registered the command is loaded. Thus you can effectively hook your cli argument at any stage of the process.
Reload all CliCommands registered by any Plugins Any plugin can add to this list by providing a CliCommand extension in the PluginManifest. If the system arguments match the command it will be invoked with the given arguments as soon as the plugin that registered the command is loaded. Thus you can effectively hook your cli argument at any stage of the process.
[ "Reload", "all", "CliCommands", "registered", "by", "any", "Plugins", "Any", "plugin", "can", "add", "to", "this", "list", "by", "providing", "a", "CliCommand", "extension", "in", "the", "PluginManifest", ".", "If", "the", "system", "arguments", "match", "the"...
def _refresh_commands(self, change=None): """ Reload all CliCommands registered by any Plugins Any plugin can add to this list by providing a CliCommand extension in the PluginManifest. If the system arguments match the command it will be invoked with the given arguments as soon as the plugin that registered the command is loaded. Thus you can effectively hook your cli argument at any stage of the process. """ workbench = self.workbench point = workbench.get_extension_point(extensions.CLI_COMMAND_POINT) commands = [] for extension in sorted(point.extensions, key=lambda ext: ext.rank): for d in extension.get_children(extensions.CliCommand): commands.append(Command( declaration=d, workbench=self.workbench, )) #: Update self.commands = commands #: Log that they've been updated log.debug("CLI | Commands loaded") #: Recreate the parser self.parser = self._default_parser() #: Parse the args, if an error occurs the program will exit #: but if no args are given it continues try: args = self.parser.parse_args() except ArgumentError as e: #: Ignore errors that may occur because commands havent loaded yet if [m for m in ['invalid choice'] if m in str(e.message)]: return self.parser.exit_with_error(e.message) #: Run it but defer it until the next available loop so the current #: plugin finishes loading if hasattr(args, 'cmd'): self.workbench.application.deferred_call(self.run, args.cmd, args) else: log.debug("CLI | No cli command was given.")
[ "def", "_refresh_commands", "(", "self", ",", "change", "=", "None", ")", ":", "workbench", "=", "self", ".", "workbench", "point", "=", "workbench", ".", "get_extension_point", "(", "extensions", ".", "CLI_COMMAND_POINT", ")", "commands", "=", "[", "]", "fo...
https://github.com/inkcut/inkcut/blob/d3dea58e13de9f9babb5ed9b562c7326b4efdcd7/inkcut/cli/plugin.py#L108-L155
whoosh-community/whoosh
5421f1ab3bb802114105b3181b7ce4f44ad7d0bb
src/whoosh/matching/mcore.py
python
Matcher.next
(self)
Moves this matcher to the next posting.
Moves this matcher to the next posting.
[ "Moves", "this", "matcher", "to", "the", "next", "posting", "." ]
def next(self): """Moves this matcher to the next posting. """ raise NotImplementedError(self.__class__.__name__)
[ "def", "next", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "self", ".", "__class__", ".", "__name__", ")" ]
https://github.com/whoosh-community/whoosh/blob/5421f1ab3bb802114105b3181b7ce4f44ad7d0bb/src/whoosh/matching/mcore.py#L308-L312
Tencent/PocketFlow
53b82cba5a34834400619e7c335a23995d45c2a6
utils/multi_gpu_wrapper.py
python
MultiGpuWrapper.init
(cls, *args)
Initialization.
Initialization.
[ "Initialization", "." ]
def init(cls, *args): """Initialization.""" try: return mgw.init(*args) except NameError: raise NameError('module <mgw> not imported')
[ "def", "init", "(", "cls", ",", "*", "args", ")", ":", "try", ":", "return", "mgw", ".", "init", "(", "*", "args", ")", "except", "NameError", ":", "raise", "NameError", "(", "'module <mgw> not imported'", ")" ]
https://github.com/Tencent/PocketFlow/blob/53b82cba5a34834400619e7c335a23995d45c2a6/utils/multi_gpu_wrapper.py#L38-L44
CellProfiler/CellProfiler
a90e17e4d258c6f3900238be0f828e0b4bd1b293
cellprofiler/modules/measureobjectskeleton.py
python
MeasureObjectSkeleton.settings
(self)
return [ self.seed_objects_name, self.image_name, self.wants_branchpoint_image, self.branchpoint_image_name, self.wants_to_fill_holes, self.maximum_hole_size, self.wants_objskeleton_graph, self.intensity_image_name, self.directory, self.vertex_file_name, self.edge_file_name, ]
The settings, in the order that they are saved in the pipeline
The settings, in the order that they are saved in the pipeline
[ "The", "settings", "in", "the", "order", "that", "they", "are", "saved", "in", "the", "pipeline" ]
def settings(self): """The settings, in the order that they are saved in the pipeline""" return [ self.seed_objects_name, self.image_name, self.wants_branchpoint_image, self.branchpoint_image_name, self.wants_to_fill_holes, self.maximum_hole_size, self.wants_objskeleton_graph, self.intensity_image_name, self.directory, self.vertex_file_name, self.edge_file_name, ]
[ "def", "settings", "(", "self", ")", ":", "return", "[", "self", ".", "seed_objects_name", ",", "self", ".", "image_name", ",", "self", ".", "wants_branchpoint_image", ",", "self", ".", "branchpoint_image_name", ",", "self", ".", "wants_to_fill_holes", ",", "s...
https://github.com/CellProfiler/CellProfiler/blob/a90e17e4d258c6f3900238be0f828e0b4bd1b293/cellprofiler/modules/measureobjectskeleton.py#L262-L276
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/concrete/expr_with_limits.py
python
_process_limits
(*symbols)
return limits, orientation
Process the list of symbols and convert them to canonical limits, storing them as Tuple(symbol, lower, upper). The orientation of the function is also returned when the upper limit is missing so (x, 1, None) becomes (x, None, 1) and the orientation is changed.
Process the list of symbols and convert them to canonical limits, storing them as Tuple(symbol, lower, upper). The orientation of the function is also returned when the upper limit is missing so (x, 1, None) becomes (x, None, 1) and the orientation is changed.
[ "Process", "the", "list", "of", "symbols", "and", "convert", "them", "to", "canonical", "limits", "storing", "them", "as", "Tuple", "(", "symbol", "lower", "upper", ")", ".", "The", "orientation", "of", "the", "function", "is", "also", "returned", "when", ...
def _process_limits(*symbols): """Process the list of symbols and convert them to canonical limits, storing them as Tuple(symbol, lower, upper). The orientation of the function is also returned when the upper limit is missing so (x, 1, None) becomes (x, None, 1) and the orientation is changed. """ limits = [] orientation = 1 for V in symbols: if isinstance(V, Symbol): limits.append(Tuple(V)) continue elif is_sequence(V, Tuple): V = sympify(flatten(V)) if V[0].is_Symbol: newsymbol = V[0] if len(V) == 2 and isinstance(V[1], Interval): V[1:] = [V[1].start, V[1].end] if len(V) == 3: if V[1] is None and V[2] is not None: nlim = [V[2]] elif V[1] is not None and V[2] is None: orientation *= -1 nlim = [V[1]] elif V[1] is None and V[2] is None: nlim = [] else: nlim = V[1:] limits.append(Tuple(newsymbol, *nlim )) continue elif len(V) == 1 or (len(V) == 2 and V[1] is None): limits.append(Tuple(newsymbol)) continue elif len(V) == 2: limits.append(Tuple(newsymbol, V[1])) continue raise ValueError('Invalid limits given: %s' % str(symbols)) return limits, orientation
[ "def", "_process_limits", "(", "*", "symbols", ")", ":", "limits", "=", "[", "]", "orientation", "=", "1", "for", "V", "in", "symbols", ":", "if", "isinstance", "(", "V", ",", "Symbol", ")", ":", "limits", ".", "append", "(", "Tuple", "(", "V", ")"...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/concrete/expr_with_limits.py#L18-L58
freqtrade/technical
c311967270d62ad7a46fa0ee7878af1a2e73d77e
technical/vendor/qtpylib/indicators.py
python
chopiness
(bars, window=14)
return 100 * np.log10(atrsum / (highs - lows)) / np.log10(window)
[]
def chopiness(bars, window=14): atrsum = true_range(bars).rolling(window).sum() highs = bars['high'].rolling(window).max() lows = bars['low'].rolling(window).min() return 100 * np.log10(atrsum / (highs - lows)) / np.log10(window)
[ "def", "chopiness", "(", "bars", ",", "window", "=", "14", ")", ":", "atrsum", "=", "true_range", "(", "bars", ")", ".", "rolling", "(", "window", ")", ".", "sum", "(", ")", "highs", "=", "bars", "[", "'high'", "]", ".", "rolling", "(", "window", ...
https://github.com/freqtrade/technical/blob/c311967270d62ad7a46fa0ee7878af1a2e73d77e/technical/vendor/qtpylib/indicators.py#L605-L609
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op2/tables/oes_stressStrain/complex/oes_bush.py
python
ComplexCBushArray.build_dataframe
(self)
creates a pandas dataframe
creates a pandas dataframe
[ "creates", "a", "pandas", "dataframe" ]
def build_dataframe(self): """creates a pandas dataframe""" # Freq 0.0 2.5 # ElementID Item # 10210 tx 0.010066-0.000334j 0.010066-0.000334j # ty 0.000000+0.000000j 0.000000+0.000000j # tz 0.431447-0.009564j 0.431461-0.009564j # rx 0.000000+0.000000j 0.000000+0.000000j # ry 0.000000+0.000000j 0.000000+0.000000j # rz 0.000000+0.000000j 0.000000+0.000000j # 10211 tx -0.000002+0.000000j -0.000002+0.000000j headers = self.get_headers() column_names, column_values = self._build_dataframe_transient_header() self.data_frame = self._build_pandas_transient_elements( column_values, column_names, headers, self.element, self.data)
[ "def", "build_dataframe", "(", "self", ")", ":", "# Freq 0.0 2.5", "# ElementID Item", "# 10210 tx 0.010066-0.000334j 0.010066-0.000334j", "# ty 0.000000+0.000000j 0.000000+0.000000j", "# tz 0.431447-0.009564j 0.431461-...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/tables/oes_stressStrain/complex/oes_bush.py#L59-L74
laramies/metagoofil
823b1146eb13a6e5c4f72b33461af5289b191abb
hachoir_core/tools.py
python
humanDatetime
(value, strip_microsecond=True)
return text
Convert a timestamp to Unicode string: use ISO format with space separator. >>> humanDatetime( datetime(2006, 7, 29, 12, 20, 44) ) u'2006-07-29 12:20:44' >>> humanDatetime( datetime(2003, 6, 30, 16, 0, 5, 370000) ) u'2003-06-30 16:00:05' >>> humanDatetime( datetime(2003, 6, 30, 16, 0, 5, 370000), False ) u'2003-06-30 16:00:05.370000'
Convert a timestamp to Unicode string: use ISO format with space separator.
[ "Convert", "a", "timestamp", "to", "Unicode", "string", ":", "use", "ISO", "format", "with", "space", "separator", "." ]
def humanDatetime(value, strip_microsecond=True): """ Convert a timestamp to Unicode string: use ISO format with space separator. >>> humanDatetime( datetime(2006, 7, 29, 12, 20, 44) ) u'2006-07-29 12:20:44' >>> humanDatetime( datetime(2003, 6, 30, 16, 0, 5, 370000) ) u'2003-06-30 16:00:05' >>> humanDatetime( datetime(2003, 6, 30, 16, 0, 5, 370000), False ) u'2003-06-30 16:00:05.370000' """ text = unicode(value.isoformat()) text = text.replace('T', ' ') if strip_microsecond and "." in text: text = text.split(".")[0] return text
[ "def", "humanDatetime", "(", "value", ",", "strip_microsecond", "=", "True", ")", ":", "text", "=", "unicode", "(", "value", ".", "isoformat", "(", ")", ")", "text", "=", "text", ".", "replace", "(", "'T'", ",", "' '", ")", "if", "strip_microsecond", "...
https://github.com/laramies/metagoofil/blob/823b1146eb13a6e5c4f72b33461af5289b191abb/hachoir_core/tools.py#L548-L563
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/distutils/command/register.py
python
register.verify_metadata
(self)
Send the metadata to the package index server to be checked.
Send the metadata to the package index server to be checked.
[ "Send", "the", "metadata", "to", "the", "package", "index", "server", "to", "be", "checked", "." ]
def verify_metadata(self): ''' Send the metadata to the package index server to be checked. ''' # send the info to the server and report the result (code, result) = self.post_to_server(self.build_post_data('verify')) log.info('Server response (%s): %s' % (code, result))
[ "def", "verify_metadata", "(", "self", ")", ":", "# send the info to the server and report the result", "(", "code", ",", "result", ")", "=", "self", ".", "post_to_server", "(", "self", ".", "build_post_data", "(", "'verify'", ")", ")", "log", ".", "info", "(", ...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/distutils/command/register.py#L92-L97
ConsenSys/mythril
d00152f8e4d925c7749d63b533152a937e1dd516
mythril/mythril/mythril_analyzer.py
python
MythrilAnalyzer.graph_html
( self, contract: EVMContract = None, enable_physics: bool = False, phrackify: bool = False, transaction_count: Optional[int] = None, )
return generate_graph(sym, physics=enable_physics, phrackify=phrackify)
:param contract: The Contract on which the analysis should be done :param enable_physics: If true then enables the graph physics simulation :param phrackify: If true generates Phrack-style call graph :param transaction_count: The amount of transactions to be executed :return: The generated graph in html format
[]
def graph_html( self, contract: EVMContract = None, enable_physics: bool = False, phrackify: bool = False, transaction_count: Optional[int] = None, ) -> str: """ :param contract: The Contract on which the analysis should be done :param enable_physics: If true then enables the graph physics simulation :param phrackify: If true generates Phrack-style call graph :param transaction_count: The amount of transactions to be executed :return: The generated graph in html format """ sym = SymExecWrapper( contract or self.contracts[0], self.address, self.strategy, dynloader=DynLoader(self.eth, active=self.use_onchain_data), max_depth=self.max_depth, execution_timeout=self.execution_timeout, transaction_count=transaction_count, create_timeout=self.create_timeout, disable_dependency_pruning=self.disable_dependency_pruning, run_analysis_modules=False, custom_modules_directory=self.custom_modules_directory, ) return generate_graph(sym, physics=enable_physics, phrackify=phrackify)
[ "def", "graph_html", "(", "self", ",", "contract", ":", "EVMContract", "=", "None", ",", "enable_physics", ":", "bool", "=", "False", ",", "phrackify", ":", "bool", "=", "False", ",", "transaction_count", ":", "Optional", "[", "int", "]", "=", "None", ",...
https://github.com/ConsenSys/mythril/blob/d00152f8e4d925c7749d63b533152a937e1dd516/mythril/mythril/mythril_analyzer.py#L100-L129
terrencepreilly/darglint
abc26b768cd7135d848223ba53f68323593c33d5
darglint/analysis/raise_visitor.py
python
RaiseVisitor.visit_Raise
(self, node)
return self.generic_visit(node)
[]
def visit_Raise(self, node): # type: (ast.Raise) -> ast.AST bubbles = self.context.add_exception(node) if bubbles: if len(self.contexts) < 2: return self.generic_visit(node) parent_context = self.contexts[-2] parent_context.exceptions |= bubbles return self.generic_visit(node)
[ "def", "visit_Raise", "(", "self", ",", "node", ")", ":", "# type: (ast.Raise) -> ast.AST", "bubbles", "=", "self", ".", "context", ".", "add_exception", "(", "node", ")", "if", "bubbles", ":", "if", "len", "(", "self", ".", "contexts", ")", "<", "2", ":...
https://github.com/terrencepreilly/darglint/blob/abc26b768cd7135d848223ba53f68323593c33d5/darglint/analysis/raise_visitor.py#L275-L284
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/names/client.py
python
Resolver._openFile
(self, path)
return FilePath(path).open()
Wrapper used for opening files in the class, exists primarily for unit testing purposes.
Wrapper used for opening files in the class, exists primarily for unit testing purposes.
[ "Wrapper", "used", "for", "opening", "files", "in", "the", "class", "exists", "primarily", "for", "unit", "testing", "purposes", "." ]
def _openFile(self, path): """ Wrapper used for opening files in the class, exists primarily for unit testing purposes. """ return FilePath(path).open()
[ "def", "_openFile", "(", "self", ",", "path", ")", ":", "return", "FilePath", "(", "path", ")", ".", "open", "(", ")" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/names/client.py#L134-L139
fabioz/PyDev.Debugger
0f8c02a010fe5690405da1dd30ed72326191ce63
_pydevd_bundle/pydevd_vars.py
python
resolve_compound_var_object_fields
(var, attrs)
Resolve compound variable by its object and attributes :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields
Resolve compound variable by its object and attributes
[ "Resolve", "compound", "variable", "by", "its", "object", "and", "attributes" ]
def resolve_compound_var_object_fields(var, attrs): """ Resolve compound variable by its object and attributes :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields """ attr_list = attrs.split('\t') for k in attr_list: type, _type_name, resolver = get_type(var) var = resolver.resolve(var, k) try: type, _type_name, resolver = get_type(var) return resolver.get_dictionary(var) except: pydev_log.exception()
[ "def", "resolve_compound_var_object_fields", "(", "var", ",", "attrs", ")", ":", "attr_list", "=", "attrs", ".", "split", "(", "'\\t'", ")", "for", "k", "in", "attr_list", ":", "type", ",", "_type_name", ",", "resolver", "=", "get_type", "(", "var", ")", ...
https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/_pydevd_bundle/pydevd_vars.py#L169-L187
Unrepl/unravel
2d21ee323eae8e9c246b291a333fab2c893a5cb0
scripts/sh.py
python
pushd
(path)
pushd changes the actual working directory for the duration of the context, unlike the _cwd arg this will work with other built-ins such as sh.glob correctly
pushd changes the actual working directory for the duration of the context, unlike the _cwd arg this will work with other built-ins such as sh.glob correctly
[ "pushd", "changes", "the", "actual", "working", "directory", "for", "the", "duration", "of", "the", "context", "unlike", "the", "_cwd", "arg", "this", "will", "work", "with", "other", "built", "-", "ins", "such", "as", "sh", ".", "glob", "correctly" ]
def pushd(path): """ pushd changes the actual working directory for the duration of the context, unlike the _cwd arg this will work with other built-ins such as sh.glob correctly """ orig_path = os.getcwd() os.chdir(path) try: yield finally: os.chdir(orig_path)
[ "def", "pushd", "(", "path", ")", ":", "orig_path", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "path", ")", "try", ":", "yield", "finally", ":", "os", ".", "chdir", "(", "orig_path", ")" ]
https://github.com/Unrepl/unravel/blob/2d21ee323eae8e9c246b291a333fab2c893a5cb0/scripts/sh.py#L3074-L3083
Alfanous-team/alfanous
594514729473c24efa3908e3107b45a38255de4b
src/alfanous/Support/whoosh/qparser/default.py
python
PyparsingBasedParser.parse
(self, input, normalize=True)
return q
Parses the input string and returns a Query object/tree. This method may return None if the input string does not result in any valid queries. It may also raise a variety of exceptions if the input string is malformed. :param input: the unicode string to parse. :param normalize: whether to call normalize() on the query object/tree before returning it. This should be left on unless you're trying to debug the parser output. :rtype: :class:`whoosh.query.Query`
Parses the input string and returns a Query object/tree. This method may return None if the input string does not result in any valid queries. It may also raise a variety of exceptions if the input string is malformed. :param input: the unicode string to parse. :param normalize: whether to call normalize() on the query object/tree before returning it. This should be left on unless you're trying to debug the parser output. :rtype: :class:`whoosh.query.Query`
[ "Parses", "the", "input", "string", "and", "returns", "a", "Query", "object", "/", "tree", ".", "This", "method", "may", "return", "None", "if", "the", "input", "string", "does", "not", "result", "in", "any", "valid", "queries", ".", "It", "may", "also",...
def parse(self, input, normalize=True): """Parses the input string and returns a Query object/tree. This method may return None if the input string does not result in any valid queries. It may also raise a variety of exceptions if the input string is malformed. :param input: the unicode string to parse. :param normalize: whether to call normalize() on the query object/tree before returning it. This should be left on unless you're trying to debug the parser output. :rtype: :class:`whoosh.query.Query` """ ast = self.parser(input)[0] q = self._eval(ast, self.default_field) if q and normalize: q = q.normalize() return q
[ "def", "parse", "(", "self", ",", "input", ",", "normalize", "=", "True", ")", ":", "ast", "=", "self", ".", "parser", "(", "input", ")", "[", "0", "]", "q", "=", "self", ".", "_eval", "(", "ast", ",", "self", ".", "default_field", ")", "if", "...
https://github.com/Alfanous-team/alfanous/blob/594514729473c24efa3908e3107b45a38255de4b/src/alfanous/Support/whoosh/qparser/default.py#L148-L166
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/versioned_label.py
python
VersionedLabel.comments
(self)
return self._comments
Gets the comments of this VersionedLabel. The user-supplied comments for the component :return: The comments of this VersionedLabel. :rtype: str
Gets the comments of this VersionedLabel. The user-supplied comments for the component
[ "Gets", "the", "comments", "of", "this", "VersionedLabel", ".", "The", "user", "-", "supplied", "comments", "for", "the", "component" ]
def comments(self): """ Gets the comments of this VersionedLabel. The user-supplied comments for the component :return: The comments of this VersionedLabel. :rtype: str """ return self._comments
[ "def", "comments", "(", "self", ")", ":", "return", "self", ".", "_comments" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/versioned_label.py#L143-L151
pyparsing/pyparsing
1ccf846394a055924b810faaf9628dac53633848
pyparsing/helpers.py
python
one_of
( strs: Union[IterableType[str], str], caseless: bool = False, use_regex: bool = True, as_keyword: bool = False, *, useRegex: bool = True, asKeyword: bool = False, )
return MatchFirst(parseElementClass(sym) for sym in symbols).set_name( " | ".join(symbols) )
Helper to quickly define a set of alternative :class:`Literal` s, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a :class:`MatchFirst` for best performance. Parameters: - ``strs`` - a string of space-delimited literals, or a collection of string literals - ``caseless`` - treat all literals as caseless - (default= ``False``) - ``use_regex`` - as an optimization, will generate a :class:`Regex` object; otherwise, will generate a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if creating a :class:`Regex` raises an exception) - (default= ``True``) - ``as_keyword`` - enforce :class:`Keyword`-style matching on the generated expressions - (default= ``False``) - ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility, but will be removed in a future release Example:: comp_oper = one_of("< = > <= >= !=") var = Word(alphas) number = Word(nums) term = var | number comparison_expr = term + comp_oper + term print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12")) prints:: [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]
Helper to quickly define a set of alternative :class:`Literal` s, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a :class:`MatchFirst` for best performance.
[ "Helper", "to", "quickly", "define", "a", "set", "of", "alternative", ":", "class", ":", "Literal", "s", "and", "makes", "sure", "to", "do", "longest", "-", "first", "testing", "when", "there", "is", "a", "conflict", "regardless", "of", "the", "input", "...
def one_of( strs: Union[IterableType[str], str], caseless: bool = False, use_regex: bool = True, as_keyword: bool = False, *, useRegex: bool = True, asKeyword: bool = False, ) -> ParserElement: """Helper to quickly define a set of alternative :class:`Literal` s, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a :class:`MatchFirst` for best performance. Parameters: - ``strs`` - a string of space-delimited literals, or a collection of string literals - ``caseless`` - treat all literals as caseless - (default= ``False``) - ``use_regex`` - as an optimization, will generate a :class:`Regex` object; otherwise, will generate a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if creating a :class:`Regex` raises an exception) - (default= ``True``) - ``as_keyword`` - enforce :class:`Keyword`-style matching on the generated expressions - (default= ``False``) - ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility, but will be removed in a future release Example:: comp_oper = one_of("< = > <= >= !=") var = Word(alphas) number = Word(nums) term = var | number comparison_expr = term + comp_oper + term print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12")) prints:: [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] """ asKeyword = asKeyword or as_keyword useRegex = useRegex and use_regex if ( isinstance(caseless, str_type) and __diag__.warn_on_multiple_string_args_to_oneof ): warnings.warn( "More than one string argument passed to one_of, pass" " choices as a list or space-delimited string", stacklevel=2, ) if caseless: isequal = lambda a, b: a.upper() == b.upper() masks = lambda a, b: b.upper().startswith(a.upper()) parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral else: isequal = lambda a, b: a == b masks = lambda a, b: b.startswith(a) parseElementClass = Keyword if asKeyword else Literal symbols: List[str] = [] if isinstance(strs, str_type): symbols = strs.split() elif isinstance(strs, Iterable): symbols = list(strs) else: raise TypeError("Invalid argument to one_of, expected string or iterable") if not symbols: return NoMatch() # reorder given symbols to take care to avoid masking longer choices with shorter ones # (but only if the given symbols are not just single characters) if any(len(sym) > 1 for sym in symbols): i = 0 while i < len(symbols) - 1: cur = symbols[i] for j, other in enumerate(symbols[i + 1 :]): if isequal(other, cur): del symbols[i + j + 1] break elif masks(cur, other): del symbols[i + j + 1] symbols.insert(i, other) break else: i += 1 if useRegex: re_flags: int = re.IGNORECASE if caseless else 0 try: if all(len(sym) == 1 for sym in symbols): # symbols are just single characters, create range regex pattern patt = "[{}]".format( "".join(_escape_regex_range_chars(sym) for sym in symbols) ) else: patt = "|".join(re.escape(sym) for sym in symbols) # wrap with \b word break markers if defining as keywords if asKeyword: patt = r"\b(?:{})\b".format(patt) ret = Regex(patt, flags=re_flags).set_name(" | ".join(symbols)) if caseless: # add parse action to return symbols as specified, not in random # casing as found in input string symbol_map = {sym.lower(): sym for sym in symbols} ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()]) return ret except sre_constants.error: warnings.warn( "Exception creating Regex for one_of, building MatchFirst", stacklevel=2 ) # last resort, just use MatchFirst return MatchFirst(parseElementClass(sym) for sym in symbols).set_name( " | ".join(symbols) )
[ "def", "one_of", "(", "strs", ":", "Union", "[", "IterableType", "[", "str", "]", ",", "str", "]", ",", "caseless", ":", "bool", "=", "False", ",", "use_regex", ":", "bool", "=", "True", ",", "as_keyword", ":", "bool", "=", "False", ",", "*", ",", ...
https://github.com/pyparsing/pyparsing/blob/1ccf846394a055924b810faaf9628dac53633848/pyparsing/helpers.py#L197-L321
open-mmlab/mmskeleton
b4c076baa9e02e69b5876c49fa7c509866d902c7
mmskeleton/models/backbones/hrnet.py
python
HRNet.forward
(self, x)
return y_list
[]
def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) x = self.layer1(x) x_list = [] for i in range(self.stage2_cfg['num_branches']): if self.transition1[i] is not None: x_list.append(self.transition1[i](x)) else: x_list.append(x) y_list = self.stage2(x_list) x_list = [] for i in range(self.stage3_cfg['num_branches']): if self.transition2[i] is not None: x_list.append(self.transition2[i](y_list[-1])) else: x_list.append(y_list[i]) y_list = self.stage3(x_list) x_list = [] for i in range(self.stage4_cfg['num_branches']): if self.transition3[i] is not None: x_list.append(self.transition3[i](y_list[-1])) else: x_list.append(y_list[i]) y_list = self.stage4(x_list) return y_list
[ "def", "forward", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "conv1", "(", "x", ")", "x", "=", "self", ".", "bn1", "(", "x", ")", "x", "=", "self", ".", "relu", "(", "x", ")", "x", "=", "self", ".", "conv2", "(", "x", ")", ...
https://github.com/open-mmlab/mmskeleton/blob/b4c076baa9e02e69b5876c49fa7c509866d902c7/mmskeleton/models/backbones/hrnet.py#L424-L456
enthought/traitsui
b7c38c7a47bf6ae7971f9ddab70c8a358647dd25
traitsui/wx/tree_editor.py
python
SimpleEditor.update_editor
(self)
Updates the editor when the object trait changes externally to the editor.
Updates the editor when the object trait changes externally to the editor.
[ "Updates", "the", "editor", "when", "the", "object", "trait", "changes", "externally", "to", "the", "editor", "." ]
def update_editor(self): """Updates the editor when the object trait changes externally to the editor. """ tree = self._tree saved_state = {} if tree is not None: nid = tree.GetRootItem() if nid.IsOk(): self._delete_node(nid) object, node = self._node_for(self.value) if node is not None: icon = self._get_icon(node, object) self._root_nid = nid = tree.AddRoot( node.get_label(object), icon, icon ) self._map[id(object)] = [(node.get_children_id(object), nid)] self._add_listeners(node, object) self._set_node_data(nid, (False, node, object)) if self.factory.hide_root or self._has_children(node, object): tree.SetItemHasChildren(nid, True) self._expand_node(nid) if not self.factory.hide_root: tree.Expand(nid) tree.SelectItem(nid) self._on_tree_sel_changed() self.expand_levels(nid, self.factory.auto_open, False) # It seems like in some cases, an explicit Refresh is needed to # trigger a screen update: tree.Refresh()
[ "def", "update_editor", "(", "self", ")", ":", "tree", "=", "self", ".", "_tree", "saved_state", "=", "{", "}", "if", "tree", "is", "not", "None", ":", "nid", "=", "tree", ".", "GetRootItem", "(", ")", "if", "nid", ".", "IsOk", "(", ")", ":", "se...
https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/wx/tree_editor.py#L400-L431
dmnfarrell/pandastable
9c268b3e2bfe2e718eaee4a30bd02832a0ad1614
pandastable/stats.py
python
StatsViewer.plotPrediction
(self, fit, ax)
return
Plot predicted vs. test
Plot predicted vs. test
[ "Plot", "predicted", "vs", ".", "test" ]
def plotPrediction(self, fit, ax): """Plot predicted vs. test""" sub = self.sub if len(sub) == 0: sub = X.index Xout = self.X.ix[~self.X.index.isin(sub)] yout = self.y.ix[~self.y.index.isin(sub)] ypred = fit.predict(Xout) ax.scatter(yout, ypred, alpha=0.6, edgecolor='black', color='blue', lw=0.5, label='fit') ax.plot(ax.get_xlim(), ax.get_xlim(), ls="--", lw=2, c=".2") ax.set_xlabel('test') ax.set_ylabel('predicted') ax.set_title('predicted vs test data') import statsmodels.tools.eval_measures as em yt = yout.squeeze().values rmse = em.rmse(yt, ypred) ax.text(0.9,0.1,'rmse: '+ str(round(rmse,3)),ha='right', va='top', transform=ax.transAxes) return
[ "def", "plotPrediction", "(", "self", ",", "fit", ",", "ax", ")", ":", "sub", "=", "self", ".", "sub", "if", "len", "(", "sub", ")", "==", "0", ":", "sub", "=", "X", ".", "index", "Xout", "=", "self", ".", "X", ".", "ix", "[", "~", "self", ...
https://github.com/dmnfarrell/pandastable/blob/9c268b3e2bfe2e718eaee4a30bd02832a0ad1614/pandastable/stats.py#L227-L247
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/gslib/third_party/storage_apitools/transfer.py
python
Upload.StreamInChunks
(self, callback=None, finish_callback=None, additional_headers=None)
return self.__StreamMedia( callback=callback, finish_callback=finish_callback, additional_headers=additional_headers)
Send this (resumable) upload in chunks.
Send this (resumable) upload in chunks.
[ "Send", "this", "(", "resumable", ")", "upload", "in", "chunks", "." ]
def StreamInChunks(self, callback=None, finish_callback=None, additional_headers=None): """Send this (resumable) upload in chunks.""" return self.__StreamMedia( callback=callback, finish_callback=finish_callback, additional_headers=additional_headers)
[ "def", "StreamInChunks", "(", "self", ",", "callback", "=", "None", ",", "finish_callback", "=", "None", ",", "additional_headers", "=", "None", ")", ":", "return", "self", ".", "__StreamMedia", "(", "callback", "=", "callback", ",", "finish_callback", "=", ...
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/gslib/third_party/storage_apitools/transfer.py#L792-L797
scoursen/django-softdelete
290b3ee583730dc85e59b123b3323edfb946572b
softdelete/models.py
python
SoftDeleteObject.undelete
(self, using='default', *args, **kwargs)
[]
def undelete(self, using='default', *args, **kwargs): logging.debug('UNDELETING %s' % self) cs = kwargs.get('changeset') or _determine_change_set(self, False) cs.undelete(using) logging.debug('FINISHED UNDELETING RELATED %s', self)
[ "def", "undelete", "(", "self", ",", "using", "=", "'default'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "'UNDELETING %s'", "%", "self", ")", "cs", "=", "kwargs", ".", "get", "(", "'changeset'", ")", "or", ...
https://github.com/scoursen/django-softdelete/blob/290b3ee583730dc85e59b123b3323edfb946572b/softdelete/models.py#L258-L262
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/feature_extraction/text.py
python
_document_frequency
(X)
Count the number of non-zero values for each feature in sparse X.
Count the number of non-zero values for each feature in sparse X.
[ "Count", "the", "number", "of", "non", "-", "zero", "values", "for", "each", "feature", "in", "sparse", "X", "." ]
def _document_frequency(X): """Count the number of non-zero values for each feature in sparse X.""" if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) else: return np.diff(X.indptr)
[ "def", "_document_frequency", "(", "X", ")", ":", "if", "sp", ".", "isspmatrix_csr", "(", "X", ")", ":", "return", "np", ".", "bincount", "(", "X", ".", "indices", ",", "minlength", "=", "X", ".", "shape", "[", "1", "]", ")", "else", ":", "return",...
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/feature_extraction/text.py#L876-L881
plaid/plaid-python
8c60fca608e426f3ff30da8857775946d29e122c
plaid/model/paystub.py
python
Paystub.openapi_types
()
return { 'deductions': (Deductions,), # noqa: E501 'doc_id': (str,), # noqa: E501 'earnings': (Earnings,), # noqa: E501 'employee': (Employee,), # noqa: E501 'employer': (PaystubEmployer,), # noqa: E501 'net_pay': (NetPay,), # noqa: E501 'pay_period_details': (PayPeriodDetails,), # noqa: E501 'verification': (PaystubVerification,), # noqa: E501 'employment_details': (EmploymentDetails,), # noqa: E501 'paystub_details': (PaystubDetails,), # noqa: E501 'income_breakdown': ([IncomeBreakdown],), # noqa: E501 'ytd_earnings': (PaystubYTDDetails,), # noqa: E501 }
This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type.
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { 'deductions': (Deductions,), # noqa: E501 'doc_id': (str,), # noqa: E501 'earnings': (Earnings,), # noqa: E501 'employee': (Employee,), # noqa: E501 'employer': (PaystubEmployer,), # noqa: E501 'net_pay': (NetPay,), # noqa: E501 'pay_period_details': (PayPeriodDetails,), # noqa: E501 'verification': (PaystubVerification,), # noqa: E501 'employment_details': (EmploymentDetails,), # noqa: E501 'paystub_details': (PaystubDetails,), # noqa: E501 'income_breakdown': ([IncomeBreakdown],), # noqa: E501 'ytd_earnings': (PaystubYTDDetails,), # noqa: E501 }
[ "def", "openapi_types", "(", ")", ":", "lazy_import", "(", ")", "return", "{", "'deductions'", ":", "(", "Deductions", ",", ")", ",", "# noqa: E501", "'doc_id'", ":", "(", "str", ",", ")", ",", "# noqa: E501", "'earnings'", ":", "(", "Earnings", ",", ")"...
https://github.com/plaid/plaid-python/blob/8c60fca608e426f3ff30da8857775946d29e122c/plaid/model/paystub.py#L94-L117
l11x0m7/lightnn
2a2e23610779a2a5b008967b4e6d518988cb3279
lightnn/layers/core.py
python
Dropout.__init__
(self, dropout=0., axis=None)
Dropout层 # Params dropout: dropout的概率 axis: 沿某个维度axis进行dropout操作,如果为None则是对所有元素进行
Dropout层
[ "Dropout层" ]
def __init__(self, dropout=0., axis=None): """ Dropout层 # Params dropout: dropout的概率 axis: 沿某个维度axis进行dropout操作,如果为None则是对所有元素进行 """ super(Dropout, self).__init__() self.dropout = dropout self.axis = axis self.mask = None
[ "def", "__init__", "(", "self", ",", "dropout", "=", "0.", ",", "axis", "=", "None", ")", ":", "super", "(", "Dropout", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "dropout", "=", "dropout", "self", ".", "axis", "=", "axis", "self", ...
https://github.com/l11x0m7/lightnn/blob/2a2e23610779a2a5b008967b4e6d518988cb3279/lightnn/layers/core.py#L200-L211
i-pan/kaggle-rsna18
2db498fe99615d935aa676f04847d0c562fd8e46
models/DeformableConvNets/lib/dataset/coco.py
python
coco._load_image_set_index
(self)
return image_ids
image id: int
image id: int
[ "image", "id", ":", "int" ]
def _load_image_set_index(self): """ image id: int """ 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/i-pan/kaggle-rsna18/blob/2db498fe99615d935aa676f04847d0c562fd8e46/models/DeformableConvNets/lib/dataset/coco.py#L115-L118
JustDoPython/python-100-day
4e75007195aa4cdbcb899aeb06b9b08996a4606c
FusionFace/fusionFace.py
python
image2base64
(imagePath)
图片转base64 :param image_path: 图片地址 :return: base64
图片转base64 :param image_path: 图片地址 :return: base64
[ "图片转base64", ":", "param", "image_path", ":", "图片地址", ":", "return", ":", "base64" ]
def image2base64(imagePath): ''' 图片转base64 :param image_path: 图片地址 :return: base64 ''' with open(imagePath, 'rb') as f: base64_data = base64.b64encode(f.read()) s = base64_data.decode() return s
[ "def", "image2base64", "(", "imagePath", ")", ":", "with", "open", "(", "imagePath", ",", "'rb'", ")", "as", "f", ":", "base64_data", "=", "base64", ".", "b64encode", "(", "f", ".", "read", "(", ")", ")", "s", "=", "base64_data", ".", "decode", "(", ...
https://github.com/JustDoPython/python-100-day/blob/4e75007195aa4cdbcb899aeb06b9b08996a4606c/FusionFace/fusionFace.py#L62-L71
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/time/core.py
python
Time._get_delta_ut1_utc
(self, jd1=None, jd2=None)
return self._delta_ut1_utc
Get ERFA DUT arg = UT1 - UTC. This getter takes optional jd1 and jd2 args because it gets called that way when converting time scales. If delta_ut1_utc is not yet set, this will interpolate them from the the IERS table.
Get ERFA DUT arg = UT1 - UTC. This getter takes optional jd1 and jd2 args because it gets called that way when converting time scales. If delta_ut1_utc is not yet set, this will interpolate them from the the IERS table.
[ "Get", "ERFA", "DUT", "arg", "=", "UT1", "-", "UTC", ".", "This", "getter", "takes", "optional", "jd1", "and", "jd2", "args", "because", "it", "gets", "called", "that", "way", "when", "converting", "time", "scales", ".", "If", "delta_ut1_utc", "is", "not...
def _get_delta_ut1_utc(self, jd1=None, jd2=None): """ Get ERFA DUT arg = UT1 - UTC. This getter takes optional jd1 and jd2 args because it gets called that way when converting time scales. If delta_ut1_utc is not yet set, this will interpolate them from the the IERS table. """ # Sec. 4.3.1: the arg DUT is the quantity delta_UT1 = UT1 - UTC in # seconds. It is obtained from tables published by the IERS. if not hasattr(self, '_delta_ut1_utc'): from astropy.utils.iers import earth_orientation_table iers_table = earth_orientation_table.get() # jd1, jd2 are normally set (see above), except if delta_ut1_utc # is access directly; ensure we behave as expected for that case if jd1 is None: self_utc = self.utc jd1, jd2 = self_utc._time.jd1, self_utc._time.jd2_filled scale = 'utc' else: scale = self.scale # interpolate UT1-UTC in IERS table delta = iers_table.ut1_utc(jd1, jd2) # if we interpolated using UT1 jds, we may be off by one # second near leap seconds (and very slightly off elsewhere) if scale == 'ut1': # calculate UTC using the offset we got; the ERFA routine # is tolerant of leap seconds, so will do this right jd1_utc, jd2_utc = erfa.ut1utc(jd1, jd2, delta.to_value(u.s)) # calculate a better estimate using the nearly correct UTC delta = iers_table.ut1_utc(jd1_utc, jd2_utc) self._set_delta_ut1_utc(delta) return self._delta_ut1_utc
[ "def", "_get_delta_ut1_utc", "(", "self", ",", "jd1", "=", "None", ",", "jd2", "=", "None", ")", ":", "# Sec. 4.3.1: the arg DUT is the quantity delta_UT1 = UT1 - UTC in", "# seconds. It is obtained from tables published by the IERS.", "if", "not", "hasattr", "(", "self", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/time/core.py#L1776-L1809
MISP/PyMISP
75cb39e0ca2019a961c2642fe2768734971dfa1b
pymisp/api.py
python
PyMISP.update_object_templates
(self)
return self._check_json_response(response)
Trigger an update of the object templates
Trigger an update of the object templates
[ "Trigger", "an", "update", "of", "the", "object", "templates" ]
def update_object_templates(self) -> Dict: """Trigger an update of the object templates""" response = self._prepare_request('POST', 'objectTemplates/update') return self._check_json_response(response)
[ "def", "update_object_templates", "(", "self", ")", "->", "Dict", ":", "response", "=", "self", ".", "_prepare_request", "(", "'POST'", ",", "'objectTemplates/update'", ")", "return", "self", ".", "_check_json_response", "(", "response", ")" ]
https://github.com/MISP/PyMISP/blob/75cb39e0ca2019a961c2642fe2768734971dfa1b/pymisp/api.py#L667-L670
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
research/delf/delf/python/datasets/google_landmarks_dataset/googlelandmarks.py
python
CreateDataset
(file_pattern, image_size=321, batch_size=32, augmentation=False, seed=0)
return dataset
Creates a dataset. Args: file_pattern: str, file pattern of the dataset files. image_size: int, image size. batch_size: int, batch size. augmentation: bool, whether to apply augmentation. seed: int, seed for shuffling the dataset. Returns: tf.data.TFRecordDataset.
Creates a dataset.
[ "Creates", "a", "dataset", "." ]
def CreateDataset(file_pattern, image_size=321, batch_size=32, augmentation=False, seed=0): """Creates a dataset. Args: file_pattern: str, file pattern of the dataset files. image_size: int, image size. batch_size: int, batch size. augmentation: bool, whether to apply augmentation. seed: int, seed for shuffling the dataset. Returns: tf.data.TFRecordDataset. """ filenames = tf.io.gfile.glob(file_pattern) dataset = tf.data.TFRecordDataset(filenames) dataset = dataset.repeat().shuffle(buffer_size=100, seed=seed) # Create a description of the features. feature_description = { 'image/height': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/width': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/channels': tf.io.FixedLenFeature([], tf.int64, default_value=0), 'image/format': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/id': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/filename': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/encoded': tf.io.FixedLenFeature([], tf.string, default_value=''), 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=0), } customized_parse_func = functools.partial( _ParseFunction, name_to_features=feature_description, image_size=image_size, augmentation=augmentation) dataset = dataset.map(customized_parse_func) dataset = dataset.batch(batch_size) return dataset
[ "def", "CreateDataset", "(", "file_pattern", ",", "image_size", "=", "321", ",", "batch_size", "=", "32", ",", "augmentation", "=", "False", ",", "seed", "=", "0", ")", ":", "filenames", "=", "tf", ".", "io", ".", "gfile", ".", "glob", "(", "file_patte...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/delf/delf/python/datasets/google_landmarks_dataset/googlelandmarks.py#L134-L177
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/container/drivers/kubernetes.py
python
KubernetesContainerDriver.destroy_cluster
(self, cluster)
return True
Delete a cluster (namespace) :return: ``True`` if the destroy was successful, otherwise ``False``. :rtype: ``bool``
Delete a cluster (namespace)
[ "Delete", "a", "cluster", "(", "namespace", ")" ]
def destroy_cluster(self, cluster): """ Delete a cluster (namespace) :return: ``True`` if the destroy was successful, otherwise ``False``. :rtype: ``bool`` """ self.connection.request( ROOT_URL + "v1/namespaces/%s" % cluster.id, method="DELETE" ).object return True
[ "def", "destroy_cluster", "(", "self", ",", "cluster", ")", ":", "self", ".", "connection", ".", "request", "(", "ROOT_URL", "+", "\"v1/namespaces/%s\"", "%", "cluster", ".", "id", ",", "method", "=", "\"DELETE\"", ")", ".", "object", "return", "True" ]
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/container/drivers/kubernetes.py#L134-L144
MaurizioFD/RecSys2019_DeepLearning_Evaluation
0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b
Base/Similarity/Compute_Similarity.py
python
Compute_Similarity.__init__
(self, dataMatrix, use_implementation = "density", similarity = None, **args)
Interface object that will call the appropriate similarity implementation :param dataMatrix: scipy sparse matrix |features|x|items| or |users|x|items| :param use_implementation: "density" will choose the most efficient implementation automatically "cython" will use the cython implementation, if available. Most efficient for sparse matrix "python" will use the python implementation. Most efficient for dense matrix :param similarity: the type of similarity to use, see SimilarityFunction enum :param args: other args required by the specific similarity implementation
Interface object that will call the appropriate similarity implementation :param dataMatrix: scipy sparse matrix |features|x|items| or |users|x|items| :param use_implementation: "density" will choose the most efficient implementation automatically "cython" will use the cython implementation, if available. Most efficient for sparse matrix "python" will use the python implementation. Most efficient for dense matrix :param similarity: the type of similarity to use, see SimilarityFunction enum :param args: other args required by the specific similarity implementation
[ "Interface", "object", "that", "will", "call", "the", "appropriate", "similarity", "implementation", ":", "param", "dataMatrix", ":", "scipy", "sparse", "matrix", "|features|x|items|", "or", "|users|x|items|", ":", "param", "use_implementation", ":", "density", "will"...
def __init__(self, dataMatrix, use_implementation = "density", similarity = None, **args): """ Interface object that will call the appropriate similarity implementation :param dataMatrix: scipy sparse matrix |features|x|items| or |users|x|items| :param use_implementation: "density" will choose the most efficient implementation automatically "cython" will use the cython implementation, if available. Most efficient for sparse matrix "python" will use the python implementation. Most efficient for dense matrix :param similarity: the type of similarity to use, see SimilarityFunction enum :param args: other args required by the specific similarity implementation """ assert np.all(np.isfinite(dataMatrix.data)), \ "Compute_Similarity: Data matrix contains {} non finite values".format(np.sum(np.logical_not(np.isfinite(dataMatrix.data)))) self.dense = False if similarity == "euclidean": # This is only available here self.compute_similarity_object = Compute_Similarity_Euclidean(dataMatrix, **args) else: columns_with_full_features = np.sum(np.ediff1d(sps.csc_matrix(dataMatrix).indptr) == dataMatrix.shape[0]) if similarity in ['dice', 'jaccard', 'tversky'] and columns_with_full_features >= dataMatrix.shape[1]/2: warnings.warn("Compute_Similarity: {:.2f}% of the columns have all features, " "set-based similarity heuristics will not be able to discriminate between the columns.".format(columns_with_full_features/dataMatrix.shape[1]*100)) if dataMatrix.shape[0] == 1 and columns_with_full_features >= dataMatrix.shape[1]/2: warnings.warn("Compute_Similarity: {:.2f}% of the columns have a value for the single feature the data has, " "most similarity heuristics will not be able to discriminate between the columns.".format(columns_with_full_features/dataMatrix.shape[1]*100)) assert not (dataMatrix.shape[0] == 1 and dataMatrix.nnz == dataMatrix.shape[1]),\ "Compute_Similarity: data has only 1 feature (shape: {}) with values in all columns," \ " cosine and set-based similarities are not able to discriminate 1-dimensional dense data," \ " use Euclidean similarity instead.".format(dataMatrix.shape) if similarity is not None: args["similarity"] = similarity if use_implementation == "density": if isinstance(dataMatrix, np.ndarray): self.dense = True elif isinstance(dataMatrix, sps.spmatrix): shape = dataMatrix.shape num_cells = shape[0]*shape[1] sparsity = dataMatrix.nnz/num_cells self.dense = sparsity > 0.5 else: print("Compute_Similarity: matrix type not recognized, calling default...") use_implementation = "python" if self.dense: print("Compute_Similarity: detected dense matrix") use_implementation = "python" else: use_implementation = "cython" if use_implementation == "cython": try: from Base.Similarity.Cython.Compute_Similarity_Cython import Compute_Similarity_Cython self.compute_similarity_object = Compute_Similarity_Cython(dataMatrix, **args) except ImportError: print("Unable to load Cython Compute_Similarity, reverting to Python") self.compute_similarity_object = Compute_Similarity_Python(dataMatrix, **args) elif use_implementation == "python": self.compute_similarity_object = Compute_Similarity_Python(dataMatrix, **args) else: raise ValueError("Compute_Similarity: value for argument 'use_implementation' not recognized")
[ "def", "__init__", "(", "self", ",", "dataMatrix", ",", "use_implementation", "=", "\"density\"", ",", "similarity", "=", "None", ",", "*", "*", "args", ")", ":", "assert", "np", ".", "all", "(", "np", ".", "isfinite", "(", "dataMatrix", ".", "data", "...
https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation/blob/0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b/Base/Similarity/Compute_Similarity.py#L33-L118
wiseman/mavelous
eef41c096cc282bb3acd33a747146a88d2bd1eee
modules/camera.py
python
mavlink_packet
(m)
handle an incoming mavlink packet
handle an incoming mavlink packet
[ "handle", "an", "incoming", "mavlink", "packet" ]
def mavlink_packet(m): '''handle an incoming mavlink packet''' state = mpstate.camera_state if mpstate.status.watch in ["camera","queue"] and time.time() > state.last_watch+1: state.last_watch = time.time() cmd_camera(["status" if mpstate.status.watch == "camera" else "queue"]) # update position interpolator state.mpos.add_msg(m)
[ "def", "mavlink_packet", "(", "m", ")", ":", "state", "=", "mpstate", ".", "camera_state", "if", "mpstate", ".", "status", ".", "watch", "in", "[", "\"camera\"", ",", "\"queue\"", "]", "and", "time", ".", "time", "(", ")", ">", "state", ".", "last_watc...
https://github.com/wiseman/mavelous/blob/eef41c096cc282bb3acd33a747146a88d2bd1eee/modules/camera.py#L555-L562
dipy/dipy
be956a529465b28085f8fc435a756947ddee1c89
dipy/tracking/life.py
python
streamline_gradients
(streamline)
return np.array(gradient(np.asarray(streamline))[0])
Calculate the gradients of the streamline along the spatial dimension Parameters ---------- streamline : array-like of shape (n, 3) The 3d coordinates of a single streamline Returns ------- Array of shape (3, n): Spatial gradients along the length of the streamline.
Calculate the gradients of the streamline along the spatial dimension
[ "Calculate", "the", "gradients", "of", "the", "streamline", "along", "the", "spatial", "dimension" ]
def streamline_gradients(streamline): """ Calculate the gradients of the streamline along the spatial dimension Parameters ---------- streamline : array-like of shape (n, 3) The 3d coordinates of a single streamline Returns ------- Array of shape (3, n): Spatial gradients along the length of the streamline. """ return np.array(gradient(np.asarray(streamline))[0])
[ "def", "streamline_gradients", "(", "streamline", ")", ":", "return", "np", ".", "array", "(", "gradient", "(", "np", ".", "asarray", "(", "streamline", ")", ")", "[", "0", "]", ")" ]
https://github.com/dipy/dipy/blob/be956a529465b28085f8fc435a756947ddee1c89/dipy/tracking/life.py#L103-L118
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/rpc/tracker.py
python
TCPEventHandler.name
(self)
return "TCPSocket: %s" % str(self._addr)
name of connection
name of connection
[ "name", "of", "connection" ]
def name(self): """name of connection""" return "TCPSocket: %s" % str(self._addr)
[ "def", "name", "(", "self", ")", ":", "return", "\"TCPSocket: %s\"", "%", "str", "(", "self", ".", "_addr", ")" ]
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/rpc/tracker.py#L176-L178
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/rmvtransport/sensor.py
python
async_setup_platform
( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, )
Set up the RMV departure sensor.
Set up the RMV departure sensor.
[ "Set", "up", "the", "RMV", "departure", "sensor", "." ]
async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the RMV departure sensor.""" timeout = config.get(CONF_TIMEOUT) sensors = [ RMVDepartureSensor( next_departure[CONF_STATION], next_departure.get(CONF_DESTINATIONS), next_departure.get(CONF_DIRECTION), next_departure.get(CONF_LINES), next_departure.get(CONF_PRODUCTS), next_departure.get(CONF_TIME_OFFSET), next_departure.get(CONF_MAX_JOURNEYS), next_departure.get(CONF_NAME), timeout, ) for next_departure in config[CONF_NEXT_DEPARTURE] ] tasks = [sensor.async_update() for sensor in sensors] if tasks: await asyncio.wait(tasks) if not any(sensor.data for sensor in sensors): raise PlatformNotReady async_add_entities(sensors)
[ "async", "def", "async_setup_platform", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "ConfigType", ",", "async_add_entities", ":", "AddEntitiesCallback", ",", "discovery_info", ":", "DiscoveryInfoType", "|", "None", "=", "None", ",", ")", "->", "None", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/rmvtransport/sensor.py#L82-L113
NervanaSystems/neon
8c3fb8a93b4a89303467b25817c60536542d08bd
neon/backends/convolution.py
python
FpropCuda.__init__
(self, lib, dtype, N, C, K, D, H, W, T, R, S, M, P, Q, pad_d, pad_h, pad_w, str_d, str_h, str_w, dil_d, dil_h, dil_w)
[]
def __init__(self, lib, dtype, N, C, K, D, H, W, T, R, S, M, P, Q, pad_d, pad_h, pad_w, str_d, str_h, str_w, dil_d, dil_h, dil_w): super(FpropCuda, self).__init__(lib, dtype, N, C, K, D, H, W, T, R, S, M, P, Q, pad_d, pad_h, pad_w, str_d, str_h, str_w, dil_d, dil_h, dil_w) from neon.backends.kernels.cuda.convolution import _get_conv_kernel self.get_kernel = _get_conv_kernel self.kernel_name = "FpropCuda" assert N % 32 == 0, "N dim must be multiple of 32" assert K % self.vec_size == 0, "K dim must be multiple of %d" % self.vec_size magic_PQ = _magic64(P * Q) magic_Q = _magic64(Q) magic_S = _magic32(R * S + 32, S) HWN = H * W * N RST = R * S * T KRST = K * RST PQ = P * Q PQN = PQ * N self.RS = R * S grid = (PQ * (-(-N // 32)), (-(-K // 32)), 1) block = (8, 8, 1) static_kernel_args = _flatten([C, D, H, W, N, T, R, S, K, M, P, Q, str_w, str_h, pad_w, pad_h, dil_w, dil_h, HWN // 4, KRST // 4, PQN // 4, PQ, 0, 0, magic_PQ, magic_Q, magic_S]) self.launch_args = [grid, block] + [None] * 7 + static_kernel_args self.shared = RST * 4 * 2 self.output_trans = CompoundOps(lib, dtype, K, PQN) lib.set_scratch_size(self.output_trans.size)
[ "def", "__init__", "(", "self", ",", "lib", ",", "dtype", ",", "N", ",", "C", ",", "K", ",", "D", ",", "H", ",", "W", ",", "T", ",", "R", ",", "S", ",", "M", ",", "P", ",", "Q", ",", "pad_d", ",", "pad_h", ",", "pad_w", ",", "str_d", ",...
https://github.com/NervanaSystems/neon/blob/8c3fb8a93b4a89303467b25817c60536542d08bd/neon/backends/convolution.py#L124-L166
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
code/default/lib/noarch/dnslib/label.py
python
DNSLabel.add
(self,name)
return new
Prepend name to label
Prepend name to label
[ "Prepend", "name", "to", "label" ]
def add(self,name): """ Prepend name to label """ new = DNSLabel(name) if self.label: new.label += self.label return new
[ "def", "add", "(", "self", ",", "name", ")", ":", "new", "=", "DNSLabel", "(", "name", ")", "if", "self", ".", "label", ":", "new", ".", "label", "+=", "self", ".", "label", "return", "new" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/code/default/lib/noarch/dnslib/label.py#L85-L92
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/models/expressions.py
python
Ref.get_source_expressions
(self)
return [self.source]
[]
def get_source_expressions(self): return [self.source]
[ "def", "get_source_expressions", "(", "self", ")", ":", "return", "[", "self", ".", "source", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/models/expressions.py#L686-L687
NicolasLM/bplustree
d4351d99b188c2fc96a3538ef0c7937aacfaa619
bplustree/memory.py
python
WAL.checkpoint
(self)
Transfer the modified data back to the tree and close the WAL.
Transfer the modified data back to the tree and close the WAL.
[ "Transfer", "the", "modified", "data", "back", "to", "the", "tree", "and", "close", "the", "WAL", "." ]
def checkpoint(self): """Transfer the modified data back to the tree and close the WAL.""" if self._not_committed_pages: logger.warning('Closing WAL with uncommitted data, discarding it') fsync_file_and_dir(self._fd.fileno(), self._dir_fd) for page, page_start in self._committed_pages.items(): page_data = read_from_file( self._fd, page_start, page_start + self._page_size ) yield page, page_data self._fd.close() os.unlink(self.filename) if self._dir_fd is not None: os.fsync(self._dir_fd) os.close(self._dir_fd)
[ "def", "checkpoint", "(", "self", ")", ":", "if", "self", ".", "_not_committed_pages", ":", "logger", ".", "warning", "(", "'Closing WAL with uncommitted data, discarding it'", ")", "fsync_file_and_dir", "(", "self", ".", "_fd", ".", "fileno", "(", ")", ",", "se...
https://github.com/NicolasLM/bplustree/blob/d4351d99b188c2fc96a3538ef0c7937aacfaa619/bplustree/memory.py#L379-L398
slackapi/python-slack-sdk
2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7
slack_sdk/web/legacy_client.py
python
LegacyWebClient.im_close
( self, *, channel: str, **kwargs, )
return self.api_call("im.close", json=kwargs)
Close a direct message channel.
Close a direct message channel.
[ "Close", "a", "direct", "message", "channel", "." ]
def im_close( self, *, channel: str, **kwargs, ) -> Union[Future, SlackResponse]: """Close a direct message channel.""" kwargs.update({"channel": channel}) kwargs = _remove_none_values(kwargs) return self.api_call("im.close", json=kwargs)
[ "def", "im_close", "(", "self", ",", "*", ",", "channel", ":", "str", ",", "*", "*", "kwargs", ",", ")", "->", "Union", "[", "Future", ",", "SlackResponse", "]", ":", "kwargs", ".", "update", "(", "{", "\"channel\"", ":", "channel", "}", ")", "kwar...
https://github.com/slackapi/python-slack-sdk/blob/2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7/slack_sdk/web/legacy_client.py#L3103-L3112
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/io/tf/lite/flatbuffers/GreaterOptions.py
python
GreaterOptionsEnd
(builder)
return builder.EndObject()
[]
def GreaterOptionsEnd(builder): return builder.EndObject()
[ "def", "GreaterOptionsEnd", "(", "builder", ")", ":", "return", "builder", ".", "EndObject", "(", ")" ]
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/io/tf/lite/flatbuffers/GreaterOptions.py#L28-L28
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/wilight/cover.py
python
wilight_to_hass_position
(value)
return min(100, round((value * 100) / 255))
Convert wilight position 1..255 to hass format 0..100.
Convert wilight position 1..255 to hass format 0..100.
[ "Convert", "wilight", "position", "1", "..", "255", "to", "hass", "format", "0", "..", "100", "." ]
def wilight_to_hass_position(value): """Convert wilight position 1..255 to hass format 0..100.""" return min(100, round((value * 100) / 255))
[ "def", "wilight_to_hass_position", "(", "value", ")", ":", "return", "min", "(", "100", ",", "round", "(", "(", "value", "*", "100", ")", "/", "255", ")", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/wilight/cover.py#L42-L44
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/logging/__init__.py
python
Handler.setFormatter
(self, fmt)
Set the formatter for this handler.
Set the formatter for this handler.
[ "Set", "the", "formatter", "for", "this", "handler", "." ]
def setFormatter(self, fmt): """ Set the formatter for this handler. """ self.formatter = fmt
[ "def", "setFormatter", "(", "self", ",", "fmt", ")", ":", "self", ".", "formatter", "=", "fmt" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/logging/__init__.py#L754-L758
DeepLabCut/DeepLabCut
1dd14c54729ae0d8e66ca495aa5baeb83502e1c7
deeplabcut/utils/auxiliaryfunctions_3d.py
python
Foldernames3Dproject
(cfg_3d)
return ( img_path, path_corners, path_camera_matrix, path_undistort, path_removed_images, )
Definitions of subfolders in 3D projects
Definitions of subfolders in 3D projects
[ "Definitions", "of", "subfolders", "in", "3D", "projects" ]
def Foldernames3Dproject(cfg_3d): """ Definitions of subfolders in 3D projects """ img_path = os.path.join(cfg_3d["project_path"], "calibration_images") path_corners = os.path.join(cfg_3d["project_path"], "corners") path_camera_matrix = os.path.join(cfg_3d["project_path"], "camera_matrix") path_undistort = os.path.join(cfg_3d["project_path"], "undistortion") path_removed_images = os.path.join( cfg_3d["project_path"], "removed_calibration_images" ) return ( img_path, path_corners, path_camera_matrix, path_undistort, path_removed_images, )
[ "def", "Foldernames3Dproject", "(", "cfg_3d", ")", ":", "img_path", "=", "os", ".", "path", ".", "join", "(", "cfg_3d", "[", "\"project_path\"", "]", ",", "\"calibration_images\"", ")", "path_corners", "=", "os", ".", "path", ".", "join", "(", "cfg_3d", "[...
https://github.com/DeepLabCut/DeepLabCut/blob/1dd14c54729ae0d8e66ca495aa5baeb83502e1c7/deeplabcut/utils/auxiliaryfunctions_3d.py#L22-L39
chaoss/grimoirelab-perceval
ba19bfd5e40bffdd422ca8e68526326b47f97491
perceval/backends/core/mediawiki.py
python
MediaWiki.fetch
(self, category=CATEGORY_PAGE, from_date=DEFAULT_DATETIME, reviews_api=False)
return items
Fetch the pages from the backend url. The method retrieves, from a MediaWiki url, the wiki pages. :param category: the category of items to fetch :param from_date: obtain pages updated since this date :param reviews_api: use the reviews API available in MediaWiki >= 1.27 :returns: a generator of pages
Fetch the pages from the backend url.
[ "Fetch", "the", "pages", "from", "the", "backend", "url", "." ]
def fetch(self, category=CATEGORY_PAGE, from_date=DEFAULT_DATETIME, reviews_api=False): """Fetch the pages from the backend url. The method retrieves, from a MediaWiki url, the wiki pages. :param category: the category of items to fetch :param from_date: obtain pages updated since this date :param reviews_api: use the reviews API available in MediaWiki >= 1.27 :returns: a generator of pages """ if from_date == DEFAULT_DATETIME: from_date = None else: from_date = datetime_to_utc(from_date) kwargs = {"from_date": from_date, "reviews_api": reviews_api} items = super().fetch(category, **kwargs) return items
[ "def", "fetch", "(", "self", ",", "category", "=", "CATEGORY_PAGE", ",", "from_date", "=", "DEFAULT_DATETIME", ",", "reviews_api", "=", "False", ")", ":", "if", "from_date", "==", "DEFAULT_DATETIME", ":", "from_date", "=", "None", "else", ":", "from_date", "...
https://github.com/chaoss/grimoirelab-perceval/blob/ba19bfd5e40bffdd422ca8e68526326b47f97491/perceval/backends/core/mediawiki.py#L90-L110
karmab/kcli
fff2a2632841f54d9346b437821585df0ec659d7
kvirt/cli.py
python
create_plantemplate
(args)
Create plan template
Create plan template
[ "Create", "plan", "template" ]
def create_plantemplate(args): """Create plan template""" skipfiles = args.skipfiles skipscripts = args.skipscripts directory = args.directory paramfile = args.paramfile overrides = common.get_overrides(paramfile=paramfile, param=args.param) baseconfig = Kbaseconfig(client=args.client, debug=args.debug) baseconfig.create_plan_template(directory, overrides=overrides, skipfiles=skipfiles, skipscripts=skipscripts)
[ "def", "create_plantemplate", "(", "args", ")", ":", "skipfiles", "=", "args", ".", "skipfiles", "skipscripts", "=", "args", ".", "skipscripts", "directory", "=", "args", ".", "directory", "paramfile", "=", "args", ".", "paramfile", "overrides", "=", "common",...
https://github.com/karmab/kcli/blob/fff2a2632841f54d9346b437821585df0ec659d7/kvirt/cli.py#L2376-L2384
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/stat.py
python
S_ISLNK
(mode)
return S_IFMT(mode) == S_IFLNK
Return True if mode is from a symbolic link.
Return True if mode is from a symbolic link.
[ "Return", "True", "if", "mode", "is", "from", "a", "symbolic", "link", "." ]
def S_ISLNK(mode): """Return True if mode is from a symbolic link.""" return S_IFMT(mode) == S_IFLNK
[ "def", "S_ISLNK", "(", "mode", ")", ":", "return", "S_IFMT", "(", "mode", ")", "==", "S_IFLNK" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/stat.py#L66-L68
aws/aws-parallelcluster
f1fe5679a01c524e7ea904c329bd6d17318c6cd9
cli/src/pcluster/api/models/config_validation_message.py
python
ConfigValidationMessage.message
(self, message)
Sets the message of this ConfigValidationMessage. Validation message :param message: The message of this ConfigValidationMessage. :type message: str
Sets the message of this ConfigValidationMessage.
[ "Sets", "the", "message", "of", "this", "ConfigValidationMessage", "." ]
def message(self, message): """Sets the message of this ConfigValidationMessage. Validation message :param message: The message of this ConfigValidationMessage. :type message: str """ self._message = message
[ "def", "message", "(", "self", ",", "message", ")", ":", "self", ".", "_message", "=", "message" ]
https://github.com/aws/aws-parallelcluster/blob/f1fe5679a01c524e7ea904c329bd6d17318c6cd9/cli/src/pcluster/api/models/config_validation_message.py#L134-L143
lxy5513/videopose
6da0415183c5befd233ad85ff3aefce3179d8c44
joints_detectors/hrnet/lib/nms/setup_linux.py
python
customize_compiler_for_nvcc
(self)
inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on.
inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on.
[ "inject", "deep", "into", "distutils", "to", "customize", "how", "the", "dispatch", "to", "gcc", "/", "nvcc", "works", ".", "If", "you", "subclass", "UnixCCompiler", "it", "s", "not", "trivial", "to", "get", "your", "subclass", "injected", "in", "and", "st...
def customize_compiler_for_nvcc(self): """inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on.""" # tell the compiler it can processes .cu self.src_extensions.append('.cu') # save references to the default compiler_so and _comple methods default_compiler_so = self.compiler_so super = self._compile # now redefine the _compile method. This gets executed for each # object but distutils doesn't have the ability to change compilers # based on source extension: we add it. def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): if os.path.splitext(src)[1] == '.cu': # use the cuda for .cu files self.set_executable('compiler_so', CUDA['nvcc']) # use only a subset of the extra_postargs, which are 1-1 translated # from the extra_compile_args in the Extension class postargs = extra_postargs['nvcc'] else: postargs = extra_postargs['gcc'] super(obj, src, ext, cc_args, postargs, pp_opts) # reset the default compiler_so, which we might have changed for cuda self.compiler_so = default_compiler_so # inject our redefined _compile method into the class self._compile = _compile
[ "def", "customize_compiler_for_nvcc", "(", "self", ")", ":", "# tell the compiler it can processes .cu", "self", ".", "src_extensions", ".", "append", "(", "'.cu'", ")", "# save references to the default compiler_so and _comple methods", "default_compiler_so", "=", "self", ".",...
https://github.com/lxy5513/videopose/blob/6da0415183c5befd233ad85ff3aefce3179d8c44/joints_detectors/hrnet/lib/nms/setup_linux.py#L66-L100
hbldh/bleak
d078e8041c009727211f435bd333c04f422b6ee6
bleak/backends/bluezdbus/signals.py
python
remove_match
(bus: MessageBus, rules: MatchRules)
return bus.call( Message( destination="org.freedesktop.DBus", interface="org.freedesktop.DBus", path="/org/freedesktop/DBus", member="RemoveMatch", signature="s", body=[str(rules)], ) )
Calls org.freedesktop.DBus.RemoveMatch using ``rules``.
Calls org.freedesktop.DBus.RemoveMatch using ``rules``.
[ "Calls", "org", ".", "freedesktop", ".", "DBus", ".", "RemoveMatch", "using", "rules", "." ]
def remove_match(bus: MessageBus, rules: MatchRules) -> Coroutine[Any, Any, Message]: """Calls org.freedesktop.DBus.RemoveMatch using ``rules``.""" return bus.call( Message( destination="org.freedesktop.DBus", interface="org.freedesktop.DBus", path="/org/freedesktop/DBus", member="RemoveMatch", signature="s", body=[str(rules)], ) )
[ "def", "remove_match", "(", "bus", ":", "MessageBus", ",", "rules", ":", "MatchRules", ")", "->", "Coroutine", "[", "Any", ",", "Any", ",", "Message", "]", ":", "return", "bus", ".", "call", "(", "Message", "(", "destination", "=", "\"org.freedesktop.DBus\...
https://github.com/hbldh/bleak/blob/d078e8041c009727211f435bd333c04f422b6ee6/bleak/backends/bluezdbus/signals.py#L190-L201
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_histogram.py
python
Histogram.constraintext
(self)
return self["constraintext"]
Constrain the size of text inside or outside a bar to be no larger than the bar itself. The 'constraintext' property is an enumeration that may be specified as: - One of the following enumeration values: ['inside', 'outside', 'both', 'none'] Returns ------- Any
Constrain the size of text inside or outside a bar to be no larger than the bar itself. The 'constraintext' property is an enumeration that may be specified as: - One of the following enumeration values: ['inside', 'outside', 'both', 'none']
[ "Constrain", "the", "size", "of", "text", "inside", "or", "outside", "a", "bar", "to", "be", "no", "larger", "than", "the", "bar", "itself", ".", "The", "constraintext", "property", "is", "an", "enumeration", "that", "may", "be", "specified", "as", ":", ...
def constraintext(self): """ Constrain the size of text inside or outside a bar to be no larger than the bar itself. The 'constraintext' property is an enumeration that may be specified as: - One of the following enumeration values: ['inside', 'outside', 'both', 'none'] Returns ------- Any """ return self["constraintext"]
[ "def", "constraintext", "(", "self", ")", ":", "return", "self", "[", "\"constraintext\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_histogram.py#L200-L213
timkpaine/pyEX
254acd2b0cf7cb7183100106f4ecc11d1860c46a
pyEX/premium/stocktwits/__init__.py
python
socialSentimentStockTwits
( symbol, type="daily", date="", token="", version="stable", filter="", format="json" )
return _get(base_url, token, version, filter)
This endpoint provides social sentiment data from StockTwits. Data can be viewed as a daily value, or by minute for a given date. https://iexcloud.io/docs/api/#social-sentiment Args: symbol (str): Symbol to look up type (Optional[str]): Can only be daily or minute. Default is daily. date (Optional[str]): Format YYYYMMDD date to fetch sentiment data. Default is today. token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results format (str): return format, defaults to json Returns: dict or DataFrame: result
This endpoint provides social sentiment data from StockTwits. Data can be viewed as a daily value, or by minute for a given date.
[ "This", "endpoint", "provides", "social", "sentiment", "data", "from", "StockTwits", ".", "Data", "can", "be", "viewed", "as", "a", "daily", "value", "or", "by", "minute", "for", "a", "given", "date", "." ]
def socialSentimentStockTwits( symbol, type="daily", date="", token="", version="stable", filter="", format="json" ): """This endpoint provides social sentiment data from StockTwits. Data can be viewed as a daily value, or by minute for a given date. https://iexcloud.io/docs/api/#social-sentiment Args: symbol (str): Symbol to look up type (Optional[str]): Can only be daily or minute. Default is daily. date (Optional[str]): Format YYYYMMDD date to fetch sentiment data. Default is today. token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results format (str): return format, defaults to json Returns: dict or DataFrame: result """ _raiseIfNotStr(symbol) if type not in ("daily", "minute"): raise PyEXception("`type` must be in (daily, minute). Got: {}".format(type)) base_url = "stock/{}/sentiment/{}".format(symbol, type) if date: date = _strOrDate(date) base_url += "/{}".format(date) return _get(base_url, token, version, filter)
[ "def", "socialSentimentStockTwits", "(", "symbol", ",", "type", "=", "\"daily\"", ",", "date", "=", "\"\"", ",", "token", "=", "\"\"", ",", "version", "=", "\"stable\"", ",", "filter", "=", "\"\"", ",", "format", "=", "\"json\"", ")", ":", "_raiseIfNotStr"...
https://github.com/timkpaine/pyEX/blob/254acd2b0cf7cb7183100106f4ecc11d1860c46a/pyEX/premium/stocktwits/__init__.py#L20-L48
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/voice/v1/dialing_permissions/country/__init__.py
python
CountryContext.highrisk_special_prefixes
(self)
return self._highrisk_special_prefixes
Access the highrisk_special_prefixes :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList
Access the highrisk_special_prefixes
[ "Access", "the", "highrisk_special_prefixes" ]
def highrisk_special_prefixes(self): """ Access the highrisk_special_prefixes :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList """ if self._highrisk_special_prefixes is None: self._highrisk_special_prefixes = HighriskSpecialPrefixList( self._version, iso_code=self._solution['iso_code'], ) return self._highrisk_special_prefixes
[ "def", "highrisk_special_prefixes", "(", "self", ")", ":", "if", "self", ".", "_highrisk_special_prefixes", "is", "None", ":", "self", ".", "_highrisk_special_prefixes", "=", "HighriskSpecialPrefixList", "(", "self", ".", "_version", ",", "iso_code", "=", "self", ...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/voice/v1/dialing_permissions/country/__init__.py#L280-L292
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/caldav/datastore/index_file.py
python
MemcachedUIDReserver._key
(self, uid)
return 'reservation:%s' % ( hashlib.md5('%s:%s' % (uid, self.index.resource.fp.path)).hexdigest())
[]
def _key(self, uid): return 'reservation:%s' % ( hashlib.md5('%s:%s' % (uid, self.index.resource.fp.path)).hexdigest())
[ "def", "_key", "(", "self", ",", "uid", ")", ":", "return", "'reservation:%s'", "%", "(", "hashlib", ".", "md5", "(", "'%s:%s'", "%", "(", "uid", ",", "self", ".", "index", ".", "resource", ".", "fp", ".", "path", ")", ")", ".", "hexdigest", "(", ...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/caldav/datastore/index_file.py#L840-L843
littlecodersh/MyPlatform
6f9a946605466f580205f6e9e96e533720fce578
vendor/requests/auth.py
python
HTTPDigestAuth.handle_401
(self, r, **kwargs)
return r
Takes the given response and tries digest-auth, if needed.
Takes the given response and tries digest-auth, if needed.
[ "Takes", "the", "given", "response", "and", "tries", "digest", "-", "auth", "if", "needed", "." ]
def handle_401(self, r, **kwargs): """Takes the given response and tries digest-auth, if needed.""" if self._thread_local.pos is not None: # Rewind the file position indicator of the body to where # it was to resend the request. r.request.body.seek(self._thread_local.pos) s_auth = r.headers.get('www-authenticate', '') if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2: self._thread_local.num_401_calls += 1 pat = re.compile(r'digest ', flags=re.IGNORECASE) self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1)) # Consume content and release the original connection # to allow our new request to reuse the same one. r.content r.close() prep = r.request.copy() extract_cookies_to_jar(prep._cookies, r.request, r.raw) prep.prepare_cookies(prep._cookies) prep.headers['Authorization'] = self.build_digest_header( prep.method, prep.url) _r = r.connection.send(prep, **kwargs) _r.history.append(r) _r.request = prep return _r self._thread_local.num_401_calls = 1 return r
[ "def", "handle_401", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_thread_local", ".", "pos", "is", "not", "None", ":", "# Rewind the file position indicator of the body to where", "# it was to resend the request.", "r", ".", "requ...
https://github.com/littlecodersh/MyPlatform/blob/6f9a946605466f580205f6e9e96e533720fce578/vendor/requests/auth.py#L171-L203
Xyntax/POC-T
9d6bd182fe200253c315e0686100e19f3fb194c2
plugin/urlparser.py
python
get_domain
(url)
return urlparse.urlunsplit([p.scheme, p.netloc, '', '', ''])
added by cdxy May 8 Sun,2016 Use: get_domain('http://cdxy.me:80/cdsa/cda/aaa.jsp?id=2#') Return: 'http://cdxy.me:80'
added by cdxy May 8 Sun,2016
[ "added", "by", "cdxy", "May", "8", "Sun", "2016" ]
def get_domain(url): """ added by cdxy May 8 Sun,2016 Use: get_domain('http://cdxy.me:80/cdsa/cda/aaa.jsp?id=2#') Return: 'http://cdxy.me:80' """ p = urlparse.urlparse(url) return urlparse.urlunsplit([p.scheme, p.netloc, '', '', ''])
[ "def", "get_domain", "(", "url", ")", ":", "p", "=", "urlparse", ".", "urlparse", "(", "url", ")", "return", "urlparse", ".", "urlunsplit", "(", "[", "p", ".", "scheme", ",", "p", ".", "netloc", ",", "''", ",", "''", ",", "''", "]", ")" ]
https://github.com/Xyntax/POC-T/blob/9d6bd182fe200253c315e0686100e19f3fb194c2/plugin/urlparser.py#L9-L20
IDArlingTeam/IDArling
d15b9b7c8bdeb992c569efcc49adf7642bb82cdf
idarling/interface/interface.py
python
Interface.update
(self)
Update the actions and widget.
Update the actions and widget.
[ "Update", "the", "actions", "and", "widget", "." ]
def update(self): """Update the actions and widget.""" if not self._plugin.network.connected: self.clear_invites() self._open_action.update() self._save_action.update() self._widget.refresh()
[ "def", "update", "(", "self", ")", ":", "if", "not", "self", ".", "_plugin", ".", "network", ".", "connected", ":", "self", ".", "clear_invites", "(", ")", "self", ".", "_open_action", ".", "update", "(", ")", "self", ".", "_save_action", ".", "update"...
https://github.com/IDArlingTeam/IDArling/blob/d15b9b7c8bdeb992c569efcc49adf7642bb82cdf/idarling/interface/interface.py#L104-L111
feliam/pysymemu
ad02e52122099d537372eb4d11fd5024b8a3857f
cpu.py
python
Cpu.JPE
(cpu, target)
Jumps short if parity even. @param cpu: current CPU. @param target: destination operand.
Jumps short if parity even.
[ "Jumps", "short", "if", "parity", "even", "." ]
def JPE(cpu, target): ''' Jumps short if parity even. @param cpu: current CPU. @param target: destination operand. ''' cpu.PC = ITE(cpu.AddressSize, cpu.PF, target.read(), cpu.PC)
[ "def", "JPE", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "PC", "=", "ITE", "(", "cpu", ".", "AddressSize", ",", "cpu", ".", "PF", ",", "target", ".", "read", "(", ")", ",", "cpu", ".", "PC", ")" ]
https://github.com/feliam/pysymemu/blob/ad02e52122099d537372eb4d11fd5024b8a3857f/cpu.py#L3537-L3544
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/mechanize/_mechanize.py
python
Browser.back
(self, n=1)
return copy.copy(response)
Go back n steps in history, and return response object. n: go back this number of steps (default 1 step)
Go back n steps in history, and return response object.
[ "Go", "back", "n", "steps", "in", "history", "and", "return", "response", "object", "." ]
def back(self, n=1): """Go back n steps in history, and return response object. n: go back this number of steps (default 1 step) """ if self._response is not None: self._response.close() self.request, response = self._history.back(n, self._response) self.set_response(response) if not response.read_complete: return self.reload() return copy.copy(response)
[ "def", "back", "(", "self", ",", "n", "=", "1", ")", ":", "if", "self", ".", "_response", "is", "not", "None", ":", "self", ".", "_response", ".", "close", "(", ")", "self", ".", "request", ",", "response", "=", "self", ".", "_history", ".", "bac...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/mechanize/_mechanize.py#L345-L357
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/mimeparse/mimeparse.py
python
quality
(mime_type, ranges)
return quality_parsed(mime_type, parsed_ranges)
Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7
Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example:
[ "Returns", "the", "quality", "q", "of", "a", "mime", "-", "type", "when", "compared", "against", "the", "media", "-", "ranges", "in", "ranges", ".", "For", "example", ":" ]
def quality(mime_type, ranges): """Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(",")] return quality_parsed(mime_type, parsed_ranges)
[ "def", "quality", "(", "mime_type", ",", "ranges", ")", ":", "parsed_ranges", "=", "[", "parse_media_range", "(", "r", ")", "for", "r", "in", "ranges", ".", "split", "(", "\",\"", ")", "]", "return", "quality_parsed", "(", "mime_type", ",", "parsed_ranges"...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/mimeparse/mimeparse.py#L98-L107