id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
15,100 | JamesPHoughton/pysd | pysd/py_backend/functions.py | xidz | def xidz(numerator, denominator, value_if_denom_is_zero):
"""
Implements Vensim's XIDZ function.
This function executes a division, robust to denominator being zero.
In the case of zero denominator, the final argument is returned.
Parameters
----------
numerator: float
denominator: floa... | python | def xidz(numerator, denominator, value_if_denom_is_zero):
"""
Implements Vensim's XIDZ function.
This function executes a division, robust to denominator being zero.
In the case of zero denominator, the final argument is returned.
Parameters
----------
numerator: float
denominator: floa... | [
"def",
"xidz",
"(",
"numerator",
",",
"denominator",
",",
"value_if_denom_is_zero",
")",
":",
"small",
"=",
"1e-6",
"# What is considered zero according to Vensim Help",
"if",
"abs",
"(",
"denominator",
")",
"<",
"small",
":",
"return",
"value_if_denom_is_zero",
"else... | Implements Vensim's XIDZ function.
This function executes a division, robust to denominator being zero.
In the case of zero denominator, the final argument is returned.
Parameters
----------
numerator: float
denominator: float
Components of the division operation
value_if_denom_is_z... | [
"Implements",
"Vensim",
"s",
"XIDZ",
"function",
".",
"This",
"function",
"executes",
"a",
"division",
"robust",
"to",
"denominator",
"being",
"zero",
".",
"In",
"the",
"case",
"of",
"zero",
"denominator",
"the",
"final",
"argument",
"is",
"returned",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L950-L973 |
15,101 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Macro.initialize | def initialize(self, initialization_order=None):
"""
This function tries to initialize the stateful objects.
In the case where an initialization function for `Stock A` depends on
the value of `Stock B`, if we try to initialize `Stock A` before `Stock B`
then we will get an error... | python | def initialize(self, initialization_order=None):
"""
This function tries to initialize the stateful objects.
In the case where an initialization function for `Stock A` depends on
the value of `Stock B`, if we try to initialize `Stock A` before `Stock B`
then we will get an error... | [
"def",
"initialize",
"(",
"self",
",",
"initialization_order",
"=",
"None",
")",
":",
"# Initialize time",
"if",
"self",
".",
"time",
"is",
"None",
":",
"if",
"self",
".",
"time_initialization",
"is",
"None",
":",
"self",
".",
"time",
"=",
"Time",
"(",
"... | This function tries to initialize the stateful objects.
In the case where an initialization function for `Stock A` depends on
the value of `Stock B`, if we try to initialize `Stock A` before `Stock B`
then we will get an error, as the value will not yet exist.
In this case, just skip i... | [
"This",
"function",
"tries",
"to",
"initialize",
"the",
"stateful",
"objects",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L320-L363 |
15,102 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Macro.set_components | def set_components(self, params):
""" Set the value of exogenous model elements.
Element values can be passed as keyword=value pairs in the function call.
Values can be numeric type or pandas Series.
Series will be interpolated by integrator.
Examples
--------
>... | python | def set_components(self, params):
""" Set the value of exogenous model elements.
Element values can be passed as keyword=value pairs in the function call.
Values can be numeric type or pandas Series.
Series will be interpolated by integrator.
Examples
--------
>... | [
"def",
"set_components",
"(",
"self",
",",
"params",
")",
":",
"# It might make sense to allow the params argument to take a pandas series, where",
"# the indices of the series are variable names. This would make it easier to",
"# do a Pandas apply on a DataFrame of parameter values. However, th... | Set the value of exogenous model elements.
Element values can be passed as keyword=value pairs in the function call.
Values can be numeric type or pandas Series.
Series will be interpolated by integrator.
Examples
--------
>>> model.set_components({'birth_rate': 10})
... | [
"Set",
"the",
"value",
"of",
"exogenous",
"model",
"elements",
".",
"Element",
"values",
"can",
"be",
"passed",
"as",
"keyword",
"=",
"value",
"pairs",
"in",
"the",
"function",
"call",
".",
"Values",
"can",
"be",
"numeric",
"type",
"or",
"pandas",
"Series"... | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L376-L415 |
15,103 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Macro._timeseries_component | def _timeseries_component(self, series):
""" Internal function for creating a timeseries model element """
# this is only called if the set_component function recognizes a pandas series
# Todo: raise a warning if extrapolating from the end of the series.
return lambda: np.interp(self.tim... | python | def _timeseries_component(self, series):
""" Internal function for creating a timeseries model element """
# this is only called if the set_component function recognizes a pandas series
# Todo: raise a warning if extrapolating from the end of the series.
return lambda: np.interp(self.tim... | [
"def",
"_timeseries_component",
"(",
"self",
",",
"series",
")",
":",
"# this is only called if the set_component function recognizes a pandas series",
"# Todo: raise a warning if extrapolating from the end of the series.",
"return",
"lambda",
":",
"np",
".",
"interp",
"(",
"self",... | Internal function for creating a timeseries model element | [
"Internal",
"function",
"for",
"creating",
"a",
"timeseries",
"model",
"element"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L417-L421 |
15,104 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Macro.set_state | def set_state(self, t, state):
""" Set the system state.
Parameters
----------
t : numeric
The system time
state : dict
A (possibly partial) dictionary of the system state.
The keys to this dictionary may be either pysafe names or original mo... | python | def set_state(self, t, state):
""" Set the system state.
Parameters
----------
t : numeric
The system time
state : dict
A (possibly partial) dictionary of the system state.
The keys to this dictionary may be either pysafe names or original mo... | [
"def",
"set_state",
"(",
"self",
",",
"t",
",",
"state",
")",
":",
"self",
".",
"time",
".",
"update",
"(",
"t",
")",
"for",
"key",
",",
"value",
"in",
"state",
".",
"items",
"(",
")",
":",
"# TODO Implement map with reference between component and stateful ... | Set the system state.
Parameters
----------
t : numeric
The system time
state : dict
A (possibly partial) dictionary of the system state.
The keys to this dictionary may be either pysafe names or original model file names | [
"Set",
"the",
"system",
"state",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L427-L464 |
15,105 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Macro.clear_caches | def clear_caches(self):
""" Clears the Caches for all model elements """
for element_name in dir(self.components):
element = getattr(self.components, element_name)
if hasattr(element, 'cache_val'):
delattr(element, 'cache_val') | python | def clear_caches(self):
""" Clears the Caches for all model elements """
for element_name in dir(self.components):
element = getattr(self.components, element_name)
if hasattr(element, 'cache_val'):
delattr(element, 'cache_val') | [
"def",
"clear_caches",
"(",
"self",
")",
":",
"for",
"element_name",
"in",
"dir",
"(",
"self",
".",
"components",
")",
":",
"element",
"=",
"getattr",
"(",
"self",
".",
"components",
",",
"element_name",
")",
"if",
"hasattr",
"(",
"element",
",",
"'cache... | Clears the Caches for all model elements | [
"Clears",
"the",
"Caches",
"for",
"all",
"model",
"elements"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L466-L471 |
15,106 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Macro.doc | def doc(self):
"""
Formats a table of documentation strings to help users remember variable names, and
understand how they are translated into python safe names.
Returns
-------
docs_df: pandas dataframe
Dataframe with columns for the model components:
... | python | def doc(self):
"""
Formats a table of documentation strings to help users remember variable names, and
understand how they are translated into python safe names.
Returns
-------
docs_df: pandas dataframe
Dataframe with columns for the model components:
... | [
"def",
"doc",
"(",
"self",
")",
":",
"collector",
"=",
"[",
"]",
"for",
"name",
",",
"varname",
"in",
"self",
".",
"components",
".",
"_namespace",
".",
"items",
"(",
")",
":",
"try",
":",
"docstring",
"=",
"getattr",
"(",
"self",
".",
"components",
... | Formats a table of documentation strings to help users remember variable names, and
understand how they are translated into python safe names.
Returns
-------
docs_df: pandas dataframe
Dataframe with columns for the model components:
- Real names
... | [
"Formats",
"a",
"table",
"of",
"documentation",
"strings",
"to",
"help",
"users",
"remember",
"variable",
"names",
"and",
"understand",
"how",
"they",
"are",
"translated",
"into",
"python",
"safe",
"names",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L473-L506 |
15,107 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Model.initialize | def initialize(self):
""" Initializes the simulation model """
self.time.update(self.components.initial_time())
self.time.stage = 'Initialization'
super(Model, self).initialize() | python | def initialize(self):
""" Initializes the simulation model """
self.time.update(self.components.initial_time())
self.time.stage = 'Initialization'
super(Model, self).initialize() | [
"def",
"initialize",
"(",
"self",
")",
":",
"self",
".",
"time",
".",
"update",
"(",
"self",
".",
"components",
".",
"initial_time",
"(",
")",
")",
"self",
".",
"time",
".",
"stage",
"=",
"'Initialization'",
"super",
"(",
"Model",
",",
"self",
")",
"... | Initializes the simulation model | [
"Initializes",
"the",
"simulation",
"model"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L547-L551 |
15,108 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Model._format_return_timestamps | def _format_return_timestamps(self, return_timestamps=None):
"""
Format the passed in return timestamps value as a numpy array.
If no value is passed, build up array of timestamps based upon
model start and end times, and the 'saveper' value.
"""
if return_timestamps is N... | python | def _format_return_timestamps(self, return_timestamps=None):
"""
Format the passed in return timestamps value as a numpy array.
If no value is passed, build up array of timestamps based upon
model start and end times, and the 'saveper' value.
"""
if return_timestamps is N... | [
"def",
"_format_return_timestamps",
"(",
"self",
",",
"return_timestamps",
"=",
"None",
")",
":",
"if",
"return_timestamps",
"is",
"None",
":",
"# Build based upon model file Start, Stop times and Saveper",
"# Vensim's standard is to expect that the data set includes the `final time`... | Format the passed in return timestamps value as a numpy array.
If no value is passed, build up array of timestamps based upon
model start and end times, and the 'saveper' value. | [
"Format",
"the",
"passed",
"in",
"return",
"timestamps",
"value",
"as",
"a",
"numpy",
"array",
".",
"If",
"no",
"value",
"is",
"passed",
"build",
"up",
"array",
"of",
"timestamps",
"based",
"upon",
"model",
"start",
"and",
"end",
"times",
"and",
"the",
"... | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L588-L613 |
15,109 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Model.run | def run(self, params=None, return_columns=None, return_timestamps=None,
initial_condition='original', reload=False):
""" Simulate the model's behavior over time.
Return a pandas dataframe with timestamps as rows,
model elements as columns.
Parameters
----------
... | python | def run(self, params=None, return_columns=None, return_timestamps=None,
initial_condition='original', reload=False):
""" Simulate the model's behavior over time.
Return a pandas dataframe with timestamps as rows,
model elements as columns.
Parameters
----------
... | [
"def",
"run",
"(",
"self",
",",
"params",
"=",
"None",
",",
"return_columns",
"=",
"None",
",",
"return_timestamps",
"=",
"None",
",",
"initial_condition",
"=",
"'original'",
",",
"reload",
"=",
"False",
")",
":",
"if",
"reload",
":",
"self",
".",
"reloa... | Simulate the model's behavior over time.
Return a pandas dataframe with timestamps as rows,
model elements as columns.
Parameters
----------
params : dictionary
Keys are strings of model component names.
Values are numeric or pandas Series.
Nu... | [
"Simulate",
"the",
"model",
"s",
"behavior",
"over",
"time",
".",
"Return",
"a",
"pandas",
"dataframe",
"with",
"timestamps",
"as",
"rows",
"model",
"elements",
"as",
"columns",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L615-L690 |
15,110 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Model._default_return_columns | def _default_return_columns(self):
"""
Return a list of the model elements that does not include lookup functions
or other functions that take parameters.
"""
return_columns = []
parsed_expr = []
for key, value in self.components._namespace.items():
i... | python | def _default_return_columns(self):
"""
Return a list of the model elements that does not include lookup functions
or other functions that take parameters.
"""
return_columns = []
parsed_expr = []
for key, value in self.components._namespace.items():
i... | [
"def",
"_default_return_columns",
"(",
"self",
")",
":",
"return_columns",
"=",
"[",
"]",
"parsed_expr",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"self",
".",
"components",
".",
"_namespace",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"... | Return a list of the model elements that does not include lookup functions
or other functions that take parameters. | [
"Return",
"a",
"list",
"of",
"the",
"model",
"elements",
"that",
"does",
"not",
"include",
"lookup",
"functions",
"or",
"other",
"functions",
"that",
"take",
"parameters",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L698-L716 |
15,111 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Model.set_initial_condition | def set_initial_condition(self, initial_condition):
""" Set the initial conditions of the integration.
Parameters
----------
initial_condition : <string> or <tuple>
Takes on one of the following sets of values:
* 'original'/'o' : Reset to the model-file specifie... | python | def set_initial_condition(self, initial_condition):
""" Set the initial conditions of the integration.
Parameters
----------
initial_condition : <string> or <tuple>
Takes on one of the following sets of values:
* 'original'/'o' : Reset to the model-file specifie... | [
"def",
"set_initial_condition",
"(",
"self",
",",
"initial_condition",
")",
":",
"if",
"isinstance",
"(",
"initial_condition",
",",
"tuple",
")",
":",
"# Todo: check the values more than just seeing if they are a tuple.",
"self",
".",
"set_state",
"(",
"*",
"initial_condi... | Set the initial conditions of the integration.
Parameters
----------
initial_condition : <string> or <tuple>
Takes on one of the following sets of values:
* 'original'/'o' : Reset to the model-file specified initial condition.
* 'current'/'c' : Use the curre... | [
"Set",
"the",
"initial",
"conditions",
"of",
"the",
"integration",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L718-L755 |
15,112 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Model._euler_step | def _euler_step(self, dt):
""" Performs a single step in the euler integration,
updating stateful components
Parameters
----------
dt : float
This is the amount to increase time by this step
"""
self.state = self.state + self.ddt() * dt | python | def _euler_step(self, dt):
""" Performs a single step in the euler integration,
updating stateful components
Parameters
----------
dt : float
This is the amount to increase time by this step
"""
self.state = self.state + self.ddt() * dt | [
"def",
"_euler_step",
"(",
"self",
",",
"dt",
")",
":",
"self",
".",
"state",
"=",
"self",
".",
"state",
"+",
"self",
".",
"ddt",
"(",
")",
"*",
"dt"
] | Performs a single step in the euler integration,
updating stateful components
Parameters
----------
dt : float
This is the amount to increase time by this step | [
"Performs",
"a",
"single",
"step",
"in",
"the",
"euler",
"integration",
"updating",
"stateful",
"components"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L757-L766 |
15,113 | JamesPHoughton/pysd | pysd/py_backend/functions.py | Model._integrate | def _integrate(self, time_steps, capture_elements, return_timestamps):
"""
Performs euler integration
Parameters
----------
time_steps: iterable
the time steps that the integrator progresses over
capture_elements: list
which model elements to capt... | python | def _integrate(self, time_steps, capture_elements, return_timestamps):
"""
Performs euler integration
Parameters
----------
time_steps: iterable
the time steps that the integrator progresses over
capture_elements: list
which model elements to capt... | [
"def",
"_integrate",
"(",
"self",
",",
"time_steps",
",",
"capture_elements",
",",
"return_timestamps",
")",
":",
"# Todo: consider adding the timestamp to the return elements, and using that as the index",
"outputs",
"=",
"[",
"]",
"for",
"t2",
"in",
"time_steps",
"[",
"... | Performs euler integration
Parameters
----------
time_steps: iterable
the time steps that the integrator progresses over
capture_elements: list
which model elements to capture - uses pysafe names
return_timestamps:
which subset of 'timesteps' ... | [
"Performs",
"euler",
"integration"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L768-L800 |
15,114 | JamesPHoughton/pysd | pysd/py_backend/builder.py | merge_partial_elements | def merge_partial_elements(element_list):
"""
merges model elements which collectively all define the model component,
mostly for multidimensional subscripts
Parameters
----------
element_list
Returns
-------
"""
outs = dict() # output data structure
for element in element... | python | def merge_partial_elements(element_list):
"""
merges model elements which collectively all define the model component,
mostly for multidimensional subscripts
Parameters
----------
element_list
Returns
-------
"""
outs = dict() # output data structure
for element in element... | [
"def",
"merge_partial_elements",
"(",
"element_list",
")",
":",
"outs",
"=",
"dict",
"(",
")",
"# output data structure",
"for",
"element",
"in",
"element_list",
":",
"if",
"element",
"[",
"'py_expr'",
"]",
"!=",
"\"None\"",
":",
"# for",
"name",
"=",
"element... | merges model elements which collectively all define the model component,
mostly for multidimensional subscripts
Parameters
----------
element_list
Returns
------- | [
"merges",
"model",
"elements",
"which",
"collectively",
"all",
"define",
"the",
"model",
"component",
"mostly",
"for",
"multidimensional",
"subscripts"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L187-L229 |
15,115 | JamesPHoughton/pysd | pysd/py_backend/builder.py | add_n_delay | def add_n_delay(delay_input, delay_time, initial_value, order, subs, subscript_dict):
"""
Creates code to instantiate a stateful 'Delay' object,
and provides reference to that object's output.
The name of the stateful object is based upon the passed in parameters, so if
there are multiple places wh... | python | def add_n_delay(delay_input, delay_time, initial_value, order, subs, subscript_dict):
"""
Creates code to instantiate a stateful 'Delay' object,
and provides reference to that object's output.
The name of the stateful object is based upon the passed in parameters, so if
there are multiple places wh... | [
"def",
"add_n_delay",
"(",
"delay_input",
",",
"delay_time",
",",
"initial_value",
",",
"order",
",",
"subs",
",",
"subscript_dict",
")",
":",
"# the py name has to be unique to all the passed parameters, or if there are two things",
"# that delay the output by different amounts, t... | Creates code to instantiate a stateful 'Delay' object,
and provides reference to that object's output.
The name of the stateful object is based upon the passed in parameters, so if
there are multiple places where identical delay functions are referenced, the
translated python file will only maintain on... | [
"Creates",
"code",
"to",
"instantiate",
"a",
"stateful",
"Delay",
"object",
"and",
"provides",
"reference",
"to",
"that",
"object",
"s",
"output",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L340-L401 |
15,116 | JamesPHoughton/pysd | pysd/py_backend/builder.py | add_n_smooth | def add_n_smooth(smooth_input, smooth_time, initial_value, order, subs, subscript_dict):
"""Constructs stock and flow chains that implement the calculation of
a smoothing function.
Parameters
----------
smooth_input: <string>
Reference to the model component that is the ... | python | def add_n_smooth(smooth_input, smooth_time, initial_value, order, subs, subscript_dict):
"""Constructs stock and flow chains that implement the calculation of
a smoothing function.
Parameters
----------
smooth_input: <string>
Reference to the model component that is the ... | [
"def",
"add_n_smooth",
"(",
"smooth_input",
",",
"smooth_time",
",",
"initial_value",
",",
"order",
",",
"subs",
",",
"subscript_dict",
")",
":",
"stateful",
"=",
"{",
"'py_name'",
":",
"utils",
".",
"make_python_identifier",
"(",
"'_smooth_%s_%s_%s_%s'",
"%",
"... | Constructs stock and flow chains that implement the calculation of
a smoothing function.
Parameters
----------
smooth_input: <string>
Reference to the model component that is the input to the smoothing function
smooth_time: <string>
Can be a number (in s... | [
"Constructs",
"stock",
"and",
"flow",
"chains",
"that",
"implement",
"the",
"calculation",
"of",
"a",
"smoothing",
"function",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L404-L461 |
15,117 | JamesPHoughton/pysd | pysd/py_backend/builder.py | add_initial | def add_initial(initial_input):
"""
Constructs a stateful object for handling vensim's 'Initial' functionality
Parameters
----------
initial_input: basestring
The expression which will be evaluated, and the first value of which returned
Returns
-------
reference: basestring
... | python | def add_initial(initial_input):
"""
Constructs a stateful object for handling vensim's 'Initial' functionality
Parameters
----------
initial_input: basestring
The expression which will be evaluated, and the first value of which returned
Returns
-------
reference: basestring
... | [
"def",
"add_initial",
"(",
"initial_input",
")",
":",
"stateful",
"=",
"{",
"'py_name'",
":",
"utils",
".",
"make_python_identifier",
"(",
"'_initial_%s'",
"%",
"initial_input",
")",
"[",
"0",
"]",
",",
"'real_name'",
":",
"'Smooth of %s'",
"%",
"initial_input",... | Constructs a stateful object for handling vensim's 'Initial' functionality
Parameters
----------
initial_input: basestring
The expression which will be evaluated, and the first value of which returned
Returns
-------
reference: basestring
reference to the Initial object `__call... | [
"Constructs",
"a",
"stateful",
"object",
"for",
"handling",
"vensim",
"s",
"Initial",
"functionality"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L511-L544 |
15,118 | JamesPHoughton/pysd | pysd/py_backend/builder.py | add_macro | def add_macro(macro_name, filename, arg_names, arg_vals):
"""
Constructs a stateful object instantiating a 'Macro'
Parameters
----------
macro_name: basestring
python safe name for macro
filename: basestring
filepath to macro definition
func_args: dict
dictionary of ... | python | def add_macro(macro_name, filename, arg_names, arg_vals):
"""
Constructs a stateful object instantiating a 'Macro'
Parameters
----------
macro_name: basestring
python safe name for macro
filename: basestring
filepath to macro definition
func_args: dict
dictionary of ... | [
"def",
"add_macro",
"(",
"macro_name",
",",
"filename",
",",
"arg_names",
",",
"arg_vals",
")",
":",
"func_args",
"=",
"'{ %s }'",
"%",
"', '",
".",
"join",
"(",
"[",
"\"'%s': lambda: %s\"",
"%",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"... | Constructs a stateful object instantiating a 'Macro'
Parameters
----------
macro_name: basestring
python safe name for macro
filename: basestring
filepath to macro definition
func_args: dict
dictionary of values to be passed to macro
{key: function}
Returns
... | [
"Constructs",
"a",
"stateful",
"object",
"instantiating",
"a",
"Macro"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L547-L588 |
15,119 | JamesPHoughton/pysd | pysd/py_backend/builder.py | add_incomplete | def add_incomplete(var_name, dependencies):
"""
Incomplete functions don't really need to be 'builders' as they
add no new real structure, but it's helpful to have a function
in which we can raise a warning about the incomplete equation
at translate time.
"""
warnings.warn('%s has no equa... | python | def add_incomplete(var_name, dependencies):
"""
Incomplete functions don't really need to be 'builders' as they
add no new real structure, but it's helpful to have a function
in which we can raise a warning about the incomplete equation
at translate time.
"""
warnings.warn('%s has no equa... | [
"def",
"add_incomplete",
"(",
"var_name",
",",
"dependencies",
")",
":",
"warnings",
".",
"warn",
"(",
"'%s has no equation specified'",
"%",
"var_name",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"# first arg is `self` reference",
"return",
"\"functions.... | Incomplete functions don't really need to be 'builders' as they
add no new real structure, but it's helpful to have a function
in which we can raise a warning about the incomplete equation
at translate time. | [
"Incomplete",
"functions",
"don",
"t",
"really",
"need",
"to",
"be",
"builders",
"as",
"they",
"add",
"no",
"new",
"real",
"structure",
"but",
"it",
"s",
"helpful",
"to",
"have",
"a",
"function",
"in",
"which",
"we",
"can",
"raise",
"a",
"warning",
"abou... | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/builder.py#L591-L602 |
15,120 | JamesPHoughton/pysd | pysd/py_backend/vensim/vensim2py.py | get_model_elements | def get_model_elements(model_str):
"""
Takes in a string representing model text and splits it into elements
I think we're making the assumption that all newline characters are removed...
Parameters
----------
model_str : string
Returns
-------
entries : array of dictionaries
... | python | def get_model_elements(model_str):
"""
Takes in a string representing model text and splits it into elements
I think we're making the assumption that all newline characters are removed...
Parameters
----------
model_str : string
Returns
-------
entries : array of dictionaries
... | [
"def",
"get_model_elements",
"(",
"model_str",
")",
":",
"model_structure_grammar",
"=",
"_include_common_grammar",
"(",
"r\"\"\"\n model = (entry / section)+ sketch?\n entry = element \"~\" element \"~\" element (\"~\" element)? \"|\"\n section = element \"~\" element \"|\"\n sketch... | Takes in a string representing model text and splits it into elements
I think we're making the assumption that all newline characters are removed...
Parameters
----------
model_str : string
Returns
-------
entries : array of dictionaries
Each dictionary contains the components of... | [
"Takes",
"in",
"a",
"string",
"representing",
"model",
"text",
"and",
"splits",
"it",
"into",
"elements"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L87-L181 |
15,121 | JamesPHoughton/pysd | pysd/py_backend/vensim/vensim2py.py | get_equation_components | def get_equation_components(equation_str):
"""
Breaks down a string representing only the equation part of a model element.
Recognizes the various types of model elements that may exist, and identifies them.
Parameters
----------
equation_str : basestring
the first section in each model... | python | def get_equation_components(equation_str):
"""
Breaks down a string representing only the equation part of a model element.
Recognizes the various types of model elements that may exist, and identifies them.
Parameters
----------
equation_str : basestring
the first section in each model... | [
"def",
"get_equation_components",
"(",
"equation_str",
")",
":",
"component_structure_grammar",
"=",
"_include_common_grammar",
"(",
"r\"\"\"\n entry = component / subscript_definition / lookup_definition\n component = name _ subscriptlist? _ \"=\" _ expression\n subscript_definition = ... | Breaks down a string representing only the equation part of a model element.
Recognizes the various types of model elements that may exist, and identifies them.
Parameters
----------
equation_str : basestring
the first section in each model element - the full equation.
Returns
-------
... | [
"Breaks",
"down",
"a",
"string",
"representing",
"only",
"the",
"equation",
"part",
"of",
"a",
"model",
"element",
".",
"Recognizes",
"the",
"various",
"types",
"of",
"model",
"elements",
"that",
"may",
"exist",
"and",
"identifies",
"them",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L206-L305 |
15,122 | JamesPHoughton/pysd | pysd/py_backend/vensim/vensim2py.py | parse_units | def parse_units(units_str):
"""
Extract and parse the units
Extract the bounds over which the expression is assumed to apply.
Parameters
----------
units_str
Returns
-------
Examples
--------
>>> parse_units('Widgets/Month [-10,10,1]')
('Widgets/Month', (-10,10,1))
... | python | def parse_units(units_str):
"""
Extract and parse the units
Extract the bounds over which the expression is assumed to apply.
Parameters
----------
units_str
Returns
-------
Examples
--------
>>> parse_units('Widgets/Month [-10,10,1]')
('Widgets/Month', (-10,10,1))
... | [
"def",
"parse_units",
"(",
"units_str",
")",
":",
"if",
"not",
"len",
"(",
"units_str",
")",
":",
"return",
"units_str",
",",
"(",
"None",
",",
"None",
")",
"if",
"units_str",
"[",
"-",
"1",
"]",
"==",
"']'",
":",
"units",
",",
"lims",
"=",
"units_... | Extract and parse the units
Extract the bounds over which the expression is assumed to apply.
Parameters
----------
units_str
Returns
-------
Examples
--------
>>> parse_units('Widgets/Month [-10,10,1]')
('Widgets/Month', (-10,10,1))
>>> parse_units('Month [0,?]')
('M... | [
"Extract",
"and",
"parse",
"the",
"units",
"Extract",
"the",
"bounds",
"over",
"which",
"the",
"expression",
"is",
"assumed",
"to",
"apply",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L308-L349 |
15,123 | JamesPHoughton/pysd | pysd/py_backend/vensim/vensim2py.py | parse_lookup_expression | def parse_lookup_expression(element):
""" This syntax parses lookups that are defined with their own element """
lookup_grammar = r"""
lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")"
number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?"
_ = ~r"[\s\\]*" # whitespace character
ra... | python | def parse_lookup_expression(element):
""" This syntax parses lookups that are defined with their own element """
lookup_grammar = r"""
lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")"
number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?"
_ = ~r"[\s\\]*" # whitespace character
ra... | [
"def",
"parse_lookup_expression",
"(",
"element",
")",
":",
"lookup_grammar",
"=",
"r\"\"\"\n lookup = _ \"(\" range? _ ( \"(\" _ number _ \",\" _ number _ \")\" _ \",\"? _ )+ \")\"\n number = (\"+\"/\"-\")? ~r\"\\d+\\.?\\d*(e[+-]\\d+)?\"\n _ = ~r\"[\\s\\\\]*\" # whitespace character\n\tra... | This syntax parses lookups that are defined with their own element | [
"This",
"syntax",
"parses",
"lookups",
"that",
"are",
"defined",
"with",
"their",
"own",
"element"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/vensim2py.py#L807-L845 |
15,124 | JamesPHoughton/pysd | pysd/py_backend/utils.py | dict_find | def dict_find(in_dict, value):
""" Helper function for looking up directory keys by their values.
This isn't robust to repeated values
Parameters
----------
in_dict : dictionary
A dictionary containing `value`
value : any type
What we wish to find in the dictionary
Return... | python | def dict_find(in_dict, value):
""" Helper function for looking up directory keys by their values.
This isn't robust to repeated values
Parameters
----------
in_dict : dictionary
A dictionary containing `value`
value : any type
What we wish to find in the dictionary
Return... | [
"def",
"dict_find",
"(",
"in_dict",
",",
"value",
")",
":",
"# Todo: make this robust to repeated values",
"# Todo: make this robust to missing values",
"return",
"list",
"(",
"in_dict",
".",
"keys",
"(",
")",
")",
"[",
"list",
"(",
"in_dict",
".",
"values",
"(",
... | Helper function for looking up directory keys by their values.
This isn't robust to repeated values
Parameters
----------
in_dict : dictionary
A dictionary containing `value`
value : any type
What we wish to find in the dictionary
Returns
-------
key: basestring
... | [
"Helper",
"function",
"for",
"looking",
"up",
"directory",
"keys",
"by",
"their",
"values",
".",
"This",
"isn",
"t",
"robust",
"to",
"repeated",
"values"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L9-L34 |
15,125 | JamesPHoughton/pysd | pysd/py_backend/utils.py | find_subscript_name | def find_subscript_name(subscript_dict, element):
"""
Given a subscript dictionary, and a member of a subscript family,
return the first key of which the member is within the value list.
If element is already a subscript name, return that
Parameters
----------
subscript_dict: dictionary
... | python | def find_subscript_name(subscript_dict, element):
"""
Given a subscript dictionary, and a member of a subscript family,
return the first key of which the member is within the value list.
If element is already a subscript name, return that
Parameters
----------
subscript_dict: dictionary
... | [
"def",
"find_subscript_name",
"(",
"subscript_dict",
",",
"element",
")",
":",
"if",
"element",
"in",
"subscript_dict",
".",
"keys",
"(",
")",
":",
"return",
"element",
"for",
"name",
",",
"elements",
"in",
"subscript_dict",
".",
"items",
"(",
")",
":",
"i... | Given a subscript dictionary, and a member of a subscript family,
return the first key of which the member is within the value list.
If element is already a subscript name, return that
Parameters
----------
subscript_dict: dictionary
Follows the {'subscript name':['list','of','subscript','e... | [
"Given",
"a",
"subscript",
"dictionary",
"and",
"a",
"member",
"of",
"a",
"subscript",
"family",
"return",
"the",
"first",
"key",
"of",
"which",
"the",
"member",
"is",
"within",
"the",
"value",
"list",
".",
"If",
"element",
"is",
"already",
"a",
"subscript... | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L65-L93 |
15,126 | JamesPHoughton/pysd | pysd/py_backend/utils.py | make_coord_dict | def make_coord_dict(subs, subscript_dict, terse=True):
"""
This is for assisting with the lookup of a particular element, such that the output
of this function would take the place of %s in this expression
`variable.loc[%s]`
Parameters
----------
subs: list of strings
coordinates, ... | python | def make_coord_dict(subs, subscript_dict, terse=True):
"""
This is for assisting with the lookup of a particular element, such that the output
of this function would take the place of %s in this expression
`variable.loc[%s]`
Parameters
----------
subs: list of strings
coordinates, ... | [
"def",
"make_coord_dict",
"(",
"subs",
",",
"subscript_dict",
",",
"terse",
"=",
"True",
")",
":",
"sub_elems_list",
"=",
"[",
"y",
"for",
"x",
"in",
"subscript_dict",
".",
"values",
"(",
")",
"for",
"y",
"in",
"x",
"]",
"coordinates",
"=",
"{",
"}",
... | This is for assisting with the lookup of a particular element, such that the output
of this function would take the place of %s in this expression
`variable.loc[%s]`
Parameters
----------
subs: list of strings
coordinates, either as names of dimensions, or positions within a dimension
... | [
"This",
"is",
"for",
"assisting",
"with",
"the",
"lookup",
"of",
"a",
"particular",
"element",
"such",
"that",
"the",
"output",
"of",
"this",
"function",
"would",
"take",
"the",
"place",
"of",
"%s",
"in",
"this",
"expression"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L96-L135 |
15,127 | JamesPHoughton/pysd | pysd/py_backend/utils.py | make_python_identifier | def make_python_identifier(string, namespace=None, reserved_words=None,
convert='drop', handle='force'):
"""
Takes an arbitrary string and creates a valid Python identifier.
If the input string is in the namespace, return its value.
If the python identifier created is alread... | python | def make_python_identifier(string, namespace=None, reserved_words=None,
convert='drop', handle='force'):
"""
Takes an arbitrary string and creates a valid Python identifier.
If the input string is in the namespace, return its value.
If the python identifier created is alread... | [
"def",
"make_python_identifier",
"(",
"string",
",",
"namespace",
"=",
"None",
",",
"reserved_words",
"=",
"None",
",",
"convert",
"=",
"'drop'",
",",
"handle",
"=",
"'force'",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"dict",
"(",
... | Takes an arbitrary string and creates a valid Python identifier.
If the input string is in the namespace, return its value.
If the python identifier created is already in the namespace,
but the input string is not (ie, two similar strings resolve to
the same python identifier)
or if the identifie... | [
"Takes",
"an",
"arbitrary",
"string",
"and",
"creates",
"a",
"valid",
"Python",
"identifier",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L138-L291 |
15,128 | JamesPHoughton/pysd | pysd/py_backend/utils.py | make_flat_df | def make_flat_df(frames, return_addresses):
"""
Takes a list of dictionaries, each representing what is returned from the
model at a particular time, and creates a dataframe whose columns correspond
to the keys of `return addresses`
Parameters
----------
frames: list of dictionaries
... | python | def make_flat_df(frames, return_addresses):
"""
Takes a list of dictionaries, each representing what is returned from the
model at a particular time, and creates a dataframe whose columns correspond
to the keys of `return addresses`
Parameters
----------
frames: list of dictionaries
... | [
"def",
"make_flat_df",
"(",
"frames",
",",
"return_addresses",
")",
":",
"# Todo: could also try a list comprehension here, or parallel apply",
"visited",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"visit_addresses",
"(",
"x",
",",
"return_addresses",
")",
",",... | Takes a list of dictionaries, each representing what is returned from the
model at a particular time, and creates a dataframe whose columns correspond
to the keys of `return addresses`
Parameters
----------
frames: list of dictionaries
each dictionary represents the result of a prticular ti... | [
"Takes",
"a",
"list",
"of",
"dictionaries",
"each",
"representing",
"what",
"is",
"returned",
"from",
"the",
"model",
"at",
"a",
"particular",
"time",
"and",
"creates",
"a",
"dataframe",
"whose",
"columns",
"correspond",
"to",
"the",
"keys",
"of",
"return",
... | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L344-L367 |
15,129 | JamesPHoughton/pysd | pysd/py_backend/utils.py | visit_addresses | def visit_addresses(frame, return_addresses):
"""
Visits all of the addresses, returns a new dict
which contains just the addressed elements
Parameters
----------
frame
return_addresses: a dictionary,
keys will be column names of the resulting dataframe, and are what the
us... | python | def visit_addresses(frame, return_addresses):
"""
Visits all of the addresses, returns a new dict
which contains just the addressed elements
Parameters
----------
frame
return_addresses: a dictionary,
keys will be column names of the resulting dataframe, and are what the
us... | [
"def",
"visit_addresses",
"(",
"frame",
",",
"return_addresses",
")",
":",
"outdict",
"=",
"dict",
"(",
")",
"for",
"real_name",
",",
"(",
"pyname",
",",
"address",
")",
"in",
"return_addresses",
".",
"items",
"(",
")",
":",
"if",
"address",
":",
"xrval"... | Visits all of the addresses, returns a new dict
which contains just the addressed elements
Parameters
----------
frame
return_addresses: a dictionary,
keys will be column names of the resulting dataframe, and are what the
user passed in as 'return_columns'. Values are a tuple:
... | [
"Visits",
"all",
"of",
"the",
"addresses",
"returns",
"a",
"new",
"dict",
"which",
"contains",
"just",
"the",
"addressed",
"elements"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/utils.py#L370-L401 |
15,130 | hirokiky/django-basicauth | basicauth/basicauthutils.py | validate_request | def validate_request(request):
"""Check an incoming request.
Returns:
- True if authentication passed
- Adding request['REMOTE_USER'] as authenticated username.
"""
if getattr(settings, 'BASICAUTH_DISABLE', False):
# Not to use this env
return True
if 'HTTP_AUTHORIZ... | python | def validate_request(request):
"""Check an incoming request.
Returns:
- True if authentication passed
- Adding request['REMOTE_USER'] as authenticated username.
"""
if getattr(settings, 'BASICAUTH_DISABLE', False):
# Not to use this env
return True
if 'HTTP_AUTHORIZ... | [
"def",
"validate_request",
"(",
"request",
")",
":",
"if",
"getattr",
"(",
"settings",
",",
"'BASICAUTH_DISABLE'",
",",
"False",
")",
":",
"# Not to use this env",
"return",
"True",
"if",
"'HTTP_AUTHORIZATION'",
"not",
"in",
"request",
".",
"META",
":",
"return"... | Check an incoming request.
Returns:
- True if authentication passed
- Adding request['REMOTE_USER'] as authenticated username. | [
"Check",
"an",
"incoming",
"request",
"."
] | dcc956ef1507f289bb50dce770e13c114ebd9a9b | https://github.com/hirokiky/django-basicauth/blob/dcc956ef1507f289bb50dce770e13c114ebd9a9b/basicauth/basicauthutils.py#L38-L69 |
15,131 | google/ipaddr-py | ipaddr.py | _find_address_range | def _find_address_range(addresses):
"""Find a sequence of addresses.
Args:
addresses: a list of IPv4 or IPv6 addresses.
Returns:
A tuple containing the first and last IP addresses in the sequence,
and the index of the last IP address in the sequence.
"""
first = last = add... | python | def _find_address_range(addresses):
"""Find a sequence of addresses.
Args:
addresses: a list of IPv4 or IPv6 addresses.
Returns:
A tuple containing the first and last IP addresses in the sequence,
and the index of the last IP address in the sequence.
"""
first = last = add... | [
"def",
"_find_address_range",
"(",
"addresses",
")",
":",
"first",
"=",
"last",
"=",
"addresses",
"[",
"0",
"]",
"last_index",
"=",
"0",
"for",
"ip",
"in",
"addresses",
"[",
"1",
":",
"]",
":",
"if",
"ip",
".",
"_ip",
"==",
"last",
".",
"_ip",
"+",... | Find a sequence of addresses.
Args:
addresses: a list of IPv4 or IPv6 addresses.
Returns:
A tuple containing the first and last IP addresses in the sequence,
and the index of the last IP address in the sequence. | [
"Find",
"a",
"sequence",
"of",
"addresses",
"."
] | 99e55513666db1276596d74f24863e056ca50851 | https://github.com/google/ipaddr-py/blob/99e55513666db1276596d74f24863e056ca50851/ipaddr.py#L157-L176 |
15,132 | google/ipaddr-py | ipaddr.py | _BaseNet._prefix_from_prefix_int | def _prefix_from_prefix_int(self, prefixlen):
"""Validate and return a prefix length integer.
Args:
prefixlen: An integer containing the prefix length.
Returns:
The input, possibly converted from long to int.
Raises:
NetmaskValueError: If the input ... | python | def _prefix_from_prefix_int(self, prefixlen):
"""Validate and return a prefix length integer.
Args:
prefixlen: An integer containing the prefix length.
Returns:
The input, possibly converted from long to int.
Raises:
NetmaskValueError: If the input ... | [
"def",
"_prefix_from_prefix_int",
"(",
"self",
",",
"prefixlen",
")",
":",
"if",
"not",
"isinstance",
"(",
"prefixlen",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"NetmaskValueError",
"(",
"'%r is not an integer'",
"%",
"prefixlen",
")",
"prefixlen"... | Validate and return a prefix length integer.
Args:
prefixlen: An integer containing the prefix length.
Returns:
The input, possibly converted from long to int.
Raises:
NetmaskValueError: If the input is not an integer, or out of range. | [
"Validate",
"and",
"return",
"a",
"prefix",
"length",
"integer",
"."
] | 99e55513666db1276596d74f24863e056ca50851 | https://github.com/google/ipaddr-py/blob/99e55513666db1276596d74f24863e056ca50851/ipaddr.py#L887-L905 |
15,133 | raimon49/pip-licenses | piplicenses.py | output_colored | def output_colored(code, text, is_bold=False):
"""
Create function to output with color sequence
"""
if is_bold:
code = '1;%s' % code
return '\033[%sm%s\033[0m' % (code, text) | python | def output_colored(code, text, is_bold=False):
"""
Create function to output with color sequence
"""
if is_bold:
code = '1;%s' % code
return '\033[%sm%s\033[0m' % (code, text) | [
"def",
"output_colored",
"(",
"code",
",",
"text",
",",
"is_bold",
"=",
"False",
")",
":",
"if",
"is_bold",
":",
"code",
"=",
"'1;%s'",
"%",
"code",
"return",
"'\\033[%sm%s\\033[0m'",
"%",
"(",
"code",
",",
"text",
")"
] | Create function to output with color sequence | [
"Create",
"function",
"to",
"output",
"with",
"color",
"sequence"
] | 879eddd9d75228ba7d6529bd3050d11ae6bf1712 | https://github.com/raimon49/pip-licenses/blob/879eddd9d75228ba7d6529bd3050d11ae6bf1712/piplicenses.py#L504-L511 |
15,134 | nickjj/flask-webpack | flask_webpack/__init__.py | Webpack._set_asset_paths | def _set_asset_paths(self, app):
"""
Read in the manifest json file which acts as a manifest for assets.
This allows us to get the asset path as well as hashed names.
:param app: Flask application
:return: None
"""
webpack_stats = app.config['WEBPACK_MANIFEST_PAT... | python | def _set_asset_paths(self, app):
"""
Read in the manifest json file which acts as a manifest for assets.
This allows us to get the asset path as well as hashed names.
:param app: Flask application
:return: None
"""
webpack_stats = app.config['WEBPACK_MANIFEST_PAT... | [
"def",
"_set_asset_paths",
"(",
"self",
",",
"app",
")",
":",
"webpack_stats",
"=",
"app",
".",
"config",
"[",
"'WEBPACK_MANIFEST_PATH'",
"]",
"try",
":",
"with",
"app",
".",
"open_resource",
"(",
"webpack_stats",
",",
"'r'",
")",
"as",
"stats_json",
":",
... | Read in the manifest json file which acts as a manifest for assets.
This allows us to get the asset path as well as hashed names.
:param app: Flask application
:return: None | [
"Read",
"in",
"the",
"manifest",
"json",
"file",
"which",
"acts",
"as",
"a",
"manifest",
"for",
"assets",
".",
"This",
"allows",
"us",
"to",
"get",
"the",
"asset",
"path",
"as",
"well",
"as",
"hashed",
"names",
"."
] | 241617c6ce0fd9ec11f507204958ddd0ec467634 | https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L47-L70 |
15,135 | nickjj/flask-webpack | flask_webpack/__init__.py | Webpack.javascript_tag | def javascript_tag(self, *args):
"""
Convenience tag to output 1 or more javascript tags.
:param args: 1 or more javascript file names
:return: Script tag(s) containing the asset
"""
tags = []
for arg in args:
asset_path = self.asset_url_for('{0}.js'... | python | def javascript_tag(self, *args):
"""
Convenience tag to output 1 or more javascript tags.
:param args: 1 or more javascript file names
:return: Script tag(s) containing the asset
"""
tags = []
for arg in args:
asset_path = self.asset_url_for('{0}.js'... | [
"def",
"javascript_tag",
"(",
"self",
",",
"*",
"args",
")",
":",
"tags",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"asset_path",
"=",
"self",
".",
"asset_url_for",
"(",
"'{0}.js'",
".",
"format",
"(",
"arg",
")",
")",
"if",
"asset_path",
":",
... | Convenience tag to output 1 or more javascript tags.
:param args: 1 or more javascript file names
:return: Script tag(s) containing the asset | [
"Convenience",
"tag",
"to",
"output",
"1",
"or",
"more",
"javascript",
"tags",
"."
] | 241617c6ce0fd9ec11f507204958ddd0ec467634 | https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L81-L95 |
15,136 | nickjj/flask-webpack | flask_webpack/__init__.py | Webpack.asset_url_for | def asset_url_for(self, asset):
"""
Lookup the hashed asset path of a file name unless it starts with
something that resembles a web address, then take it as is.
:param asset: A logical path to an asset
:type asset: str
:return: Asset path or None if not found
""... | python | def asset_url_for(self, asset):
"""
Lookup the hashed asset path of a file name unless it starts with
something that resembles a web address, then take it as is.
:param asset: A logical path to an asset
:type asset: str
:return: Asset path or None if not found
""... | [
"def",
"asset_url_for",
"(",
"self",
",",
"asset",
")",
":",
"if",
"'//'",
"in",
"asset",
":",
"return",
"asset",
"if",
"asset",
"not",
"in",
"self",
".",
"assets",
":",
"return",
"None",
"return",
"'{0}{1}'",
".",
"format",
"(",
"self",
".",
"assets_u... | Lookup the hashed asset path of a file name unless it starts with
something that resembles a web address, then take it as is.
:param asset: A logical path to an asset
:type asset: str
:return: Asset path or None if not found | [
"Lookup",
"the",
"hashed",
"asset",
"path",
"of",
"a",
"file",
"name",
"unless",
"it",
"starts",
"with",
"something",
"that",
"resembles",
"a",
"web",
"address",
"then",
"take",
"it",
"as",
"is",
"."
] | 241617c6ce0fd9ec11f507204958ddd0ec467634 | https://github.com/nickjj/flask-webpack/blob/241617c6ce0fd9ec11f507204958ddd0ec467634/flask_webpack/__init__.py#L114-L129 |
15,137 | hishnash/djangochannelsrestframework | djangochannelsrestframework/observer/observer.py | ModelObserver.pre_change_receiver | def pre_change_receiver(self, instance: Model, action: Action):
"""
Entry point for triggering the old_binding from save signals.
"""
if action == Action.CREATE:
group_names = set()
else:
group_names = set(self.group_names(instance))
# use a threa... | python | def pre_change_receiver(self, instance: Model, action: Action):
"""
Entry point for triggering the old_binding from save signals.
"""
if action == Action.CREATE:
group_names = set()
else:
group_names = set(self.group_names(instance))
# use a threa... | [
"def",
"pre_change_receiver",
"(",
"self",
",",
"instance",
":",
"Model",
",",
"action",
":",
"Action",
")",
":",
"if",
"action",
"==",
"Action",
".",
"CREATE",
":",
"group_names",
"=",
"set",
"(",
")",
"else",
":",
"group_names",
"=",
"set",
"(",
"sel... | Entry point for triggering the old_binding from save signals. | [
"Entry",
"point",
"for",
"triggering",
"the",
"old_binding",
"from",
"save",
"signals",
"."
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/observer/observer.py#L171-L187 |
15,138 | hishnash/djangochannelsrestframework | djangochannelsrestframework/observer/observer.py | ModelObserver.post_change_receiver | def post_change_receiver(self, instance: Model, action: Action, **kwargs):
"""
Triggers the old_binding to possibly send to its group.
"""
try:
old_group_names = instance.__instance_groups.observers[self]
except (ValueError, KeyError):
old_group_names = se... | python | def post_change_receiver(self, instance: Model, action: Action, **kwargs):
"""
Triggers the old_binding to possibly send to its group.
"""
try:
old_group_names = instance.__instance_groups.observers[self]
except (ValueError, KeyError):
old_group_names = se... | [
"def",
"post_change_receiver",
"(",
"self",
",",
"instance",
":",
"Model",
",",
"action",
":",
"Action",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"old_group_names",
"=",
"instance",
".",
"__instance_groups",
".",
"observers",
"[",
"self",
"]",
"excep... | Triggers the old_binding to possibly send to its group. | [
"Triggers",
"the",
"old_binding",
"to",
"possibly",
"send",
"to",
"its",
"group",
"."
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/observer/observer.py#L189-L226 |
15,139 | hishnash/djangochannelsrestframework | djangochannelsrestframework/generics.py | GenericAsyncAPIConsumer.get_queryset | def get_queryset(self, **kwargs) -> QuerySet:
"""
Get the list of items for this view.
This must be an iterable, and may be a queryset.
Defaults to using `self.queryset`.
This method should always be used rather than accessing `self.queryset`
directly, as `self.queryset`... | python | def get_queryset(self, **kwargs) -> QuerySet:
"""
Get the list of items for this view.
This must be an iterable, and may be a queryset.
Defaults to using `self.queryset`.
This method should always be used rather than accessing `self.queryset`
directly, as `self.queryset`... | [
"def",
"get_queryset",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"QuerySet",
":",
"assert",
"self",
".",
"queryset",
"is",
"not",
"None",
",",
"(",
"\"'%s' should either include a `queryset` attribute, \"",
"\"or override the `get_queryset()` method.\"",
"%",
"... | Get the list of items for this view.
This must be an iterable, and may be a queryset.
Defaults to using `self.queryset`.
This method should always be used rather than accessing `self.queryset`
directly, as `self.queryset` gets evaluated only once, and those results
are cached fo... | [
"Get",
"the",
"list",
"of",
"items",
"for",
"this",
"view",
".",
"This",
"must",
"be",
"an",
"iterable",
"and",
"may",
"be",
"a",
"queryset",
".",
"Defaults",
"to",
"using",
"self",
".",
"queryset",
"."
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/generics.py#L34-L59 |
15,140 | hishnash/djangochannelsrestframework | djangochannelsrestframework/generics.py | GenericAsyncAPIConsumer.get_serializer_class | def get_serializer_class(self, **kwargs) -> Type[Serializer]:
"""
Return the class to use for the serializer.
Defaults to using `self.serializer_class`.
You may want to override this if you need to provide different
serializations depending on the incoming request.
(Eg.... | python | def get_serializer_class(self, **kwargs) -> Type[Serializer]:
"""
Return the class to use for the serializer.
Defaults to using `self.serializer_class`.
You may want to override this if you need to provide different
serializations depending on the incoming request.
(Eg.... | [
"def",
"get_serializer_class",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"Type",
"[",
"Serializer",
"]",
":",
"assert",
"self",
".",
"serializer_class",
"is",
"not",
"None",
",",
"(",
"\"'%s' should either include a `serializer_class` attribute, \"",
"\"or ov... | Return the class to use for the serializer.
Defaults to using `self.serializer_class`.
You may want to override this if you need to provide different
serializations depending on the incoming request.
(Eg. admins get full serialization, others get basic serialization) | [
"Return",
"the",
"class",
"to",
"use",
"for",
"the",
"serializer",
".",
"Defaults",
"to",
"using",
"self",
".",
"serializer_class",
"."
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/generics.py#L109-L125 |
15,141 | hishnash/djangochannelsrestframework | djangochannelsrestframework/consumers.py | view_as_consumer | def view_as_consumer(
wrapped_view: typing.Callable[[HttpRequest], HttpResponse],
mapped_actions: typing.Optional[
typing.Dict[str, str]
]=None) -> Type[AsyncConsumer]:
"""
Wrap a django View so that it will be triggered by actions over this json
websocket consumer.
... | python | def view_as_consumer(
wrapped_view: typing.Callable[[HttpRequest], HttpResponse],
mapped_actions: typing.Optional[
typing.Dict[str, str]
]=None) -> Type[AsyncConsumer]:
"""
Wrap a django View so that it will be triggered by actions over this json
websocket consumer.
... | [
"def",
"view_as_consumer",
"(",
"wrapped_view",
":",
"typing",
".",
"Callable",
"[",
"[",
"HttpRequest",
"]",
",",
"HttpResponse",
"]",
",",
"mapped_actions",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"... | Wrap a django View so that it will be triggered by actions over this json
websocket consumer. | [
"Wrap",
"a",
"django",
"View",
"so",
"that",
"it",
"will",
"be",
"triggered",
"by",
"actions",
"over",
"this",
"json",
"websocket",
"consumer",
"."
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L303-L324 |
15,142 | hishnash/djangochannelsrestframework | djangochannelsrestframework/consumers.py | AsyncAPIConsumer.check_permissions | async def check_permissions(self, action: str, **kwargs):
"""
Check if the action should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
for permission in await self.get_permissions(action=action, **kwargs):
if not await ensure_asyn... | python | async def check_permissions(self, action: str, **kwargs):
"""
Check if the action should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
for permission in await self.get_permissions(action=action, **kwargs):
if not await ensure_asyn... | [
"async",
"def",
"check_permissions",
"(",
"self",
",",
"action",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"permission",
"in",
"await",
"self",
".",
"get_permissions",
"(",
"action",
"=",
"action",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
... | Check if the action should be permitted.
Raises an appropriate exception if the request is not permitted. | [
"Check",
"if",
"the",
"action",
"should",
"be",
"permitted",
".",
"Raises",
"an",
"appropriate",
"exception",
"if",
"the",
"request",
"is",
"not",
"permitted",
"."
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L93-L102 |
15,143 | hishnash/djangochannelsrestframework | djangochannelsrestframework/consumers.py | AsyncAPIConsumer.handle_exception | async def handle_exception(self, exc: Exception, action: str, request_id):
"""
Handle any exception that occurs, by sending an appropriate message
"""
if isinstance(exc, APIException):
await self.reply(
action=action,
errors=self._format_errors... | python | async def handle_exception(self, exc: Exception, action: str, request_id):
"""
Handle any exception that occurs, by sending an appropriate message
"""
if isinstance(exc, APIException):
await self.reply(
action=action,
errors=self._format_errors... | [
"async",
"def",
"handle_exception",
"(",
"self",
",",
"exc",
":",
"Exception",
",",
"action",
":",
"str",
",",
"request_id",
")",
":",
"if",
"isinstance",
"(",
"exc",
",",
"APIException",
")",
":",
"await",
"self",
".",
"reply",
"(",
"action",
"=",
"ac... | Handle any exception that occurs, by sending an appropriate message | [
"Handle",
"any",
"exception",
"that",
"occurs",
"by",
"sending",
"an",
"appropriate",
"message"
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L104-L123 |
15,144 | hishnash/djangochannelsrestframework | djangochannelsrestframework/consumers.py | AsyncAPIConsumer.receive_json | async def receive_json(self, content: typing.Dict, **kwargs):
"""
Called with decoded JSON content.
"""
# TODO assert format, if does not match return message.
request_id = content.pop('request_id')
action = content.pop('action')
await self.handle_action(action, r... | python | async def receive_json(self, content: typing.Dict, **kwargs):
"""
Called with decoded JSON content.
"""
# TODO assert format, if does not match return message.
request_id = content.pop('request_id')
action = content.pop('action')
await self.handle_action(action, r... | [
"async",
"def",
"receive_json",
"(",
"self",
",",
"content",
":",
"typing",
".",
"Dict",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO assert format, if does not match return message.",
"request_id",
"=",
"content",
".",
"pop",
"(",
"'request_id'",
")",
"action",
"... | Called with decoded JSON content. | [
"Called",
"with",
"decoded",
"JSON",
"content",
"."
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L170-L177 |
15,145 | hishnash/djangochannelsrestframework | djangochannelsrestframework/decorators.py | action | def action(atomic=None, **kwargs):
"""
Mark a method as an action.
"""
def decorator(func):
if atomic is None:
_atomic = getattr(settings, 'ATOMIC_REQUESTS', False)
else:
_atomic = atomic
func.action = True
func.kwargs = kwargs
if asyncio.... | python | def action(atomic=None, **kwargs):
"""
Mark a method as an action.
"""
def decorator(func):
if atomic is None:
_atomic = getattr(settings, 'ATOMIC_REQUESTS', False)
else:
_atomic = atomic
func.action = True
func.kwargs = kwargs
if asyncio.... | [
"def",
"action",
"(",
"atomic",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"if",
"atomic",
"is",
"None",
":",
"_atomic",
"=",
"getattr",
"(",
"settings",
",",
"'ATOMIC_REQUESTS'",
",",
"False",
")",
"el... | Mark a method as an action. | [
"Mark",
"a",
"method",
"as",
"an",
"action",
"."
] | 19fdec7efd785b1a94d19612a8de934e1948e344 | https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/decorators.py#L35-L72 |
15,146 | blue-yonder/bonfire | bonfire/dateutils.py | datetime_parser | def datetime_parser(s):
"""
Parse timestamp s in local time. First the arrow parser is used, if it fails, the parsedatetime parser is used.
:param s:
:return:
"""
try:
ts = arrow.get(s)
# Convert UTC to local, result of get is UTC unless it specifies timezone, bonfire assumes
... | python | def datetime_parser(s):
"""
Parse timestamp s in local time. First the arrow parser is used, if it fails, the parsedatetime parser is used.
:param s:
:return:
"""
try:
ts = arrow.get(s)
# Convert UTC to local, result of get is UTC unless it specifies timezone, bonfire assumes
... | [
"def",
"datetime_parser",
"(",
"s",
")",
":",
"try",
":",
"ts",
"=",
"arrow",
".",
"get",
"(",
"s",
")",
"# Convert UTC to local, result of get is UTC unless it specifies timezone, bonfire assumes",
"# all time to be machine local",
"if",
"ts",
".",
"tzinfo",
"==",
"arr... | Parse timestamp s in local time. First the arrow parser is used, if it fails, the parsedatetime parser is used.
:param s:
:return: | [
"Parse",
"timestamp",
"s",
"in",
"local",
"time",
".",
"First",
"the",
"arrow",
"parser",
"is",
"used",
"if",
"it",
"fails",
"the",
"parsedatetime",
"parser",
"is",
"used",
"."
] | d0af9ca10394f366cfa3c60f0741f1f0918011c2 | https://github.com/blue-yonder/bonfire/blob/d0af9ca10394f366cfa3c60f0741f1f0918011c2/bonfire/dateutils.py#L14-L42 |
15,147 | kyb3r/dhooks | dhooks/file.py | File.seek | def seek(self, offset: int = 0, *args, **kwargs):
"""
A shortcut to ``self.fp.seek``.
"""
return self.fp.seek(offset, *args, **kwargs) | python | def seek(self, offset: int = 0, *args, **kwargs):
"""
A shortcut to ``self.fp.seek``.
"""
return self.fp.seek(offset, *args, **kwargs) | [
"def",
"seek",
"(",
"self",
",",
"offset",
":",
"int",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"fp",
".",
"seek",
"(",
"offset",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | A shortcut to ``self.fp.seek``. | [
"A",
"shortcut",
"to",
"self",
".",
"fp",
".",
"seek",
"."
] | 2cde52b26cc94dcbf538ebcc4e17dfc3714d2827 | https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/file.py#L32-L38 |
15,148 | kyb3r/dhooks | dhooks/embed.py | Embed.set_title | def set_title(self, title: str, url: str = None) -> None:
"""
Sets the title of the embed.
Parameters
----------
title: str
Title of the embed.
url: str or None, optional
URL hyperlink of the title.
"""
self.title = title
... | python | def set_title(self, title: str, url: str = None) -> None:
"""
Sets the title of the embed.
Parameters
----------
title: str
Title of the embed.
url: str or None, optional
URL hyperlink of the title.
"""
self.title = title
... | [
"def",
"set_title",
"(",
"self",
",",
"title",
":",
"str",
",",
"url",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"title",
"=",
"title",
"self",
".",
"url",
"=",
"url"
] | Sets the title of the embed.
Parameters
----------
title: str
Title of the embed.
url: str or None, optional
URL hyperlink of the title. | [
"Sets",
"the",
"title",
"of",
"the",
"embed",
"."
] | 2cde52b26cc94dcbf538ebcc4e17dfc3714d2827 | https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L82-L96 |
15,149 | kyb3r/dhooks | dhooks/embed.py | Embed.set_timestamp | def set_timestamp(self, time: Union[str, datetime.datetime] = None,
now: bool = False) -> None:
"""
Sets the timestamp of the embed.
Parameters
----------
time: str or :class:`datetime.datetime`
The ``ISO 8601`` timestamp from the embed.
... | python | def set_timestamp(self, time: Union[str, datetime.datetime] = None,
now: bool = False) -> None:
"""
Sets the timestamp of the embed.
Parameters
----------
time: str or :class:`datetime.datetime`
The ``ISO 8601`` timestamp from the embed.
... | [
"def",
"set_timestamp",
"(",
"self",
",",
"time",
":",
"Union",
"[",
"str",
",",
"datetime",
".",
"datetime",
"]",
"=",
"None",
",",
"now",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"now",
":",
"self",
".",
"timestamp",
"=",
"str",
... | Sets the timestamp of the embed.
Parameters
----------
time: str or :class:`datetime.datetime`
The ``ISO 8601`` timestamp from the embed.
now: bool
Defaults to :class:`False`.
If set to :class:`True` the current time is used for the timestamp. | [
"Sets",
"the",
"timestamp",
"of",
"the",
"embed",
"."
] | 2cde52b26cc94dcbf538ebcc4e17dfc3714d2827 | https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L98-L116 |
15,150 | kyb3r/dhooks | dhooks/embed.py | Embed.add_field | def add_field(self, name: str, value: str, inline: bool = True) -> None:
"""
Adds an embed field.
Parameters
----------
name: str
Name attribute of the embed field.
value: str
Value attribute of the embed field.
inline: bool
... | python | def add_field(self, name: str, value: str, inline: bool = True) -> None:
"""
Adds an embed field.
Parameters
----------
name: str
Name attribute of the embed field.
value: str
Value attribute of the embed field.
inline: bool
... | [
"def",
"add_field",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"str",
",",
"inline",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"field",
"=",
"{",
"'name'",
":",
"name",
",",
"'value'",
":",
"value",
",",
"'inline'",
":",
"in... | Adds an embed field.
Parameters
----------
name: str
Name attribute of the embed field.
value: str
Value attribute of the embed field.
inline: bool
Defaults to :class:`True`.
Whether or not the embed should be inline. | [
"Adds",
"an",
"embed",
"field",
"."
] | 2cde52b26cc94dcbf538ebcc4e17dfc3714d2827 | https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L118-L140 |
15,151 | kyb3r/dhooks | dhooks/embed.py | Embed.set_author | def set_author(self, name: str, icon_url: str = None, url: str = None) -> \
None:
"""
Sets the author of the embed.
Parameters
----------
name: str
The author's name.
icon_url: str, optional
URL for the author's icon.
url: st... | python | def set_author(self, name: str, icon_url: str = None, url: str = None) -> \
None:
"""
Sets the author of the embed.
Parameters
----------
name: str
The author's name.
icon_url: str, optional
URL for the author's icon.
url: st... | [
"def",
"set_author",
"(",
"self",
",",
"name",
":",
"str",
",",
"icon_url",
":",
"str",
"=",
"None",
",",
"url",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"author",
"=",
"{",
"'name'",
":",
"name",
",",
"'icon_url'",
":",
"ico... | Sets the author of the embed.
Parameters
----------
name: str
The author's name.
icon_url: str, optional
URL for the author's icon.
url: str, optional
URL hyperlink for the author. | [
"Sets",
"the",
"author",
"of",
"the",
"embed",
"."
] | 2cde52b26cc94dcbf538ebcc4e17dfc3714d2827 | https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L142-L163 |
15,152 | kyb3r/dhooks | dhooks/embed.py | Embed.set_footer | def set_footer(self, text: str, icon_url: str = None) -> None:
"""
Sets the footer of the embed.
Parameters
----------
text: str
The footer text.
icon_url: str, optional
URL for the icon in the footer.
"""
self.footer = {
... | python | def set_footer(self, text: str, icon_url: str = None) -> None:
"""
Sets the footer of the embed.
Parameters
----------
text: str
The footer text.
icon_url: str, optional
URL for the icon in the footer.
"""
self.footer = {
... | [
"def",
"set_footer",
"(",
"self",
",",
"text",
":",
"str",
",",
"icon_url",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"footer",
"=",
"{",
"'text'",
":",
"text",
",",
"'icon_url'",
":",
"icon_url",
"}"
] | Sets the footer of the embed.
Parameters
----------
text: str
The footer text.
icon_url: str, optional
URL for the icon in the footer. | [
"Sets",
"the",
"footer",
"of",
"the",
"embed",
"."
] | 2cde52b26cc94dcbf538ebcc4e17dfc3714d2827 | https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/dhooks/embed.py#L189-L205 |
15,153 | kyb3r/dhooks | examples/async.py | init | async def init(app, loop):
"""Sends a message to the webhook channel when server starts."""
app.session = aiohttp.ClientSession(loop=loop) # to make web requests
app.webhook = Webhook.Async(webhook_url, session=app.session)
em = Embed(color=0x2ecc71)
em.set_author('[INFO] Starting Worker')
em.... | python | async def init(app, loop):
"""Sends a message to the webhook channel when server starts."""
app.session = aiohttp.ClientSession(loop=loop) # to make web requests
app.webhook = Webhook.Async(webhook_url, session=app.session)
em = Embed(color=0x2ecc71)
em.set_author('[INFO] Starting Worker')
em.... | [
"async",
"def",
"init",
"(",
"app",
",",
"loop",
")",
":",
"app",
".",
"session",
"=",
"aiohttp",
".",
"ClientSession",
"(",
"loop",
"=",
"loop",
")",
"# to make web requests",
"app",
".",
"webhook",
"=",
"Webhook",
".",
"Async",
"(",
"webhook_url",
",",... | Sends a message to the webhook channel when server starts. | [
"Sends",
"a",
"message",
"to",
"the",
"webhook",
"channel",
"when",
"server",
"starts",
"."
] | 2cde52b26cc94dcbf538ebcc4e17dfc3714d2827 | https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/examples/async.py#L17-L26 |
15,154 | kyb3r/dhooks | examples/async.py | server_stop | async def server_stop(app, loop):
"""Sends a message to the webhook channel when server stops."""
em = Embed(color=0xe67e22)
em.set_footer('Host: {}'.format(socket.gethostname()))
em.description = '[INFO] Server Stopped'
await app.webhook.send(embed=em)
await app.session.close() | python | async def server_stop(app, loop):
"""Sends a message to the webhook channel when server stops."""
em = Embed(color=0xe67e22)
em.set_footer('Host: {}'.format(socket.gethostname()))
em.description = '[INFO] Server Stopped'
await app.webhook.send(embed=em)
await app.session.close() | [
"async",
"def",
"server_stop",
"(",
"app",
",",
"loop",
")",
":",
"em",
"=",
"Embed",
"(",
"color",
"=",
"0xe67e22",
")",
"em",
".",
"set_footer",
"(",
"'Host: {}'",
".",
"format",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
")",
"em",
".",
"... | Sends a message to the webhook channel when server stops. | [
"Sends",
"a",
"message",
"to",
"the",
"webhook",
"channel",
"when",
"server",
"stops",
"."
] | 2cde52b26cc94dcbf538ebcc4e17dfc3714d2827 | https://github.com/kyb3r/dhooks/blob/2cde52b26cc94dcbf538ebcc4e17dfc3714d2827/examples/async.py#L30-L37 |
15,155 | tantale/deprecated | deprecated/classic.py | ClassicAdapter.get_deprecated_msg | def get_deprecated_msg(self, wrapped, instance):
"""
Get the deprecation warning message for the user.
:param wrapped: Wrapped class or function.
:param instance: The object to which the wrapped function was bound when it was called.
:return: The warning message.
"""
... | python | def get_deprecated_msg(self, wrapped, instance):
"""
Get the deprecation warning message for the user.
:param wrapped: Wrapped class or function.
:param instance: The object to which the wrapped function was bound when it was called.
:return: The warning message.
"""
... | [
"def",
"get_deprecated_msg",
"(",
"self",
",",
"wrapped",
",",
"instance",
")",
":",
"if",
"instance",
"is",
"None",
":",
"if",
"inspect",
".",
"isclass",
"(",
"wrapped",
")",
":",
"fmt",
"=",
"\"Call to deprecated class {name}.\"",
"else",
":",
"fmt",
"=",
... | Get the deprecation warning message for the user.
:param wrapped: Wrapped class or function.
:param instance: The object to which the wrapped function was bound when it was called.
:return: The warning message. | [
"Get",
"the",
"deprecation",
"warning",
"message",
"for",
"the",
"user",
"."
] | 3dc742c571de7cebbbdaaf4c554f2f36fc61b3db | https://github.com/tantale/deprecated/blob/3dc742c571de7cebbbdaaf4c554f2f36fc61b3db/deprecated/classic.py#L101-L127 |
15,156 | izdi/django-slack-oauth | django_slack_oauth/pipelines.py | slack_user | def slack_user(request, api_data):
"""
Pipeline for backward compatibility prior to 1.0.0 version.
In case if you're willing maintain `slack_user` table.
"""
if request.user.is_anonymous:
return request, api_data
data = deepcopy(api_data)
slacker, _ = SlackUser.objects.get_or_crea... | python | def slack_user(request, api_data):
"""
Pipeline for backward compatibility prior to 1.0.0 version.
In case if you're willing maintain `slack_user` table.
"""
if request.user.is_anonymous:
return request, api_data
data = deepcopy(api_data)
slacker, _ = SlackUser.objects.get_or_crea... | [
"def",
"slack_user",
"(",
"request",
",",
"api_data",
")",
":",
"if",
"request",
".",
"user",
".",
"is_anonymous",
":",
"return",
"request",
",",
"api_data",
"data",
"=",
"deepcopy",
"(",
"api_data",
")",
"slacker",
",",
"_",
"=",
"SlackUser",
".",
"obje... | Pipeline for backward compatibility prior to 1.0.0 version.
In case if you're willing maintain `slack_user` table. | [
"Pipeline",
"for",
"backward",
"compatibility",
"prior",
"to",
"1",
".",
"0",
".",
"0",
"version",
".",
"In",
"case",
"if",
"you",
"re",
"willing",
"maintain",
"slack_user",
"table",
"."
] | 46e10f7c64407a018b9585f257224fc38888fbcb | https://github.com/izdi/django-slack-oauth/blob/46e10f7c64407a018b9585f257224fc38888fbcb/django_slack_oauth/pipelines.py#L26-L46 |
15,157 | matplotlib/cmocean | cmocean/data.py | read | def read(varin, fname='MS2_L10.mat.txt'):
'''Read in dataset for variable var
:param varin: Variable for which to read in data.
'''
# # fname = 'MS09_L10.mat.txt'
# # fname = 'MS09_L05.mat.txt' # has PAR
# fname = 'MS2_L10.mat.txt' # empty PAR
d = np.loadtxt(fname, comments='*')
if ... | python | def read(varin, fname='MS2_L10.mat.txt'):
'''Read in dataset for variable var
:param varin: Variable for which to read in data.
'''
# # fname = 'MS09_L10.mat.txt'
# # fname = 'MS09_L05.mat.txt' # has PAR
# fname = 'MS2_L10.mat.txt' # empty PAR
d = np.loadtxt(fname, comments='*')
if ... | [
"def",
"read",
"(",
"varin",
",",
"fname",
"=",
"'MS2_L10.mat.txt'",
")",
":",
"# # fname = 'MS09_L10.mat.txt'",
"# # fname = 'MS09_L05.mat.txt' # has PAR",
"# fname = 'MS2_L10.mat.txt' # empty PAR",
"d",
"=",
"np",
".",
"loadtxt",
"(",
"fname",
",",
"comments",
"=",
"'... | Read in dataset for variable var
:param varin: Variable for which to read in data. | [
"Read",
"in",
"dataset",
"for",
"variable",
"var"
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/data.py#L15-L40 |
15,158 | matplotlib/cmocean | cmocean/data.py | show | def show(cmap, var, vmin=None, vmax=None):
'''Show a colormap for a chosen input variable var side by side with
black and white and jet colormaps.
:param cmap: Colormap instance
:param var: Variable to plot.
:param vmin=None: Min plot value.
:param vmax=None: Max plot value.
'''
# get... | python | def show(cmap, var, vmin=None, vmax=None):
'''Show a colormap for a chosen input variable var side by side with
black and white and jet colormaps.
:param cmap: Colormap instance
:param var: Variable to plot.
:param vmin=None: Min plot value.
:param vmax=None: Max plot value.
'''
# get... | [
"def",
"show",
"(",
"cmap",
",",
"var",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"# get variable data",
"lat",
",",
"lon",
",",
"z",
",",
"data",
"=",
"read",
"(",
"var",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",... | Show a colormap for a chosen input variable var side by side with
black and white and jet colormaps.
:param cmap: Colormap instance
:param var: Variable to plot.
:param vmin=None: Min plot value.
:param vmax=None: Max plot value. | [
"Show",
"a",
"colormap",
"for",
"a",
"chosen",
"input",
"variable",
"var",
"side",
"by",
"side",
"with",
"black",
"and",
"white",
"and",
"jet",
"colormaps",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/data.py#L43-L76 |
15,159 | matplotlib/cmocean | cmocean/data.py | plot_data | def plot_data():
'''Plot sample data up with the fancy colormaps.
'''
var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM']
# colorbar limits for each property
lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2]... | python | def plot_data():
'''Plot sample data up with the fancy colormaps.
'''
var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM']
# colorbar limits for each property
lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2]... | [
"def",
"plot_data",
"(",
")",
":",
"var",
"=",
"[",
"'temp'",
",",
"'oxygen'",
",",
"'salinity'",
",",
"'fluorescence-ECO'",
",",
"'density'",
",",
"'PAR'",
",",
"'turbidity'",
",",
"'fluorescence-CDOM'",
"]",
"# colorbar limits for each property",
"lims",
"=",
... | Plot sample data up with the fancy colormaps. | [
"Plot",
"sample",
"data",
"up",
"with",
"the",
"fancy",
"colormaps",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/data.py#L79-L115 |
15,160 | matplotlib/cmocean | cmocean/plots.py | plot_lightness | def plot_lightness(saveplot=False):
'''Plot lightness of colormaps together.
'''
from colorspacious import cspace_converter
dc = 1.
x = np.linspace(0.0, 1.0, 256)
locs = [] # locations for text labels
fig = plt.figure(figsize=(16, 5))
ax = fig.add_subplot(111)
fig.subplots_adjus... | python | def plot_lightness(saveplot=False):
'''Plot lightness of colormaps together.
'''
from colorspacious import cspace_converter
dc = 1.
x = np.linspace(0.0, 1.0, 256)
locs = [] # locations for text labels
fig = plt.figure(figsize=(16, 5))
ax = fig.add_subplot(111)
fig.subplots_adjus... | [
"def",
"plot_lightness",
"(",
"saveplot",
"=",
"False",
")",
":",
"from",
"colorspacious",
"import",
"cspace_converter",
"dc",
"=",
"1.",
"x",
"=",
"np",
".",
"linspace",
"(",
"0.0",
",",
"1.0",
",",
"256",
")",
"locs",
"=",
"[",
"]",
"# locations for te... | Plot lightness of colormaps together. | [
"Plot",
"lightness",
"of",
"colormaps",
"together",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L14-L61 |
15,161 | matplotlib/cmocean | cmocean/plots.py | plot_gallery | def plot_gallery(saveplot=False):
'''Make plot of colormaps and labels, like in the matplotlib
gallery.
:param saveplot=False: Whether to save the plot or not.
'''
from colorspacious import cspace_converter
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
... | python | def plot_gallery(saveplot=False):
'''Make plot of colormaps and labels, like in the matplotlib
gallery.
:param saveplot=False: Whether to save the plot or not.
'''
from colorspacious import cspace_converter
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
... | [
"def",
"plot_gallery",
"(",
"saveplot",
"=",
"False",
")",
":",
"from",
"colorspacious",
"import",
"cspace_converter",
"gradient",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"256",
")",
"gradient",
"=",
"np",
".",
"vstack",
"(",
"(",
"gradient"... | Make plot of colormaps and labels, like in the matplotlib
gallery.
:param saveplot=False: Whether to save the plot or not. | [
"Make",
"plot",
"of",
"colormaps",
"and",
"labels",
"like",
"in",
"the",
"matplotlib",
"gallery",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L64-L115 |
15,162 | matplotlib/cmocean | cmocean/plots.py | wrap_viscm | def wrap_viscm(cmap, dpi=100, saveplot=False):
'''Evaluate goodness of colormap using perceptual deltas.
:param cmap: Colormap instance.
:param dpi=100: dpi for saved image.
:param saveplot=False: Whether to save the plot or not.
'''
from viscm import viscm
viscm(cmap)
fig = plt.gcf(... | python | def wrap_viscm(cmap, dpi=100, saveplot=False):
'''Evaluate goodness of colormap using perceptual deltas.
:param cmap: Colormap instance.
:param dpi=100: dpi for saved image.
:param saveplot=False: Whether to save the plot or not.
'''
from viscm import viscm
viscm(cmap)
fig = plt.gcf(... | [
"def",
"wrap_viscm",
"(",
"cmap",
",",
"dpi",
"=",
"100",
",",
"saveplot",
"=",
"False",
")",
":",
"from",
"viscm",
"import",
"viscm",
"viscm",
"(",
"cmap",
")",
"fig",
"=",
"plt",
".",
"gcf",
"(",
")",
"fig",
".",
"set_size_inches",
"(",
"22",
","... | Evaluate goodness of colormap using perceptual deltas.
:param cmap: Colormap instance.
:param dpi=100: dpi for saved image.
:param saveplot=False: Whether to save the plot or not. | [
"Evaluate",
"goodness",
"of",
"colormap",
"using",
"perceptual",
"deltas",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L118-L136 |
15,163 | matplotlib/cmocean | cmocean/plots.py | quick_plot | def quick_plot(cmap, fname=None, fig=None, ax=None, N=10):
'''Show quick test of a colormap.
'''
x = np.linspace(0, 10, N)
X, _ = np.meshgrid(x, x)
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
mappable = ax.pcolor(X, cmap=cmap)
ax.set_title(cmap.name, fontsi... | python | def quick_plot(cmap, fname=None, fig=None, ax=None, N=10):
'''Show quick test of a colormap.
'''
x = np.linspace(0, 10, N)
X, _ = np.meshgrid(x, x)
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
mappable = ax.pcolor(X, cmap=cmap)
ax.set_title(cmap.name, fontsi... | [
"def",
"quick_plot",
"(",
"cmap",
",",
"fname",
"=",
"None",
",",
"fig",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"N",
"=",
"10",
")",
":",
"x",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"10",
",",
"N",
")",
"X",
",",
"_",
"=",
"np",
".... | Show quick test of a colormap. | [
"Show",
"quick",
"test",
"of",
"a",
"colormap",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L164-L183 |
15,164 | matplotlib/cmocean | cmocean/tools.py | print_colormaps | def print_colormaps(cmaps, N=256, returnrgb=True, savefiles=False):
'''Print colormaps in 256 RGB colors to text files.
:param returnrgb=False: Whether or not to return the rgb array. Only makes sense to do if print one colormaps' rgb.
'''
rgb = []
for cmap in cmaps:
rgbtemp = cmap(np.l... | python | def print_colormaps(cmaps, N=256, returnrgb=True, savefiles=False):
'''Print colormaps in 256 RGB colors to text files.
:param returnrgb=False: Whether or not to return the rgb array. Only makes sense to do if print one colormaps' rgb.
'''
rgb = []
for cmap in cmaps:
rgbtemp = cmap(np.l... | [
"def",
"print_colormaps",
"(",
"cmaps",
",",
"N",
"=",
"256",
",",
"returnrgb",
"=",
"True",
",",
"savefiles",
"=",
"False",
")",
":",
"rgb",
"=",
"[",
"]",
"for",
"cmap",
"in",
"cmaps",
":",
"rgbtemp",
"=",
"cmap",
"(",
"np",
".",
"linspace",
"(",... | Print colormaps in 256 RGB colors to text files.
:param returnrgb=False: Whether or not to return the rgb array. Only makes sense to do if print one colormaps' rgb. | [
"Print",
"colormaps",
"in",
"256",
"RGB",
"colors",
"to",
"text",
"files",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/tools.py#L17-L34 |
15,165 | matplotlib/cmocean | cmocean/tools.py | cmap | def cmap(rgbin, N=256):
'''Input an array of rgb values to generate a colormap.
:param rgbin: An [mx3] array, where m is the number of input color triplets which
are interpolated between to make the colormap that is returned. hex values
can be input instead, as [mx1] in single quotes with a #... | python | def cmap(rgbin, N=256):
'''Input an array of rgb values to generate a colormap.
:param rgbin: An [mx3] array, where m is the number of input color triplets which
are interpolated between to make the colormap that is returned. hex values
can be input instead, as [mx1] in single quotes with a #... | [
"def",
"cmap",
"(",
"rgbin",
",",
"N",
"=",
"256",
")",
":",
"# rgb inputs here",
"if",
"not",
"isinstance",
"(",
"rgbin",
"[",
"0",
"]",
",",
"_string_types",
")",
":",
"# normalize to be out of 1 if out of 256 instead",
"if",
"rgbin",
".",
"max",
"(",
")",... | Input an array of rgb values to generate a colormap.
:param rgbin: An [mx3] array, where m is the number of input color triplets which
are interpolated between to make the colormap that is returned. hex values
can be input instead, as [mx1] in single quotes with a #.
:param N=10: The number o... | [
"Input",
"an",
"array",
"of",
"rgb",
"values",
"to",
"generate",
"a",
"colormap",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/tools.py#L73-L91 |
15,166 | matplotlib/cmocean | cmocean/tools.py | lighten | def lighten(cmapin, alpha):
'''Lighten a colormap by adding alpha < 1.
:param cmap: A colormap object, like cmocean.cm.matter.
:param alpha: An alpha or transparency value to assign the colormap. Alpha
of 1 is opaque and of 1 is fully transparent.
Outputs resultant colormap object.
This w... | python | def lighten(cmapin, alpha):
'''Lighten a colormap by adding alpha < 1.
:param cmap: A colormap object, like cmocean.cm.matter.
:param alpha: An alpha or transparency value to assign the colormap. Alpha
of 1 is opaque and of 1 is fully transparent.
Outputs resultant colormap object.
This w... | [
"def",
"lighten",
"(",
"cmapin",
",",
"alpha",
")",
":",
"# set the alpha value while retaining the number of rows in original cmap",
"return",
"cmap",
"(",
"cmapin",
"(",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"cmapin",
".",
"N",
")",
",",
"alpha",
"... | Lighten a colormap by adding alpha < 1.
:param cmap: A colormap object, like cmocean.cm.matter.
:param alpha: An alpha or transparency value to assign the colormap. Alpha
of 1 is opaque and of 1 is fully transparent.
Outputs resultant colormap object.
This will lighten the appearance of a plo... | [
"Lighten",
"a",
"colormap",
"by",
"adding",
"alpha",
"<",
"1",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/tools.py#L94-L109 |
15,167 | matplotlib/cmocean | cmocean/tools.py | crop_by_percent | def crop_by_percent(cmap, per, which='both', N=None):
'''Crop end or ends of a colormap by per percent.
:param cmap: A colormap object, like cmocean.cm.matter.
:param per: Percent of colormap to remove. If which=='both', take this
percent off both ends of colormap. If which=='min' or which=='max',
... | python | def crop_by_percent(cmap, per, which='both', N=None):
'''Crop end or ends of a colormap by per percent.
:param cmap: A colormap object, like cmocean.cm.matter.
:param per: Percent of colormap to remove. If which=='both', take this
percent off both ends of colormap. If which=='min' or which=='max',
... | [
"def",
"crop_by_percent",
"(",
"cmap",
",",
"per",
",",
"which",
"=",
"'both'",
",",
"N",
"=",
"None",
")",
":",
"if",
"which",
"==",
"'both'",
":",
"# take percent off both ends of cmap",
"vmin",
"=",
"-",
"100",
"vmax",
"=",
"100",
"pivot",
"=",
"0",
... | Crop end or ends of a colormap by per percent.
:param cmap: A colormap object, like cmocean.cm.matter.
:param per: Percent of colormap to remove. If which=='both', take this
percent off both ends of colormap. If which=='min' or which=='max',
take percent only off the specified end of colormap.
... | [
"Crop",
"end",
"or",
"ends",
"of",
"a",
"colormap",
"by",
"per",
"percent",
"."
] | 37edd4a209a733d87dea7fed9eb22adc1d5a57c8 | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/tools.py#L198-L270 |
15,168 | enricobacis/wos | wos/client.py | WosClient._premium | def _premium(fn):
"""Premium decorator for APIs that require premium access level."""
@_functools.wraps(fn)
def _fn(self, *args, **kwargs):
if self._lite:
raise RuntimeError('Premium API not available in lite access.')
return fn(self, *args, **kwargs)
... | python | def _premium(fn):
"""Premium decorator for APIs that require premium access level."""
@_functools.wraps(fn)
def _fn(self, *args, **kwargs):
if self._lite:
raise RuntimeError('Premium API not available in lite access.')
return fn(self, *args, **kwargs)
... | [
"def",
"_premium",
"(",
"fn",
")",
":",
"@",
"_functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"_fn",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_lite",
":",
"raise",
"RuntimeError",
"(",
"'Premium API no... | Premium decorator for APIs that require premium access level. | [
"Premium",
"decorator",
"for",
"APIs",
"that",
"require",
"premium",
"access",
"level",
"."
] | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L70-L77 |
15,169 | enricobacis/wos | wos/client.py | WosClient.make_retrieveParameters | def make_retrieveParameters(offset=1, count=100, name='RS', sort='D'):
"""Create retrieve parameters dictionary to be used with APIs.
:count: Number of records to display in the result. Cannot be less than
0 and cannot be greater than 100. If count is 0 then only the
sum... | python | def make_retrieveParameters(offset=1, count=100, name='RS', sort='D'):
"""Create retrieve parameters dictionary to be used with APIs.
:count: Number of records to display in the result. Cannot be less than
0 and cannot be greater than 100. If count is 0 then only the
sum... | [
"def",
"make_retrieveParameters",
"(",
"offset",
"=",
"1",
",",
"count",
"=",
"100",
",",
"name",
"=",
"'RS'",
",",
"sort",
"=",
"'D'",
")",
":",
"return",
"_OrderedDict",
"(",
"[",
"(",
"'firstRecord'",
",",
"offset",
")",
",",
"(",
"'count'",
",",
... | Create retrieve parameters dictionary to be used with APIs.
:count: Number of records to display in the result. Cannot be less than
0 and cannot be greater than 100. If count is 0 then only the
summary information will be returned.
:offset: First record in results to re... | [
"Create",
"retrieve",
"parameters",
"dictionary",
"to",
"be",
"used",
"with",
"APIs",
"."
] | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L80-L102 |
15,170 | enricobacis/wos | wos/client.py | WosClient.connect | def connect(self):
"""Authenticate to WOS and set the SID cookie."""
if not self._SID:
self._SID = self._auth.service.authenticate()
print('Authenticated (SID: %s)' % self._SID)
self._search.set_options(headers={'Cookie': 'SID="%s"' % self._SID})
self._auth.optio... | python | def connect(self):
"""Authenticate to WOS and set the SID cookie."""
if not self._SID:
self._SID = self._auth.service.authenticate()
print('Authenticated (SID: %s)' % self._SID)
self._search.set_options(headers={'Cookie': 'SID="%s"' % self._SID})
self._auth.optio... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_SID",
":",
"self",
".",
"_SID",
"=",
"self",
".",
"_auth",
".",
"service",
".",
"authenticate",
"(",
")",
"print",
"(",
"'Authenticated (SID: %s)'",
"%",
"self",
".",
"_SID",
")",
"... | Authenticate to WOS and set the SID cookie. | [
"Authenticate",
"to",
"WOS",
"and",
"set",
"the",
"SID",
"cookie",
"."
] | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L104-L112 |
15,171 | enricobacis/wos | wos/client.py | WosClient.close | def close(self):
"""The close operation loads the session if it is valid and then closes
it and releases the session seat. All the session data are deleted and
become invalid after the request is processed. The session ID can no
longer be used in subsequent requests."""
if self._... | python | def close(self):
"""The close operation loads the session if it is valid and then closes
it and releases the session seat. All the session data are deleted and
become invalid after the request is processed. The session ID can no
longer be used in subsequent requests."""
if self._... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_SID",
":",
"self",
".",
"_auth",
".",
"service",
".",
"closeSession",
"(",
")",
"self",
".",
"_SID",
"=",
"None"
] | The close operation loads the session if it is valid and then closes
it and releases the session seat. All the session data are deleted and
become invalid after the request is processed. The session ID can no
longer be used in subsequent requests. | [
"The",
"close",
"operation",
"loads",
"the",
"session",
"if",
"it",
"is",
"valid",
"and",
"then",
"closes",
"it",
"and",
"releases",
"the",
"session",
"seat",
".",
"All",
"the",
"session",
"data",
"are",
"deleted",
"and",
"become",
"invalid",
"after",
"the... | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L114-L121 |
15,172 | enricobacis/wos | wos/client.py | WosClient.search | def search(self, query, count=5, offset=1, editions=None,
symbolicTimeSpan=None, timeSpan=None, retrieveParameters=None):
"""The search operation submits a search query to the specified
database edition and retrieves data. This operation returns a query ID
that can be used in subs... | python | def search(self, query, count=5, offset=1, editions=None,
symbolicTimeSpan=None, timeSpan=None, retrieveParameters=None):
"""The search operation submits a search query to the specified
database edition and retrieves data. This operation returns a query ID
that can be used in subs... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"count",
"=",
"5",
",",
"offset",
"=",
"1",
",",
"editions",
"=",
"None",
",",
"symbolicTimeSpan",
"=",
"None",
",",
"timeSpan",
"=",
"None",
",",
"retrieveParameters",
"=",
"None",
")",
":",
"return",
... | The search operation submits a search query to the specified
database edition and retrieves data. This operation returns a query ID
that can be used in subsequent operations to retrieve more records.
:query: User query for requesting data. The query parser will return
errors for... | [
"The",
"search",
"operation",
"submits",
"a",
"search",
"query",
"to",
"the",
"specified",
"database",
"edition",
"and",
"retrieves",
"data",
".",
"This",
"operation",
"returns",
"a",
"query",
"ID",
"that",
"can",
"be",
"used",
"in",
"subsequent",
"operations"... | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L124-L187 |
15,173 | enricobacis/wos | wos/client.py | WosClient.citedReferences | def citedReferences(self, uid, count=100, offset=1,
retrieveParameters=None):
"""The citedReferences operation returns references cited by an article
identified by a unique identifier. You may specify only one identifier
per request.
:uid: Thomson Reuters unique ... | python | def citedReferences(self, uid, count=100, offset=1,
retrieveParameters=None):
"""The citedReferences operation returns references cited by an article
identified by a unique identifier. You may specify only one identifier
per request.
:uid: Thomson Reuters unique ... | [
"def",
"citedReferences",
"(",
"self",
",",
"uid",
",",
"count",
"=",
"100",
",",
"offset",
"=",
"1",
",",
"retrieveParameters",
"=",
"None",
")",
":",
"return",
"self",
".",
"_search",
".",
"service",
".",
"citedReferences",
"(",
"databaseId",
"=",
"'WO... | The citedReferences operation returns references cited by an article
identified by a unique identifier. You may specify only one identifier
per request.
:uid: Thomson Reuters unique record identifier
:count: Number of records to display in the result. Cannot be less than
... | [
"The",
"citedReferences",
"operation",
"returns",
"references",
"cited",
"by",
"an",
"article",
"identified",
"by",
"a",
"unique",
"identifier",
".",
"You",
"may",
"specify",
"only",
"one",
"identifier",
"per",
"request",
"."
] | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L250-L274 |
15,174 | enricobacis/wos | wos/client.py | WosClient.citedReferencesRetrieve | def citedReferencesRetrieve(self, queryId, count=100, offset=1,
retrieveParameters=None):
"""The citedReferencesRetrieve operation submits a query returned by a
previous citedReferences operation.
This operation is useful for overcoming the retrieval limit of 100... | python | def citedReferencesRetrieve(self, queryId, count=100, offset=1,
retrieveParameters=None):
"""The citedReferencesRetrieve operation submits a query returned by a
previous citedReferences operation.
This operation is useful for overcoming the retrieval limit of 100... | [
"def",
"citedReferencesRetrieve",
"(",
"self",
",",
"queryId",
",",
"count",
"=",
"100",
",",
"offset",
"=",
"1",
",",
"retrieveParameters",
"=",
"None",
")",
":",
"return",
"self",
".",
"_search",
".",
"service",
".",
"citedReferencesRetrieve",
"(",
"queryI... | The citedReferencesRetrieve operation submits a query returned by a
previous citedReferences operation.
This operation is useful for overcoming the retrieval limit of 100
records per query. For example, a citedReferences operation may find
106 cited references, as revealed by the conten... | [
"The",
"citedReferencesRetrieve",
"operation",
"submits",
"a",
"query",
"returned",
"by",
"a",
"previous",
"citedReferences",
"operation",
"."
] | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/client.py#L278-L305 |
15,175 | enricobacis/wos | wos/utils.py | single | def single(wosclient, wos_query, xml_query=None, count=5, offset=1):
"""Perform a single Web of Science query and then XML query the results."""
result = wosclient.search(wos_query, count, offset)
xml = _re.sub(' xmlns="[^"]+"', '', result.records, count=1).encode('utf-8')
if xml_query:
xml = _E... | python | def single(wosclient, wos_query, xml_query=None, count=5, offset=1):
"""Perform a single Web of Science query and then XML query the results."""
result = wosclient.search(wos_query, count, offset)
xml = _re.sub(' xmlns="[^"]+"', '', result.records, count=1).encode('utf-8')
if xml_query:
xml = _E... | [
"def",
"single",
"(",
"wosclient",
",",
"wos_query",
",",
"xml_query",
"=",
"None",
",",
"count",
"=",
"5",
",",
"offset",
"=",
"1",
")",
":",
"result",
"=",
"wosclient",
".",
"search",
"(",
"wos_query",
",",
"count",
",",
"offset",
")",
"xml",
"=",
... | Perform a single Web of Science query and then XML query the results. | [
"Perform",
"a",
"single",
"Web",
"of",
"Science",
"query",
"and",
"then",
"XML",
"query",
"the",
"results",
"."
] | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/utils.py#L10-L18 |
15,176 | enricobacis/wos | wos/utils.py | query | def query(wosclient, wos_query, xml_query=None, count=5, offset=1, limit=100):
"""Query Web of Science and XML query results with multiple requests."""
results = [single(wosclient, wos_query, xml_query, min(limit, count-x+1), x)
for x in range(offset, count+1, limit)]
if xml_query:
re... | python | def query(wosclient, wos_query, xml_query=None, count=5, offset=1, limit=100):
"""Query Web of Science and XML query results with multiple requests."""
results = [single(wosclient, wos_query, xml_query, min(limit, count-x+1), x)
for x in range(offset, count+1, limit)]
if xml_query:
re... | [
"def",
"query",
"(",
"wosclient",
",",
"wos_query",
",",
"xml_query",
"=",
"None",
",",
"count",
"=",
"5",
",",
"offset",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"results",
"=",
"[",
"single",
"(",
"wosclient",
",",
"wos_query",
",",
"xml_query... | Query Web of Science and XML query results with multiple requests. | [
"Query",
"Web",
"of",
"Science",
"and",
"XML",
"query",
"results",
"with",
"multiple",
"requests",
"."
] | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/utils.py#L21-L31 |
15,177 | enricobacis/wos | wos/utils.py | doi_to_wos | def doi_to_wos(wosclient, doi):
"""Convert DOI to WOS identifier."""
results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1)
return results[0].lstrip('WOS:') if results else None | python | def doi_to_wos(wosclient, doi):
"""Convert DOI to WOS identifier."""
results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1)
return results[0].lstrip('WOS:') if results else None | [
"def",
"doi_to_wos",
"(",
"wosclient",
",",
"doi",
")",
":",
"results",
"=",
"query",
"(",
"wosclient",
",",
"'DO=\"%s\"'",
"%",
"doi",
",",
"'./REC/UID'",
",",
"count",
"=",
"1",
")",
"return",
"results",
"[",
"0",
"]",
".",
"lstrip",
"(",
"'WOS:'",
... | Convert DOI to WOS identifier. | [
"Convert",
"DOI",
"to",
"WOS",
"identifier",
"."
] | a51f4d1a983c2c7529caac3e09606a432223630d | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/utils.py#L34-L37 |
15,178 | adamchainz/django-perf-rec | django_perf_rec/sql.py | sql_fingerprint | def sql_fingerprint(query, hide_columns=True):
"""
Simplify a query, taking away exact values and fields selected.
Imperfect but better than super explicit, value-dependent queries.
"""
parsed_query = parse(query)[0]
sql_recursively_simplify(parsed_query, hide_columns=hide_columns)
return s... | python | def sql_fingerprint(query, hide_columns=True):
"""
Simplify a query, taking away exact values and fields selected.
Imperfect but better than super explicit, value-dependent queries.
"""
parsed_query = parse(query)[0]
sql_recursively_simplify(parsed_query, hide_columns=hide_columns)
return s... | [
"def",
"sql_fingerprint",
"(",
"query",
",",
"hide_columns",
"=",
"True",
")",
":",
"parsed_query",
"=",
"parse",
"(",
"query",
")",
"[",
"0",
"]",
"sql_recursively_simplify",
"(",
"parsed_query",
",",
"hide_columns",
"=",
"hide_columns",
")",
"return",
"str",... | Simplify a query, taking away exact values and fields selected.
Imperfect but better than super explicit, value-dependent queries. | [
"Simplify",
"a",
"query",
"taking",
"away",
"exact",
"values",
"and",
"fields",
"selected",
"."
] | 76a1874820b55bcbc2f95a85bbda3cb056584e2c | https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/sql.py#L7-L15 |
15,179 | adamchainz/django-perf-rec | django_perf_rec/sql.py | match_keyword | def match_keyword(token, keywords):
"""
Checks if the given token represents one of the given keywords
"""
if not token:
return False
if not token.is_keyword:
return False
return token.value.upper() in keywords | python | def match_keyword(token, keywords):
"""
Checks if the given token represents one of the given keywords
"""
if not token:
return False
if not token.is_keyword:
return False
return token.value.upper() in keywords | [
"def",
"match_keyword",
"(",
"token",
",",
"keywords",
")",
":",
"if",
"not",
"token",
":",
"return",
"False",
"if",
"not",
"token",
".",
"is_keyword",
":",
"return",
"False",
"return",
"token",
".",
"value",
".",
"upper",
"(",
")",
"in",
"keywords"
] | Checks if the given token represents one of the given keywords | [
"Checks",
"if",
"the",
"given",
"token",
"represents",
"one",
"of",
"the",
"given",
"keywords"
] | 76a1874820b55bcbc2f95a85bbda3cb056584e2c | https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/sql.py#L84-L93 |
15,180 | adamchainz/django-perf-rec | django_perf_rec/sql.py | _is_group | def _is_group(token):
"""
sqlparse 0.2.2 changed it from a callable to a bool property
"""
is_group = token.is_group
if isinstance(is_group, bool):
return is_group
else:
return is_group() | python | def _is_group(token):
"""
sqlparse 0.2.2 changed it from a callable to a bool property
"""
is_group = token.is_group
if isinstance(is_group, bool):
return is_group
else:
return is_group() | [
"def",
"_is_group",
"(",
"token",
")",
":",
"is_group",
"=",
"token",
".",
"is_group",
"if",
"isinstance",
"(",
"is_group",
",",
"bool",
")",
":",
"return",
"is_group",
"else",
":",
"return",
"is_group",
"(",
")"
] | sqlparse 0.2.2 changed it from a callable to a bool property | [
"sqlparse",
"0",
".",
"2",
".",
"2",
"changed",
"it",
"from",
"a",
"callable",
"to",
"a",
"bool",
"property"
] | 76a1874820b55bcbc2f95a85bbda3cb056584e2c | https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/sql.py#L96-L104 |
15,181 | adamchainz/django-perf-rec | django_perf_rec/utils.py | sorted_names | def sorted_names(names):
"""
Sort a list of names but keep the word 'default' first if it's there.
"""
names = list(names)
have_default = False
if 'default' in names:
names.remove('default')
have_default = True
sorted_names = sorted(names)
if have_default:
sort... | python | def sorted_names(names):
"""
Sort a list of names but keep the word 'default' first if it's there.
"""
names = list(names)
have_default = False
if 'default' in names:
names.remove('default')
have_default = True
sorted_names = sorted(names)
if have_default:
sort... | [
"def",
"sorted_names",
"(",
"names",
")",
":",
"names",
"=",
"list",
"(",
"names",
")",
"have_default",
"=",
"False",
"if",
"'default'",
"in",
"names",
":",
"names",
".",
"remove",
"(",
"'default'",
")",
"have_default",
"=",
"True",
"sorted_names",
"=",
... | Sort a list of names but keep the word 'default' first if it's there. | [
"Sort",
"a",
"list",
"of",
"names",
"but",
"keep",
"the",
"word",
"default",
"first",
"if",
"it",
"s",
"there",
"."
] | 76a1874820b55bcbc2f95a85bbda3cb056584e2c | https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/utils.py#L82-L98 |
15,182 | adamchainz/django-perf-rec | django_perf_rec/utils.py | record_diff | def record_diff(old, new):
"""
Generate a human-readable diff of two performance records.
"""
return '\n'.join(difflib.ndiff(
['%s: %s' % (k, v) for op in old for k, v in op.items()],
['%s: %s' % (k, v) for op in new for k, v in op.items()],
)) | python | def record_diff(old, new):
"""
Generate a human-readable diff of two performance records.
"""
return '\n'.join(difflib.ndiff(
['%s: %s' % (k, v) for op in old for k, v in op.items()],
['%s: %s' % (k, v) for op in new for k, v in op.items()],
)) | [
"def",
"record_diff",
"(",
"old",
",",
"new",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"difflib",
".",
"ndiff",
"(",
"[",
"'%s: %s'",
"%",
"(",
"k",
",",
"v",
")",
"for",
"op",
"in",
"old",
"for",
"k",
",",
"v",
"in",
"op",
".",
"items",
... | Generate a human-readable diff of two performance records. | [
"Generate",
"a",
"human",
"-",
"readable",
"diff",
"of",
"two",
"performance",
"records",
"."
] | 76a1874820b55bcbc2f95a85bbda3cb056584e2c | https://github.com/adamchainz/django-perf-rec/blob/76a1874820b55bcbc2f95a85bbda3cb056584e2c/django_perf_rec/utils.py#L101-L108 |
15,183 | reportportal/client-Python | reportportal_client/service_async.py | QueueListener.dequeue | def dequeue(self, block=True):
"""Dequeue a record and return item."""
return self.queue.get(block, self.queue_get_timeout) | python | def dequeue(self, block=True):
"""Dequeue a record and return item."""
return self.queue.get(block, self.queue_get_timeout) | [
"def",
"dequeue",
"(",
"self",
",",
"block",
"=",
"True",
")",
":",
"return",
"self",
".",
"queue",
".",
"get",
"(",
"block",
",",
"self",
".",
"queue_get_timeout",
")"
] | Dequeue a record and return item. | [
"Dequeue",
"a",
"record",
"and",
"return",
"item",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L39-L41 |
15,184 | reportportal/client-Python | reportportal_client/service_async.py | QueueListener.start | def start(self):
"""Start the listener.
This starts up a background thread to monitor the queue for
items to process.
"""
self._thread = t = threading.Thread(target=self._monitor)
t.setDaemon(True)
t.start() | python | def start(self):
"""Start the listener.
This starts up a background thread to monitor the queue for
items to process.
"""
self._thread = t = threading.Thread(target=self._monitor)
t.setDaemon(True)
t.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_thread",
"=",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_monitor",
")",
"t",
".",
"setDaemon",
"(",
"True",
")",
"t",
".",
"start",
"(",
")"
] | Start the listener.
This starts up a background thread to monitor the queue for
items to process. | [
"Start",
"the",
"listener",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L43-L51 |
15,185 | reportportal/client-Python | reportportal_client/service_async.py | QueueListener.handle | def handle(self, record):
"""Handle an item.
This just loops through the handlers offering them the record
to handle.
"""
record = self.prepare(record)
for handler in self.handlers:
handler(record) | python | def handle(self, record):
"""Handle an item.
This just loops through the handlers offering them the record
to handle.
"""
record = self.prepare(record)
for handler in self.handlers:
handler(record) | [
"def",
"handle",
"(",
"self",
",",
"record",
")",
":",
"record",
"=",
"self",
".",
"prepare",
"(",
"record",
")",
"for",
"handler",
"in",
"self",
".",
"handlers",
":",
"handler",
"(",
"record",
")"
] | Handle an item.
This just loops through the handlers offering them the record
to handle. | [
"Handle",
"an",
"item",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L62-L70 |
15,186 | reportportal/client-Python | reportportal_client/service_async.py | QueueListener._monitor | def _monitor(self):
"""Monitor the queue for items, and ask the handler to deal with them.
This method runs on a separate, internal thread.
The thread will terminate if it sees a sentinel object in the queue.
"""
err_msg = ("invalid internal state:"
" _stop_no... | python | def _monitor(self):
"""Monitor the queue for items, and ask the handler to deal with them.
This method runs on a separate, internal thread.
The thread will terminate if it sees a sentinel object in the queue.
"""
err_msg = ("invalid internal state:"
" _stop_no... | [
"def",
"_monitor",
"(",
"self",
")",
":",
"err_msg",
"=",
"(",
"\"invalid internal state:\"",
"\" _stop_nowait can not be set if _stop is not set\"",
")",
"assert",
"self",
".",
"_stop",
".",
"isSet",
"(",
")",
"or",
"not",
"self",
".",
"_stop_nowait",
".",
"isSet... | Monitor the queue for items, and ask the handler to deal with them.
This method runs on a separate, internal thread.
The thread will terminate if it sees a sentinel object in the queue. | [
"Monitor",
"the",
"queue",
"for",
"items",
"and",
"ask",
"the",
"handler",
"to",
"deal",
"with",
"them",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L72-L106 |
15,187 | reportportal/client-Python | reportportal_client/service_async.py | QueueListener.stop | def stop(self, nowait=False):
"""Stop the listener.
This asks the thread to terminate, and then waits for it to do so.
Note that if you don't call this before your application exits, there
may be some records still left on the queue, which won't be processed.
If nowait is False ... | python | def stop(self, nowait=False):
"""Stop the listener.
This asks the thread to terminate, and then waits for it to do so.
Note that if you don't call this before your application exits, there
may be some records still left on the queue, which won't be processed.
If nowait is False ... | [
"def",
"stop",
"(",
"self",
",",
"nowait",
"=",
"False",
")",
":",
"self",
".",
"_stop",
".",
"set",
"(",
")",
"if",
"nowait",
":",
"self",
".",
"_stop_nowait",
".",
"set",
"(",
")",
"self",
".",
"queue",
".",
"put_nowait",
"(",
"self",
".",
"_se... | Stop the listener.
This asks the thread to terminate, and then waits for it to do so.
Note that if you don't call this before your application exits, there
may be some records still left on the queue, which won't be processed.
If nowait is False then thread will handle remaining items i... | [
"Stop",
"the",
"listener",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L108-L126 |
15,188 | reportportal/client-Python | reportportal_client/service_async.py | ReportPortalServiceAsync.terminate | def terminate(self, nowait=False):
"""Finalize and stop service
Args:
nowait: set to True to terminate immediately and skip processing
messages still in the queue
"""
logger.debug("Acquiring lock for service termination")
with self.lock:
l... | python | def terminate(self, nowait=False):
"""Finalize and stop service
Args:
nowait: set to True to terminate immediately and skip processing
messages still in the queue
"""
logger.debug("Acquiring lock for service termination")
with self.lock:
l... | [
"def",
"terminate",
"(",
"self",
",",
"nowait",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Acquiring lock for service termination\"",
")",
"with",
"self",
".",
"lock",
":",
"logger",
".",
"debug",
"(",
"\"Terminating service\"",
")",
"if",
"not",
... | Finalize and stop service
Args:
nowait: set to True to terminate immediately and skip processing
messages still in the queue | [
"Finalize",
"and",
"stop",
"service"
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L169-L196 |
15,189 | reportportal/client-Python | reportportal_client/service_async.py | ReportPortalServiceAsync.process_log | def process_log(self, **log_item):
"""Special handler for log messages.
Accumulate incoming log messages and post them in batch.
"""
logger.debug("Processing log item: %s", log_item)
self.log_batch.append(log_item)
if len(self.log_batch) >= self.log_batch_size:
... | python | def process_log(self, **log_item):
"""Special handler for log messages.
Accumulate incoming log messages and post them in batch.
"""
logger.debug("Processing log item: %s", log_item)
self.log_batch.append(log_item)
if len(self.log_batch) >= self.log_batch_size:
... | [
"def",
"process_log",
"(",
"self",
",",
"*",
"*",
"log_item",
")",
":",
"logger",
".",
"debug",
"(",
"\"Processing log item: %s\"",
",",
"log_item",
")",
"self",
".",
"log_batch",
".",
"append",
"(",
"log_item",
")",
"if",
"len",
"(",
"self",
".",
"log_b... | Special handler for log messages.
Accumulate incoming log messages and post them in batch. | [
"Special",
"handler",
"for",
"log",
"messages",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L206-L214 |
15,190 | reportportal/client-Python | reportportal_client/service_async.py | ReportPortalServiceAsync.process_item | def process_item(self, item):
"""Main item handler.
Called by queue listener.
"""
logger.debug("Processing item: %s (queue size: %s)", item,
self.queue.qsize())
method, kwargs = item
if method not in self.supported_methods:
raise Error("... | python | def process_item(self, item):
"""Main item handler.
Called by queue listener.
"""
logger.debug("Processing item: %s (queue size: %s)", item,
self.queue.qsize())
method, kwargs = item
if method not in self.supported_methods:
raise Error("... | [
"def",
"process_item",
"(",
"self",
",",
"item",
")",
":",
"logger",
".",
"debug",
"(",
"\"Processing item: %s (queue size: %s)\"",
",",
"item",
",",
"self",
".",
"queue",
".",
"qsize",
"(",
")",
")",
"method",
",",
"kwargs",
"=",
"item",
"if",
"method",
... | Main item handler.
Called by queue listener. | [
"Main",
"item",
"handler",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L216-L239 |
15,191 | reportportal/client-Python | reportportal_client/service_async.py | ReportPortalServiceAsync.log | def log(self, time, message, level=None, attachment=None):
"""Logs a message with attachment.
The attachment is a dict of:
name: name of attachment
data: file content
mime: content type for attachment
"""
logger.debug("log queued")
args = {
... | python | def log(self, time, message, level=None, attachment=None):
"""Logs a message with attachment.
The attachment is a dict of:
name: name of attachment
data: file content
mime: content type for attachment
"""
logger.debug("log queued")
args = {
... | [
"def",
"log",
"(",
"self",
",",
"time",
",",
"message",
",",
"level",
"=",
"None",
",",
"attachment",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"log queued\"",
")",
"args",
"=",
"{",
"\"time\"",
":",
"time",
",",
"\"message\"",
":",
"mess... | Logs a message with attachment.
The attachment is a dict of:
name: name of attachment
data: file content
mime: content type for attachment | [
"Logs",
"a",
"message",
"with",
"attachment",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service_async.py#L296-L312 |
15,192 | reportportal/client-Python | reportportal_client/service.py | ReportPortalService.log_batch | def log_batch(self, log_data):
"""Logs batch of messages with attachment.
Args:
log_data: list of log records.
log record is a dict of;
time, message, level, attachment
attachment is a dict of:
name: name of attachment
... | python | def log_batch(self, log_data):
"""Logs batch of messages with attachment.
Args:
log_data: list of log records.
log record is a dict of;
time, message, level, attachment
attachment is a dict of:
name: name of attachment
... | [
"def",
"log_batch",
"(",
"self",
",",
"log_data",
")",
":",
"url",
"=",
"uri_join",
"(",
"self",
".",
"base_url",
",",
"\"log\"",
")",
"attachments",
"=",
"[",
"]",
"for",
"log_item",
"in",
"log_data",
":",
"log_item",
"[",
"\"item_id\"",
"]",
"=",
"se... | Logs batch of messages with attachment.
Args:
log_data: list of log records.
log record is a dict of;
time, message, level, attachment
attachment is a dict of:
name: name of attachment
data: fileobj or content
... | [
"Logs",
"batch",
"of",
"messages",
"with",
"attachment",
"."
] | 8d22445d0de73f46fb23d0c0e49ac309335173ce | https://github.com/reportportal/client-Python/blob/8d22445d0de73f46fb23d0c0e49ac309335173ce/reportportal_client/service.py#L250-L312 |
15,193 | saltstack/pytest-salt | versioneer.py | git_versions_from_keywords | def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compli... | python | def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compli... | [
"def",
"git_versions_from_keywords",
"(",
"keywords",
",",
"tag_prefix",
",",
"verbose",
")",
":",
"if",
"not",
"keywords",
":",
"raise",
"NotThisMethod",
"(",
"\"no keywords at all, weird\"",
")",
"date",
"=",
"keywords",
".",
"get",
"(",
"\"date\"",
")",
"if",... | Get version information from git keywords. | [
"Get",
"version",
"information",
"from",
"git",
"keywords",
"."
] | 3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d | https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1042-L1094 |
15,194 | saltstack/pytest-salt | versioneer.py | render_pep440_branch_based | def render_pep440_branch_based(pieces):
"""Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty
Exceptions:
1: no tags. git_describe was just H... | python | def render_pep440_branch_based(pieces):
"""Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty
Exceptions:
1: no tags. git_describe was just H... | [
"def",
"render_pep440_branch_based",
"(",
"pieces",
")",
":",
"replacements",
"=",
"(",
"[",
"' '",
",",
"'.'",
"]",
",",
"[",
"'('",
",",
"''",
"]",
",",
"[",
"')'",
",",
"''",
"]",
",",
"[",
"'\\\\'",
",",
"'.'",
"]",
",",
"[",
"'/'",
",",
"'... | Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.BRANCH_gHEX[.dirty] | [
"Build",
"up",
"version",
"string",
"with",
"post",
"-",
"release",
"local",
"version",
"identifier",
"."
] | 3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d | https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1458-L1495 |
15,195 | saltstack/pytest-salt | versioneer.py | render | def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None}
... | python | def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None}
... | [
"def",
"render",
"(",
"pieces",
",",
"style",
")",
":",
"if",
"pieces",
"[",
"\"error\"",
"]",
":",
"return",
"{",
"\"version\"",
":",
"\"unknown\"",
",",
"\"full-revisionid\"",
":",
"pieces",
".",
"get",
"(",
"\"long\"",
")",
",",
"\"dirty\"",
":",
"Non... | Render the given version pieces into the requested style. | [
"Render",
"the",
"given",
"version",
"pieces",
"into",
"the",
"requested",
"style",
"."
] | 3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d | https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1498-L1529 |
15,196 | saltstack/pytest-salt | versioneer.py | do_setup | def do_setup():
"""Do main VCS-independent setup function for installing Versioneer."""
root = get_root()
try:
cfg = get_config_from_root(root)
except (EnvironmentError, configparser.NoSectionError,
configparser.NoOptionError) as e:
if isinstance(e, (EnvironmentError, configp... | python | def do_setup():
"""Do main VCS-independent setup function for installing Versioneer."""
root = get_root()
try:
cfg = get_config_from_root(root)
except (EnvironmentError, configparser.NoSectionError,
configparser.NoOptionError) as e:
if isinstance(e, (EnvironmentError, configp... | [
"def",
"do_setup",
"(",
")",
":",
"root",
"=",
"get_root",
"(",
")",
"try",
":",
"cfg",
"=",
"get_config_from_root",
"(",
"root",
")",
"except",
"(",
"EnvironmentError",
",",
"configparser",
".",
"NoSectionError",
",",
"configparser",
".",
"NoOptionError",
"... | Do main VCS-independent setup function for installing Versioneer. | [
"Do",
"main",
"VCS",
"-",
"independent",
"setup",
"function",
"for",
"installing",
"Versioneer",
"."
] | 3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d | https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1846-L1925 |
15,197 | saltstack/pytest-salt | versioneer.py | scan_setup_py | def scan_setup_py():
"""Validate the contents of setup.py against Versioneer's expectations."""
found = set()
setters = False
errors = 0
with open("setup.py", "r") as f:
for line in f.readlines():
if "import versioneer" in line:
found.add("import")
if ... | python | def scan_setup_py():
"""Validate the contents of setup.py against Versioneer's expectations."""
found = set()
setters = False
errors = 0
with open("setup.py", "r") as f:
for line in f.readlines():
if "import versioneer" in line:
found.add("import")
if ... | [
"def",
"scan_setup_py",
"(",
")",
":",
"found",
"=",
"set",
"(",
")",
"setters",
"=",
"False",
"errors",
"=",
"0",
"with",
"open",
"(",
"\"setup.py\"",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
... | Validate the contents of setup.py against Versioneer's expectations. | [
"Validate",
"the",
"contents",
"of",
"setup",
".",
"py",
"against",
"Versioneer",
"s",
"expectations",
"."
] | 3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d | https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/versioneer.py#L1928-L1962 |
15,198 | saltstack/pytest-salt | setup.py | read | def read(fname):
'''
Read a file from the directory where setup.py resides
'''
file_path = os.path.join(SETUP_DIRNAME, fname)
with codecs.open(file_path, encoding='utf-8') as rfh:
return rfh.read() | python | def read(fname):
'''
Read a file from the directory where setup.py resides
'''
file_path = os.path.join(SETUP_DIRNAME, fname)
with codecs.open(file_path, encoding='utf-8') as rfh:
return rfh.read() | [
"def",
"read",
"(",
"fname",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SETUP_DIRNAME",
",",
"fname",
")",
"with",
"codecs",
".",
"open",
"(",
"file_path",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"rfh",
":",
"return",
"rfh"... | Read a file from the directory where setup.py resides | [
"Read",
"a",
"file",
"from",
"the",
"directory",
"where",
"setup",
".",
"py",
"resides"
] | 3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d | https://github.com/saltstack/pytest-salt/blob/3e8c379b3636c64707e7a08b8eb6c9af20a1ac4d/setup.py#L23-L29 |
15,199 | jeongyoonlee/Kaggler | kaggler/model/nn.py | NN.func | def func(self, w, *args):
"""Return the costs of the neural network for predictions.
Args:
w (array of float): weight vectors such that:
w[:-h1] -- weights between the input and h layers
w[-h1:] -- weights between the h and output layers
args: fea... | python | def func(self, w, *args):
"""Return the costs of the neural network for predictions.
Args:
w (array of float): weight vectors such that:
w[:-h1] -- weights between the input and h layers
w[-h1:] -- weights between the h and output layers
args: fea... | [
"def",
"func",
"(",
"self",
",",
"w",
",",
"*",
"args",
")",
":",
"x0",
"=",
"args",
"[",
"0",
"]",
"x1",
"=",
"args",
"[",
"1",
"]",
"n0",
"=",
"x0",
".",
"shape",
"[",
"0",
"]",
"n1",
"=",
"x1",
".",
"shape",
"[",
"0",
"]",
"# n -- numb... | Return the costs of the neural network for predictions.
Args:
w (array of float): weight vectors such that:
w[:-h1] -- weights between the input and h layers
w[-h1:] -- weights between the h and output layers
args: features (args[0]) and target (args[1])
... | [
"Return",
"the",
"costs",
"of",
"the",
"neural",
"network",
"for",
"predictions",
"."
] | 20661105b61958dc9a3c529c1d3b2313ab23ae32 | https://github.com/jeongyoonlee/Kaggler/blob/20661105b61958dc9a3c529c1d3b2313ab23ae32/kaggler/model/nn.py#L204-L256 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.