nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
Python-Markdown/markdown
af38c42706f8dff93694d4a7572003dbd8b0ddc0
markdown/blockparser.py
python
State.set
(self, state)
Set a new state.
Set a new state.
[ "Set", "a", "new", "state", "." ]
def set(self, state): """ Set a new state. """ self.append(state)
[ "def", "set", "(", "self", ",", "state", ")", ":", "self", ".", "append", "(", "state", ")" ]
https://github.com/Python-Markdown/markdown/blob/af38c42706f8dff93694d4a7572003dbd8b0ddc0/markdown/blockparser.py#L44-L46
facebookresearch/SlowFast
39ef35c9a086443209b458cceaec86a02e27b369
slowfast/datasets/cv2_transform.py
python
contrast
(var, image)
return blend(image, img_gray, alpha)
Perform color contrast on the given image. Args: var (float): variance. image (array): image to perform color contrast. Returns: (array): image that performed color contrast.
Perform color contrast on the given image. Args: var (float): variance. image (array): image to perform color contrast. Returns: (array): image that performed color contrast.
[ "Perform", "color", "contrast", "on", "the", "given", "image", ".", "Args", ":", "var", "(", "float", ")", ":", "variance", ".", "image", "(", "array", ")", ":", "image", "to", "perform", "color", "contrast", ".", "Returns", ":", "(", "array", ")", "...
def contrast(var, image): """ Perform color contrast on the given image. Args: var (float): variance. image (array): image to perform color contrast. Returns: (array): image that performed color contrast. """ img_gray = grayscale(image) img_gray.fill(np.mean(img_gray[0])) alpha = 1.0 + np.random.uniform(-var, var) return blend(image, img_gray, alpha)
[ "def", "contrast", "(", "var", ",", "image", ")", ":", "img_gray", "=", "grayscale", "(", "image", ")", "img_gray", ".", "fill", "(", "np", ".", "mean", "(", "img_gray", "[", "0", "]", ")", ")", "alpha", "=", "1.0", "+", "np", ".", "random", ".",...
https://github.com/facebookresearch/SlowFast/blob/39ef35c9a086443209b458cceaec86a02e27b369/slowfast/datasets/cv2_transform.py#L682-L694
selinon/selinon
3613153566d454022a138639f0375c63f490c4cb
selinon/predicates/fieldUrlScheme.py
python
fieldUrlScheme
(message, key, scheme)
[]
def fieldUrlScheme(message, key, scheme): try: val = reduce(lambda m, k: m[k], key if isinstance(key, list) else [key], message) return urlparse(val).scheme == scheme except: return False
[ "def", "fieldUrlScheme", "(", "message", ",", "key", ",", "scheme", ")", ":", "try", ":", "val", "=", "reduce", "(", "lambda", "m", ",", "k", ":", "m", "[", "k", "]", ",", "key", "if", "isinstance", "(", "key", ",", "list", ")", "else", "[", "k...
https://github.com/selinon/selinon/blob/3613153566d454022a138639f0375c63f490c4cb/selinon/predicates/fieldUrlScheme.py#L8-L13
longcw/youdao
afb518ff792ae12477081d11cf6384d3eff1ae23
youdao/lib/pystardict.py
python
Dictionary.clear
(self)
clear dict cache
clear dict cache
[ "clear", "dict", "cache" ]
def clear(self): """ clear dict cache """ self._dict_cache = dict()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_dict_cache", "=", "dict", "(", ")" ]
https://github.com/longcw/youdao/blob/afb518ff792ae12477081d11cf6384d3eff1ae23/youdao/lib/pystardict.py#L541-L545
itailang/SampleNet
442459abc54f9e14f0966a169a094a98febd32eb
reconstruction/src/sampler_autoencoder.py
python
SamplerAutoEncoder.get_loss_ae_per_pc
(self, feed_data, samp_data, orig_data=None)
return ae_loss
[]
def get_loss_ae_per_pc(self, feed_data, samp_data, orig_data=None): feed_data_shape = feed_data.shape assert len(feed_data_shape) == 3, "The feed data should have 3 dimensions" if orig_data is not None: assert ( feed_data_shape == orig_data.shape ), "The feed data and original data should have the same size" else: orig_data = feed_data n_examples = feed_data_shape[0] ae_loss = np.zeros(n_examples) for i in range(0, n_examples, 1): ae_loss[i] = self.get_loss_ae( feed_data[i : i + 1], orig_data[i : i + 1], samp_data[i : i + 1] ) return ae_loss
[ "def", "get_loss_ae_per_pc", "(", "self", ",", "feed_data", ",", "samp_data", ",", "orig_data", "=", "None", ")", ":", "feed_data_shape", "=", "feed_data", ".", "shape", "assert", "len", "(", "feed_data_shape", ")", "==", "3", ",", "\"The feed data should have 3...
https://github.com/itailang/SampleNet/blob/442459abc54f9e14f0966a169a094a98febd32eb/reconstruction/src/sampler_autoencoder.py#L149-L167
geigi/cozy
5006ea7097534e18adf525d1d0ec384ddc000404
cozy/control/string_representation.py
python
seconds_to_str
(seconds, max_length=None, include_seconds=True)
return result
Converts seconds to a string with the following apperance: hh:mm:ss :param seconds: The seconds as float
Converts seconds to a string with the following apperance: hh:mm:ss
[ "Converts", "seconds", "to", "a", "string", "with", "the", "following", "apperance", ":", "hh", ":", "mm", ":", "ss" ]
def seconds_to_str(seconds, max_length=None, include_seconds=True): """ Converts seconds to a string with the following apperance: hh:mm:ss :param seconds: The seconds as float """ m, s = divmod(seconds, 60) h, m = divmod(m, 60) if max_length: max_m, max_s = divmod(max_length, 60) max_h, max_m = divmod(max_m, 60) else: max_h = h max_m = m max_s = s if (max_h >= 10): result = "%02d:%02d" % (h, m) elif (max_h >= 1): result = "%d:%02d" % (h, m) else: result = "%02d" % (m) if include_seconds: result += ":%02d" % (s) return result
[ "def", "seconds_to_str", "(", "seconds", ",", "max_length", "=", "None", ",", "include_seconds", "=", "True", ")", ":", "m", ",", "s", "=", "divmod", "(", "seconds", ",", "60", ")", "h", ",", "m", "=", "divmod", "(", "m", ",", "60", ")", "if", "m...
https://github.com/geigi/cozy/blob/5006ea7097534e18adf525d1d0ec384ddc000404/cozy/control/string_representation.py#L1-L29
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pywin/Lib/mailbox.py
python
MaildirMessage.remove_flag
(self, flag)
Unset the given string flag(s) without changing others.
Unset the given string flag(s) without changing others.
[ "Unset", "the", "given", "string", "flag", "(", "s", ")", "without", "changing", "others", "." ]
def remove_flag(self, flag): """Unset the given string flag(s) without changing others.""" if self.get_flags() != '': self.set_flags(''.join(set(self.get_flags()) - set(flag)))
[ "def", "remove_flag", "(", "self", ",", "flag", ")", ":", "if", "self", ".", "get_flags", "(", ")", "!=", "''", ":", "self", ".", "set_flags", "(", "''", ".", "join", "(", "set", "(", "self", ".", "get_flags", "(", ")", ")", "-", "set", "(", "f...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/mailbox.py#L1517-L1520
tobspr/RenderPipeline
d8c38c0406a63298f4801782a8e44e9c1e467acf
rpplugins/scattering/scattering_methods.py
python
ScatteringMethodEricBruneton.load
(self)
Inits parameters, those should match with the ones specified in common.glsl
Inits parameters, those should match with the ones specified in common.glsl
[ "Inits", "parameters", "those", "should", "match", "with", "the", "ones", "specified", "in", "common", ".", "glsl" ]
def load(self): """ Inits parameters, those should match with the ones specified in common.glsl """ self.use_32_bit = False self.trans_w, self.trans_h = 256 * 4, 64 * 4 self.sky_w, self.sky_h = 64 * 4, 16 * 4 self.res_r, self.res_mu, self.res_mu_s, self.res_nu = 32, 128, 32, 8 self.res_mu_s_nu = self.res_mu_s * self.res_nu self.create_shaders() self.create_textures()
[ "def", "load", "(", "self", ")", ":", "self", ".", "use_32_bit", "=", "False", "self", ".", "trans_w", ",", "self", ".", "trans_h", "=", "256", "*", "4", ",", "64", "*", "4", "self", ".", "sky_w", ",", "self", ".", "sky_h", "=", "64", "*", "4",...
https://github.com/tobspr/RenderPipeline/blob/d8c38c0406a63298f4801782a8e44e9c1e467acf/rpplugins/scattering/scattering_methods.py#L95-L104
Tencent/bk-bcs-saas
2b437bf2f5fd5ce2078f7787c3a12df609f7679d
bcs-app/backend/uniapps/application/filters/views.py
python
GetAllMusters.get
(self, request, project_id)
return APIResponse({"data": ret_data})
查询项目下不同集群类型的模板集
查询项目下不同集群类型的模板集
[ "查询项目下不同集群类型的模板集" ]
def get(self, request, project_id): """查询项目下不同集群类型的模板集""" flag, kind = self.get_project_kind(request, project_id) if not flag: return kind cluster_type, category = self.get_cluster_category(request, kind) all_musters = self.get_muster(project_id) version_inst_map = self.get_version_instances(all_musters.keys()) version_inst_cluster = self.get_insts(version_inst_map.keys(), category=category) cluster_env_map = self.get_cluster_id_env(request, project_id) # 组装数据 ret_data = self.compose_data( all_musters, version_inst_map, version_inst_cluster, cluster_env_map, cluster_type, request.query_params.get("cluster_id"), ) ret_data = [{"muster_id": key, "muster_name": val} for key, val in ret_data.items()] return APIResponse({"data": ret_data})
[ "def", "get", "(", "self", ",", "request", ",", "project_id", ")", ":", "flag", ",", "kind", "=", "self", ".", "get_project_kind", "(", "request", ",", "project_id", ")", "if", "not", "flag", ":", "return", "kind", "cluster_type", ",", "category", "=", ...
https://github.com/Tencent/bk-bcs-saas/blob/2b437bf2f5fd5ce2078f7787c3a12df609f7679d/bcs-app/backend/uniapps/application/filters/views.py#L102-L122
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_vendor/urllib3/packages/six.py
python
add_metaclass
(metaclass)
return wrapper
Class decorator for creating a class with a metaclass.
Class decorator for creating a class with a metaclass.
[ "Class", "decorator", "for", "creating", "a", "class", "with", "a", "metaclass", "." ]
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper
[ "def", "add_metaclass", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "orig_vars", "=", "cls", ".", "__dict__", ".", "copy", "(", ")", "slots", "=", "orig_vars", ".", "get", "(", "'__slots__'", ")", "if", "slots", "is", "not", "...
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/urllib3/packages/six.py#L812-L825
facebookresearch/pyrobot
27ffd64bbb7ce3ff6ec4b2122d84b438d5641d0f
examples/locobot/manipulation/moveit_planning.py
python
main
()
[]
def main(): target_joints = [[0.408, 0.721, -0.471, -1.4, 0.920], [-0.675, 0, 0.23, 1, -0.70]] config = dict(moveit_planner="ESTkConfigDefault") bot = Robot("locobot", arm_config=config) bot.arm.go_home() for joint in target_joints: bot.arm.set_joint_positions(joint, plan=True) bot.arm.go_home()
[ "def", "main", "(", ")", ":", "target_joints", "=", "[", "[", "0.408", ",", "0.721", ",", "-", "0.471", ",", "-", "1.4", ",", "0.920", "]", ",", "[", "-", "0.675", ",", "0", ",", "0.23", ",", "1", ",", "-", "0.70", "]", "]", "config", "=", ...
https://github.com/facebookresearch/pyrobot/blob/27ffd64bbb7ce3ff6ec4b2122d84b438d5641d0f/examples/locobot/manipulation/moveit_planning.py#L13-L24
google/brain-tokyo-workshop
faf12f6bbae773fbe535c7a6cf357dc662c6c1d8
WANNRelease/WANNTool/train.py
python
mpi_fork
(n)
Re-launches the current script with workers Returns "parent" for original parent, "child" for MPI children (from https://github.com/garymcintire/mpi_util/)
Re-launches the current script with workers Returns "parent" for original parent, "child" for MPI children (from https://github.com/garymcintire/mpi_util/)
[ "Re", "-", "launches", "the", "current", "script", "with", "workers", "Returns", "parent", "for", "original", "parent", "child", "for", "MPI", "children", "(", "from", "https", ":", "//", "github", ".", "com", "/", "garymcintire", "/", "mpi_util", "/", ")"...
def mpi_fork(n): """Re-launches the current script with workers Returns "parent" for original parent, "child" for MPI children (from https://github.com/garymcintire/mpi_util/) """ if n<=1: return "child" if os.getenv("IN_MPI") is None: env = os.environ.copy() env.update( MKL_NUM_THREADS="1", OMP_NUM_THREADS="1", IN_MPI="1" ) print( ["mpirun", "-np", str(n), sys.executable] + sys.argv) subprocess.check_call(["mpirun", "-np", str(n), sys.executable] +['-u']+ sys.argv, env=env) return "parent" else: global nworkers, rank nworkers = comm.Get_size() rank = comm.Get_rank() print('assigning the rank and nworkers', nworkers, rank) return "child"
[ "def", "mpi_fork", "(", "n", ")", ":", "if", "n", "<=", "1", ":", "return", "\"child\"", "if", "os", ".", "getenv", "(", "\"IN_MPI\"", ")", "is", "None", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "env", ".", "update", "(", "...
https://github.com/google/brain-tokyo-workshop/blob/faf12f6bbae773fbe535c7a6cf357dc662c6c1d8/WANNRelease/WANNTool/train.py#L401-L423
PaddlePaddle/PGL
e48545f2814523c777b8a9a9188bf5a7f00d6e52
apps/Graph4KG/dataset/trigraph.py
python
TriGraph.num_rels
(self)
return self._num_rels
Number of relations.
Number of relations.
[ "Number", "of", "relations", "." ]
def num_rels(self): """Number of relations. """ return self._num_rels
[ "def", "num_rels", "(", "self", ")", ":", "return", "self", ".", "_num_rels" ]
https://github.com/PaddlePaddle/PGL/blob/e48545f2814523c777b8a9a9188bf5a7f00d6e52/apps/Graph4KG/dataset/trigraph.py#L262-L265
blackye/lalascan
e35726e6648525eb47493e39ee63a2a906dbb4b2
lalascan/data/http.py
python
HTTP_Response.protocol
(self)
return self.__protocol
:returns: Protocol name. :rtype: str | None
:returns: Protocol name. :rtype: str | None
[ ":", "returns", ":", "Protocol", "name", ".", ":", "rtype", ":", "str", "|", "None" ]
def protocol(self): """ :returns: Protocol name. :rtype: str | None """ return self.__protocol
[ "def", "protocol", "(", "self", ")", ":", "return", "self", ".", "__protocol" ]
https://github.com/blackye/lalascan/blob/e35726e6648525eb47493e39ee63a2a906dbb4b2/lalascan/data/http.py#L888-L893
MalloyDelacroix/DownloaderForReddit
e2547a6d1f119b31642445e64cb21f4568ce4012
DownloaderForReddit/core/runner.py
python
verify_run
(method)
return check
Decorator method that verifies that the containing class's continue_run variable is set to True before calling the supplied method. :param method: The method that should be called if the run condition is met.
Decorator method that verifies that the containing class's continue_run variable is set to True before calling the supplied method. :param method: The method that should be called if the run condition is met.
[ "Decorator", "method", "that", "verifies", "that", "the", "containing", "class", "s", "continue_run", "variable", "is", "set", "to", "True", "before", "calling", "the", "supplied", "method", ".", ":", "param", "method", ":", "The", "method", "that", "should", ...
def verify_run(method): """ Decorator method that verifies that the containing class's continue_run variable is set to True before calling the supplied method. :param method: The method that should be called if the run condition is met. """ def check(instance, *args, **kwargs): if instance.continue_run: return method(instance, *args, **kwargs) return check
[ "def", "verify_run", "(", "method", ")", ":", "def", "check", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "instance", ".", "continue_run", ":", "return", "method", "(", "instance", ",", "*", "args", ",", "*", "*", "k...
https://github.com/MalloyDelacroix/DownloaderForReddit/blob/e2547a6d1f119b31642445e64cb21f4568ce4012/DownloaderForReddit/core/runner.py#L4-L14
ros/ros_comm
52b0556dadf3ec0c0bc72df4fc202153a53b539e
utilities/roswtf/src/roswtf/network.py
python
ros_ip_check
(ctx)
Make sure that ROS_IP is a local IP address
Make sure that ROS_IP is a local IP address
[ "Make", "sure", "that", "ROS_IP", "is", "a", "local", "IP", "address" ]
def ros_ip_check(ctx): """Make sure that ROS_IP is a local IP address""" if not rosgraph.ROS_IP in ctx.env: return ip = ctx.env[rosgraph.ROS_IP] # best we can do is compare roslib's routine against socket resolution and make sure they agree addrs = rosgraph.network.get_local_addresses() if " " in ip: return "ROS_IP [%s] contains whitespace. This is not a valid IP."%ip if ip not in addrs: return "ROS_IP [%s] does not appear to be an IP address of a local network interface (one of %s)."%(ip, str(addrs))
[ "def", "ros_ip_check", "(", "ctx", ")", ":", "if", "not", "rosgraph", ".", "ROS_IP", "in", "ctx", ".", "env", ":", "return", "ip", "=", "ctx", ".", "env", "[", "rosgraph", ".", "ROS_IP", "]", "# best we can do is compare roslib's routine against socket resolutio...
https://github.com/ros/ros_comm/blob/52b0556dadf3ec0c0bc72df4fc202153a53b539e/utilities/roswtf/src/roswtf/network.py#L85-L99
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas_rhino/conversions/vector.py
python
RhinoVector.geometry
(self, geometry)
Set the geometry of the wrapper. Parameters ---------- geometry : :rhino:`Rhino_Geometry_Vector3d` or :class:`compas.geometry.Vector` or list of float The input geometry. Raises ------ :class:`ConversionError` If the geometry cannot be converted to a vector.
Set the geometry of the wrapper.
[ "Set", "the", "geometry", "of", "the", "wrapper", "." ]
def geometry(self, geometry): """Set the geometry of the wrapper. Parameters ---------- geometry : :rhino:`Rhino_Geometry_Vector3d` or :class:`compas.geometry.Vector` or list of float The input geometry. Raises ------ :class:`ConversionError` If the geometry cannot be converted to a vector. """ if not isinstance(geometry, Rhino.Geometry.Vector3d): geometry = vector_to_rhino(geometry) self._geometry = geometry
[ "def", "geometry", "(", "self", ",", "geometry", ")", ":", "if", "not", "isinstance", "(", "geometry", ",", "Rhino", ".", "Geometry", ".", "Vector3d", ")", ":", "geometry", "=", "vector_to_rhino", "(", "geometry", ")", "self", ".", "_geometry", "=", "geo...
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas_rhino/conversions/vector.py#L21-L36
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/pkg_resources/__init__.py
python
Environment.__iadd__
(self, other)
return self
In-place addition of a distribution or environment
In-place addition of a distribution or environment
[ "In", "-", "place", "addition", "of", "a", "distribution", "or", "environment" ]
def __iadd__(self, other): """In-place addition of a distribution or environment""" if isinstance(other, Distribution): self.add(other) elif isinstance(other, Environment): for project in other: for dist in other[project]: self.add(dist) else: raise TypeError("Can't add %r to environment" % (other,)) return self
[ "def", "__iadd__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Distribution", ")", ":", "self", ".", "add", "(", "other", ")", "elif", "isinstance", "(", "other", ",", "Environment", ")", ":", "for", "project", "in", ...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/pkg_resources/__init__.py#L1083-L1093
coreemu/core
7e18a7a72023a69a92ad61d87461bd659ba27f7c
daemon/core/services/coreservices.py
python
ServiceShim.tovaluelist
(cls, node: CoreNode, service: "CoreService")
return "|".join(vals)
Convert service properties into a string list of key=value pairs, separated by "|". :param node: node to get value list for :param service: service to get value list for :return: value list string
Convert service properties into a string list of key=value pairs, separated by "|".
[ "Convert", "service", "properties", "into", "a", "string", "list", "of", "key", "=", "value", "pairs", "separated", "by", "|", "." ]
def tovaluelist(cls, node: CoreNode, service: "CoreService") -> str: """ Convert service properties into a string list of key=value pairs, separated by "|". :param node: node to get value list for :param service: service to get value list for :return: value list string """ start_time = 0 start_index = 0 valmap = [ service.dirs, service.configs, start_index, service.startup, service.shutdown, service.validate, service.meta, start_time, ] if not service.custom: valmap[1] = service.get_configs(node) valmap[3] = service.get_startup(node) vals = ["%s=%s" % (x, y) for x, y in zip(cls.keys, valmap)] return "|".join(vals)
[ "def", "tovaluelist", "(", "cls", ",", "node", ":", "CoreNode", ",", "service", ":", "\"CoreService\"", ")", "->", "str", ":", "start_time", "=", "0", "start_index", "=", "0", "valmap", "=", "[", "service", ".", "dirs", ",", "service", ".", "configs", ...
https://github.com/coreemu/core/blob/7e18a7a72023a69a92ad61d87461bd659ba27f7c/daemon/core/services/coreservices.py#L120-L145
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/mail/interfaces.py
python
IAccountIMAP.subscribe
(name)
Subscribe to a mailbox @type name: L{bytes} @param name: The name of the mailbox to subscribe to @rtype: L{Deferred} or L{bool} @return: A true value if the mailbox is subscribed to successfully, or a Deferred whose callback will be invoked with this value when the subscription is successful. @raise MailboxException: Raised if this mailbox cannot be subscribed to. This may also be raised asynchronously, if a L{Deferred} is returned.
Subscribe to a mailbox
[ "Subscribe", "to", "a", "mailbox" ]
def subscribe(name): """ Subscribe to a mailbox @type name: L{bytes} @param name: The name of the mailbox to subscribe to @rtype: L{Deferred} or L{bool} @return: A true value if the mailbox is subscribed to successfully, or a Deferred whose callback will be invoked with this value when the subscription is successful. @raise MailboxException: Raised if this mailbox cannot be subscribed to. This may also be raised asynchronously, if a L{Deferred} is returned. """
[ "def", "subscribe", "(", "name", ")", ":" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/mail/interfaces.py#L930-L945
brosner/everyblock_code
25397148223dad81e7fbb9c7cf2f169162df4681
ebgeo/ebgeo/maps/mapserver.py
python
MapServer.create_layer
(self, layer_name, style_name, postgis_table)
return layer
Convenience shortcut method for setting up a new layer with a defined style and PostGIS table name.
Convenience shortcut method for setting up a new layer with a defined style and PostGIS table name.
[ "Convenience", "shortcut", "method", "for", "setting", "up", "a", "new", "layer", "with", "a", "defined", "style", "and", "PostGIS", "table", "name", "." ]
def create_layer(self, layer_name, style_name, postgis_table): """ Convenience shortcut method for setting up a new layer with a defined style and PostGIS table name. """ layer = Layer(layer_name) layer.datasource = PostGIS(host=settings.MAPS_POSTGIS_HOST, user=settings.MAPS_POSTGIS_USER, password=settings.MAPS_POSTGIS_PASS, dbname=settings.MAPS_POSTGIS_DB, table=postgis_table) layer.styles.append(style_name) return layer
[ "def", "create_layer", "(", "self", ",", "layer_name", ",", "style_name", ",", "postgis_table", ")", ":", "layer", "=", "Layer", "(", "layer_name", ")", "layer", ".", "datasource", "=", "PostGIS", "(", "host", "=", "settings", ".", "MAPS_POSTGIS_HOST", ",", ...
https://github.com/brosner/everyblock_code/blob/25397148223dad81e7fbb9c7cf2f169162df4681/ebgeo/ebgeo/maps/mapserver.py#L73-L81
mcedit/mcedit2
4bb98da521447b6cf43d923cea9f00acf2f427e9
src/mceditlib/anvil/adapter.py
python
AnvilWorldAdapter.deleteChunk
(self, cx, cz, dimName)
Delete the chunk at the given position in the given dimension. :type cx: int :type cz: int :type dimName: str
Delete the chunk at the given position in the given dimension.
[ "Delete", "the", "chunk", "at", "the", "given", "position", "in", "the", "given", "dimension", "." ]
def deleteChunk(self, cx, cz, dimName): """ Delete the chunk at the given position in the given dimension. :type cx: int :type cz: int :type dimName: str """ self.selectedRevision.deleteChunk(cx, cz, dimName)
[ "def", "deleteChunk", "(", "self", ",", "cx", ",", "cz", ",", "dimName", ")", ":", "self", ".", "selectedRevision", ".", "deleteChunk", "(", "cx", ",", "cz", ",", "dimName", ")" ]
https://github.com/mcedit/mcedit2/blob/4bb98da521447b6cf43d923cea9f00acf2f427e9/src/mceditlib/anvil/adapter.py#L951-L959
PaddlePaddle/PARL
5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96
benchmark/torch/AlphaZero/connect4_game.py
python
Board._is_diagonal_winner
(self, player_pieces)
return False
Checks if player_pieces contains a diagonal win.
Checks if player_pieces contains a diagonal win.
[ "Checks", "if", "player_pieces", "contains", "a", "diagonal", "win", "." ]
def _is_diagonal_winner(self, player_pieces): """Checks if player_pieces contains a diagonal win.""" win_length = self.win_length for i in range(len(player_pieces) - win_length + 1): for j in range(len(player_pieces[0]) - win_length + 1): if all(player_pieces[i + x][j + x] for x in range(win_length)): return True for j in range(win_length - 1, len(player_pieces[0])): if all(player_pieces[i + x][j - x] for x in range(win_length)): return True return False
[ "def", "_is_diagonal_winner", "(", "self", ",", "player_pieces", ")", ":", "win_length", "=", "self", ".", "win_length", "for", "i", "in", "range", "(", "len", "(", "player_pieces", ")", "-", "win_length", "+", "1", ")", ":", "for", "j", "in", "range", ...
https://github.com/PaddlePaddle/PARL/blob/5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96/benchmark/torch/AlphaZero/connect4_game.py#L72-L82
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/SearchIO/_model/hit.py
python
Hit.sort
(self, key=None, reverse=False, in_place=True)
Sort the HSP objects. :param key: sorting function :type key: callable, accepts HSP, returns key for sorting :param reverse: whether to reverse sorting results or no :type reverse: bool :param in_place: whether to do in-place sorting or no :type in_place: bool ``sort`` defaults to sorting in-place, to mimic Python's ``list.sort`` method. If you set the ``in_place`` argument to False, it will treat return a new, sorted Hit object and keep the initial one unsorted
Sort the HSP objects.
[ "Sort", "the", "HSP", "objects", "." ]
def sort(self, key=None, reverse=False, in_place=True): """Sort the HSP objects. :param key: sorting function :type key: callable, accepts HSP, returns key for sorting :param reverse: whether to reverse sorting results or no :type reverse: bool :param in_place: whether to do in-place sorting or no :type in_place: bool ``sort`` defaults to sorting in-place, to mimic Python's ``list.sort`` method. If you set the ``in_place`` argument to False, it will treat return a new, sorted Hit object and keep the initial one unsorted """ if in_place: self._items.sort(key=key, reverse=reverse) else: hsps = self.hsps[:] hsps.sort(key=key, reverse=reverse) obj = self.__class__(hsps) self._transfer_attrs(obj) return obj
[ "def", "sort", "(", "self", ",", "key", "=", "None", ",", "reverse", "=", "False", ",", "in_place", "=", "True", ")", ":", "if", "in_place", ":", "self", ".", "_items", ".", "sort", "(", "key", "=", "key", ",", "reverse", "=", "reverse", ")", "el...
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/SearchIO/_model/hit.py#L434-L456
getsentry/raven-python
5b3f48c66269993a0202cfc988750e5fe66e0c00
raven/utils/stacks.py
python
iter_traceback_frames
(tb)
Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable.
Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable.
[ "Given", "a", "traceback", "object", "it", "will", "iterate", "over", "all", "frames", "that", "do", "not", "contain", "the", "__traceback_hide__", "local", "variable", "." ]
def iter_traceback_frames(tb): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ # Some versions of celery have hacked traceback objects that might # miss tb_frame. while tb and hasattr(tb, 'tb_frame'): # support for __traceback_hide__ which is used by a few libraries # to hide internal frames. f_locals = getattr(tb.tb_frame, 'f_locals', {}) if not _getitem_from_frame(f_locals, '__traceback_hide__'): yield tb.tb_frame, getattr(tb, 'tb_lineno', None) tb = tb.tb_next
[ "def", "iter_traceback_frames", "(", "tb", ")", ":", "# Some versions of celery have hacked traceback objects that might", "# miss tb_frame.", "while", "tb", "and", "hasattr", "(", "tb", ",", "'tb_frame'", ")", ":", "# support for __traceback_hide__ which is used by a few librari...
https://github.com/getsentry/raven-python/blob/5b3f48c66269993a0202cfc988750e5fe66e0c00/raven/utils/stacks.py#L111-L125
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/pathlib.py
python
Path.is_char_device
(self)
Whether this path is a character device.
Whether this path is a character device.
[ "Whether", "this", "path", "is", "a", "character", "device", "." ]
def is_char_device(self): """ Whether this path is a character device. """ try: return S_ISCHR(self.stat().st_mode) except OSError as e: if not _ignore_error(e): raise # Path doesn't exist or is a broken symlink # (see https://bitbucket.org/pitrou/pathlib/issue/12/) return False
[ "def", "is_char_device", "(", "self", ")", ":", "try", ":", "return", "S_ISCHR", "(", "self", ".", "stat", "(", ")", ".", "st_mode", ")", "except", "OSError", "as", "e", ":", "if", "not", "_ignore_error", "(", "e", ")", ":", "raise", "# Path doesn't ex...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/pathlib.py#L1426-L1437
tcgoetz/GarminDB
55796eb621df9f6ecd92f16b3a53393d23c0b4dc
garmindb/download.py
python
Download.get_monitoring
(self, directory_func, date, days)
Download the daily monitoring data from Garmin Connect, unzip and save the raw files.
Download the daily monitoring data from Garmin Connect, unzip and save the raw files.
[ "Download", "the", "daily", "monitoring", "data", "from", "Garmin", "Connect", "unzip", "and", "save", "the", "raw", "files", "." ]
def get_monitoring(self, directory_func, date, days): """Download the daily monitoring data from Garmin Connect, unzip and save the raw files.""" root_logger.info("Geting monitoring: %s (%d)", date, days) for day in tqdm(range(0, days + 1), unit='days'): day_date = date + datetime.timedelta(day) self.temp_dir = tempfile.mkdtemp() self.__get_monitoring_day(day_date) self.__unzip_files(directory_func(day_date.year)) # pause for a second between every page access time.sleep(1)
[ "def", "get_monitoring", "(", "self", ",", "directory_func", ",", "date", ",", "days", ")", ":", "root_logger", ".", "info", "(", "\"Geting monitoring: %s (%d)\"", ",", "date", ",", "days", ")", "for", "day", "in", "tqdm", "(", "range", "(", "0", ",", "d...
https://github.com/tcgoetz/GarminDB/blob/55796eb621df9f6ecd92f16b3a53393d23c0b4dc/garmindb/download.py#L222-L231
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/dist/git_install.py
python
do_step
(item)
Do this step in the process, regardless of whether it has been done or not. If it completes without failure, mark it done.
Do this step in the process, regardless of whether it has been done or not. If it completes without failure, mark it done.
[ "Do", "this", "step", "in", "the", "process", "regardless", "of", "whether", "it", "has", "been", "done", "or", "not", ".", "If", "it", "completes", "without", "failure", "mark", "it", "done", "." ]
def do_step(item): """ Do this step in the process, regardless of whether it has been done or not. If it completes without failure, mark it done. """ val = data[item] print('') print("{}: {}".format(item,val[1])) print(val[0]) exec(val[0]) print('') data[item] = (val[0],val[1],True)
[ "def", "do_step", "(", "item", ")", ":", "val", "=", "data", "[", "item", "]", "print", "(", "''", ")", "print", "(", "\"{}: {}\"", ".", "format", "(", "item", ",", "val", "[", "1", "]", ")", ")", "print", "(", "val", "[", "0", "]", ")", "exe...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/dist/git_install.py#L321-L332
wrye-bash/wrye-bash
d495c47cfdb44475befa523438a40c4419cb386f
Mopy/bash/bosh/bsa_files.py
python
OblivionBsa.undo_alterations
(self, progress=Progress())
return reset_count
Undoes any alterations that previously applied BSA Alteration may have done to this BSA by recalculating all mismatched hashes. NOTE: In order for this method to do anything, the BSA must be fully loaded - that means you must either pass load_cache=True and names_only=False to the constructor, or call _load_bsa() (NOT _load_bsa_light() !) before calling this method. See this link for an in-depth overview of BSA Alteration and the problem it tries to solve: http://devnull.sweetdanger.com/archiveinvalidation.html :param progress: The progress indicator to use for this process.
Undoes any alterations that previously applied BSA Alteration may have done to this BSA by recalculating all mismatched hashes.
[ "Undoes", "any", "alterations", "that", "previously", "applied", "BSA", "Alteration", "may", "have", "done", "to", "this", "BSA", "by", "recalculating", "all", "mismatched", "hashes", "." ]
def undo_alterations(self, progress=Progress()): """Undoes any alterations that previously applied BSA Alteration may have done to this BSA by recalculating all mismatched hashes. NOTE: In order for this method to do anything, the BSA must be fully loaded - that means you must either pass load_cache=True and names_only=False to the constructor, or call _load_bsa() (NOT _load_bsa_light() !) before calling this method. See this link for an in-depth overview of BSA Alteration and the problem it tries to solve: http://devnull.sweetdanger.com/archiveinvalidation.html :param progress: The progress indicator to use for this process.""" progress.setFull(self.bsa_header.folder_count) with open(self.abs_path.s, u'r+b') as bsa_file: reset_count = 0 for folder_name, folder in self.bsa_folders.items(): for file_name, file_info in folder.folder_assets.items(): rebuilt_hash = self.calculate_hash(file_name) if file_info.record_hash != rebuilt_hash: bsa_file.seek(file_info.file_pos) bsa_file.write( structs_cache[_HashedRecord.formats[0][0]].pack( rebuilt_hash)) reset_count += 1 progress(progress.state + 1, u'Rebuilding Hashes...\n' + folder_name) return reset_count
[ "def", "undo_alterations", "(", "self", ",", "progress", "=", "Progress", "(", ")", ")", ":", "progress", ".", "setFull", "(", "self", ".", "bsa_header", ".", "folder_count", ")", "with", "open", "(", "self", ".", "abs_path", ".", "s", ",", "u'r+b'", "...
https://github.com/wrye-bash/wrye-bash/blob/d495c47cfdb44475befa523438a40c4419cb386f/Mopy/bash/bosh/bsa_files.py#L960-L988
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/codec/base.py
python
Segment.list_files
(self, storage)
return [name for name in storage.list() if name.startswith(prefix)]
[]
def list_files(self, storage): prefix = "%s." % self.segment_id() return [name for name in storage.list() if name.startswith(prefix)]
[ "def", "list_files", "(", "self", ",", "storage", ")", ":", "prefix", "=", "\"%s.\"", "%", "self", ".", "segment_id", "(", ")", "return", "[", "name", "for", "name", "in", "storage", ".", "list", "(", ")", "if", "name", ".", "startswith", "(", "prefi...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/codec/base.py#L536-L538
DylanWusee/pointconv
f39dc3e101af2f52544181ee20c14f73279b48ae
scannet/pc_util.py
python
point_cloud_to_volume_batch
(point_clouds, vsize=12, radius=1.0, flatten=True)
Input is BxNx3 batch of point cloud Output is Bx(vsize^3)
Input is BxNx3 batch of point cloud Output is Bx(vsize^3)
[ "Input", "is", "BxNx3", "batch", "of", "point", "cloud", "Output", "is", "Bx", "(", "vsize^3", ")" ]
def point_cloud_to_volume_batch(point_clouds, vsize=12, radius=1.0, flatten=True): """ Input is BxNx3 batch of point cloud Output is Bx(vsize^3) """ vol_list = [] for b in range(point_clouds.shape[0]): vol = point_cloud_to_volume(np.squeeze(point_clouds[b,:,:]), vsize, radius) if flatten: vol_list.append(vol.flatten()) else: vol_list.append(np.expand_dims(np.expand_dims(vol, -1), 0)) if flatten: return np.vstack(vol_list) else: return np.concatenate(vol_list, 0)
[ "def", "point_cloud_to_volume_batch", "(", "point_clouds", ",", "vsize", "=", "12", ",", "radius", "=", "1.0", ",", "flatten", "=", "True", ")", ":", "vol_list", "=", "[", "]", "for", "b", "in", "range", "(", "point_clouds", ".", "shape", "[", "0", "]"...
https://github.com/DylanWusee/pointconv/blob/f39dc3e101af2f52544181ee20c14f73279b48ae/scannet/pc_util.py#L53-L67
santi-pdp/segan_pytorch
052238718b037cd72c7fa69bc1577782e5ef015d
segan/models/spectral_norm.py
python
l2normalize
(v, eps=1e-12)
return v / (v.norm() + eps)
[]
def l2normalize(v, eps=1e-12): return v / (v.norm() + eps)
[ "def", "l2normalize", "(", "v", ",", "eps", "=", "1e-12", ")", ":", "return", "v", "/", "(", "v", ".", "norm", "(", ")", "+", "eps", ")" ]
https://github.com/santi-pdp/segan_pytorch/blob/052238718b037cd72c7fa69bc1577782e5ef015d/segan/models/spectral_norm.py#L10-L11
google-research/fixmatch
d4985a158065947dba803e626ee9a6721709c570
imagenet/augment/ct_augment.py
python
CTAugment._sample_ops
(self, local_log_prob)
return op_indices, op_args
Samples sequence of augmentation ops using current probabilities.
Samples sequence of augmentation ops using current probabilities.
[ "Samples", "sequence", "of", "augmentation", "ops", "using", "current", "probabilities", "." ]
def _sample_ops(self, local_log_prob): """Samples sequence of augmentation ops using current probabilities.""" # choose operations op_indices = tf.random.uniform( shape=[self.num_layers], maxval=len(IMAGENET_AUG_OPS), dtype=tf.int32) # sample arguments for each selected operation selected_ops_log_probs = tf.gather(local_log_prob, op_indices, axis=0) op_args = tf.random.categorical(selected_ops_log_probs, num_samples=1) op_args = tf.cast(tf.squeeze(op_args, axis=1), tf.float32) op_args = (op_args + tf.random.uniform([self.num_layers])) / self.num_levels return op_indices, op_args
[ "def", "_sample_ops", "(", "self", ",", "local_log_prob", ")", ":", "# choose operations", "op_indices", "=", "tf", ".", "random", ".", "uniform", "(", "shape", "=", "[", "self", ".", "num_layers", "]", ",", "maxval", "=", "len", "(", "IMAGENET_AUG_OPS", "...
https://github.com/google-research/fixmatch/blob/d4985a158065947dba803e626ee9a6721709c570/imagenet/augment/ct_augment.py#L263-L273
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/site-packages/django/contrib/gis/geos/polygon.py
python
Polygon._get_ext_ring
(self)
return self[0]
Gets the exterior ring of the Polygon.
Gets the exterior ring of the Polygon.
[ "Gets", "the", "exterior", "ring", "of", "the", "Polygon", "." ]
def _get_ext_ring(self): "Gets the exterior ring of the Polygon." return self[0]
[ "def", "_get_ext_ring", "(", "self", ")", ":", "return", "self", "[", "0", "]" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/contrib/gis/geos/polygon.py#L142-L144
google/loaner
24f9a9e70434e430f1beb4ead87e3675f4b53676
loaner/web_app/backend/lib/search_utils.py
python
document_to_message
(document, message)
return message
Builds a search document into an ProtoRPC message. Args: document: search.ScoredDocument, A document from a search result. message: messages.Message, a ProtoRPC.messages message to build. Returns: A constructed ProtoRPC message.
Builds a search document into an ProtoRPC message.
[ "Builds", "a", "search", "document", "into", "an", "ProtoRPC", "message", "." ]
def document_to_message(document, message): """Builds a search document into an ProtoRPC message. Args: document: search.ScoredDocument, A document from a search result. message: messages.Message, a ProtoRPC.messages message to build. Returns: A constructed ProtoRPC message. """ for field in document.fields: if field.name == 'assignment_date': setattr( message, 'max_extend_date', device_model.calculate_return_dates(field.value).max) try: setattr(message, field.name, field.value) except messages.ValidationError: if field.value == 'True': setattr(message, field.name, True) elif field.value == 'False': setattr(message, field.name, False) elif isinstance(field.value, float): setattr(message, field.name, int(field.value)) except AttributeError: if field.name == 'lat_long': setattr(message, 'latitude', field.value.latitude) setattr(message, 'longitude', field.value.longitude) else: logging.error('Unable to map %s to any attribute.', field.name) return message
[ "def", "document_to_message", "(", "document", ",", "message", ")", ":", "for", "field", "in", "document", ".", "fields", ":", "if", "field", ".", "name", "==", "'assignment_date'", ":", "setattr", "(", "message", ",", "'max_extend_date'", ",", "device_model",...
https://github.com/google/loaner/blob/24f9a9e70434e430f1beb4ead87e3675f4b53676/loaner/web_app/backend/lib/search_utils.py#L58-L89
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/scattersmith/marker/_line.py
python
Line.color
(self)
return self["color"]
Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A number that will be interpreted as a color according to scattersmith.marker.line.colorscale - A list or array of any of the above Returns ------- str|numpy.ndarray
Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A number that will be interpreted as a color according to scattersmith.marker.line.colorscale - A list or array of any of the above
[ "Sets", "themarker", ".", "linecolor", ".", "It", "accepts", "either", "a", "specific", "color", "or", "an", "array", "of", "numbers", "that", "are", "mapped", "to", "the", "colorscale", "relative", "to", "the", "max", "and", "min", "values", "of", "the", ...
def color(self): """ Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A number that will be interpreted as a color according to scattersmith.marker.line.colorscale - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"]
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/scattersmith/marker/_line.py#L151-L207
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/content/instrument.py
python
Instrument.getLatestValidCalibration
(self)
return None
Returns the calibration with the most remaining days in calibration. If no calibration was found, it returns None.
Returns the calibration with the most remaining days in calibration. If no calibration was found, it returns None.
[ "Returns", "the", "calibration", "with", "the", "most", "remaining", "days", "in", "calibration", ".", "If", "no", "calibration", "was", "found", "it", "returns", "None", "." ]
def getLatestValidCalibration(self): """Returns the calibration with the most remaining days in calibration. If no calibration was found, it returns None. """ # 1. get all calibrations calibrations = self.getCalibrations() # 2. filter out calibrations, which are not in progress active_calibrations = filter(lambda x: x.isCalibrationInProgress(), calibrations) # 3. sort by the remaining days in calibration, e.g. [10, 7, 6, 1] def sort_func(x, y): return cmp(x.getRemainingDaysInCalibration(), y.getRemainingDaysInCalibration()) sorted_calibrations = sorted(active_calibrations, cmp=sort_func, reverse=True) # 4. return the calibration with the most remaining days if len(sorted_calibrations) > 0: return sorted_calibrations[0] return None
[ "def", "getLatestValidCalibration", "(", "self", ")", ":", "# 1. get all calibrations", "calibrations", "=", "self", ".", "getCalibrations", "(", ")", "# 2. filter out calibrations, which are not in progress", "active_calibrations", "=", "filter", "(", "lambda", "x", ":", ...
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/content/instrument.py#L646-L664
gaasedelen/lighthouse
7245a2d2c4e84351cd259ed81dafa4263167909a
plugins/lighthouse/util/disassembler/api.py
python
DisassemblerCoreAPI.version_major
(self)
return self._version_major
Return the major version number of the disassembler framework.
Return the major version number of the disassembler framework.
[ "Return", "the", "major", "version", "number", "of", "the", "disassembler", "framework", "." ]
def version_major(self): """ Return the major version number of the disassembler framework. """ assert self._version_major != NotImplemented return self._version_major
[ "def", "version_major", "(", "self", ")", ":", "assert", "self", ".", "_version_major", "!=", "NotImplemented", "return", "self", ".", "_version_major" ]
https://github.com/gaasedelen/lighthouse/blob/7245a2d2c4e84351cd259ed81dafa4263167909a/plugins/lighthouse/util/disassembler/api.py#L60-L65
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/transformations/advanced_transformations.py
python
SuperTransformation.__init__
(self, transformations, nstructures_per_trans=1)
Args: transformations ([transformations]): List of transformations to apply to a structure. One transformation is applied to each output structure. nstructures_per_trans (int): If the transformations are one-to-many and, nstructures_per_trans structures from each transformation are added to the full list. Defaults to 1, i.e., only best structure.
Args: transformations ([transformations]): List of transformations to apply to a structure. One transformation is applied to each output structure. nstructures_per_trans (int): If the transformations are one-to-many and, nstructures_per_trans structures from each transformation are added to the full list. Defaults to 1, i.e., only best structure.
[ "Args", ":", "transformations", "(", "[", "transformations", "]", ")", ":", "List", "of", "transformations", "to", "apply", "to", "a", "structure", ".", "One", "transformation", "is", "applied", "to", "each", "output", "structure", ".", "nstructures_per_trans", ...
def __init__(self, transformations, nstructures_per_trans=1): """ Args: transformations ([transformations]): List of transformations to apply to a structure. One transformation is applied to each output structure. nstructures_per_trans (int): If the transformations are one-to-many and, nstructures_per_trans structures from each transformation are added to the full list. Defaults to 1, i.e., only best structure. """ self._transformations = transformations self.nstructures_per_trans = nstructures_per_trans
[ "def", "__init__", "(", "self", ",", "transformations", ",", "nstructures_per_trans", "=", "1", ")", ":", "self", ".", "_transformations", "=", "transformations", "self", ".", "nstructures_per_trans", "=", "nstructures_per_trans" ]
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/transformations/advanced_transformations.py#L115-L127
uqfoundation/multiprocess
028cc73f02655e6451d92e5147d19d8c10aebe50
py3.9/multiprocess/context.py
python
BaseContext.RawArray
(self, typecode_or_type, size_or_initializer)
return RawArray(typecode_or_type, size_or_initializer)
Returns a shared array
Returns a shared array
[ "Returns", "a", "shared", "array" ]
def RawArray(self, typecode_or_type, size_or_initializer): '''Returns a shared array''' from .sharedctypes import RawArray return RawArray(typecode_or_type, size_or_initializer)
[ "def", "RawArray", "(", "self", ",", "typecode_or_type", ",", "size_or_initializer", ")", ":", "from", ".", "sharedctypes", "import", "RawArray", "return", "RawArray", "(", "typecode_or_type", ",", "size_or_initializer", ")" ]
https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.9/multiprocess/context.py#L127-L130
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/keyframeeditcanvas.py
python
AbstractEditCanvas._shape_press_event
(self)
[]
def _shape_press_event(self): print("_shape_press_event not impl")
[ "def", "_shape_press_event", "(", "self", ")", ":", "print", "(", "\"_shape_press_event not impl\"", ")" ]
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/keyframeeditcanvas.py#L439-L440
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/commtrack/sms.py
python
send_confirmation
(v, data)
[]
def send_confirmation(v, data): C = CommtrackConfig.for_domain(v.domain) static_loc = data['location'] location_name = static_loc.name metadata = MessageMetadata(location_id=static_loc.get_id) tx_by_action = map_reduce(lambda tx: [(tx.action_config(C).name,)], data=data['transactions'], include_docs=True) def summarize_action(action, txs): return '%s %s' % (txs[0].action_config(C).keyword.upper(), ' '.join(sorted(tx.fragment() for tx in txs))) msg = 'received stock report for %s(%s) %s' % ( static_loc.site_code, truncate(location_name, 20), ' '.join(sorted(summarize_action(a, txs) for a, txs in tx_by_action.items())) ) send_sms_to_verified_number(v, msg, metadata=metadata)
[ "def", "send_confirmation", "(", "v", ",", "data", ")", ":", "C", "=", "CommtrackConfig", ".", "for_domain", "(", "v", ".", "domain", ")", "static_loc", "=", "data", "[", "'location'", "]", "location_name", "=", "static_loc", ".", "name", "metadata", "=", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/commtrack/sms.py#L361-L378
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/Commit.py
python
Commit.parents
(self)
return self._parents.value
:type: list of :class:`github.Commit.Commit`
:type: list of :class:`github.Commit.Commit`
[ ":", "type", ":", "list", "of", ":", "class", ":", "github", ".", "Commit", ".", "Commit" ]
def parents(self): """ :type: list of :class:`github.Commit.Commit` """ self._completeIfNotSet(self._parents) return self._parents.value
[ "def", "parents", "(", "self", ")", ":", "self", ".", "_completeIfNotSet", "(", "self", ".", "_parents", ")", "return", "self", ".", "_parents", ".", "value" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/Commit.py#L107-L112
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/compute/drivers/ec2.py
python
BaseEC2NodeDriver._to_addresses
(self, response, only_associated)
return addresses
Builds a list of dictionaries containing elastic IP properties. :param only_associated: If true, return only those addresses that are associated with an instance. If false, return all addresses. :type only_associated: ``bool`` :rtype: ``list`` of :class:`ElasticIP`
Builds a list of dictionaries containing elastic IP properties.
[ "Builds", "a", "list", "of", "dictionaries", "containing", "elastic", "IP", "properties", "." ]
def _to_addresses(self, response, only_associated): """ Builds a list of dictionaries containing elastic IP properties. :param only_associated: If true, return only those addresses that are associated with an instance. If false, return all addresses. :type only_associated: ``bool`` :rtype: ``list`` of :class:`ElasticIP` """ addresses = [] for el in response.findall( fixxpath(xpath="addressesSet/item", namespace=NAMESPACE) ): addr = self._to_address(el, only_associated) if addr is not None: addresses.append(addr) return addresses
[ "def", "_to_addresses", "(", "self", ",", "response", ",", "only_associated", ")", ":", "addresses", "=", "[", "]", "for", "el", "in", "response", ".", "findall", "(", "fixxpath", "(", "xpath", "=", "\"addressesSet/item\"", ",", "namespace", "=", "NAMESPACE"...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/ec2.py#L4759-L4778
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/openid/consumer/consumer.py
python
GenericConsumer._checkSetupNeeded
(self, message)
Check an id_res message to see if it is a checkid_immediate cancel response. @raises SetupNeededError: if it is a checkid_immediate cancellation
Check an id_res message to see if it is a checkid_immediate cancel response.
[ "Check", "an", "id_res", "message", "to", "see", "if", "it", "is", "a", "checkid_immediate", "cancel", "response", "." ]
def _checkSetupNeeded(self, message): """Check an id_res message to see if it is a checkid_immediate cancel response. @raises SetupNeededError: if it is a checkid_immediate cancellation """ # In OpenID 1, we check to see if this is a cancel from # immediate mode by the presence of the user_setup_url # parameter. if message.isOpenID1(): user_setup_url = message.getArg(OPENID1_NS, 'user_setup_url') if user_setup_url is not None: raise SetupNeededError(user_setup_url)
[ "def", "_checkSetupNeeded", "(", "self", ",", "message", ")", ":", "# In OpenID 1, we check to see if this is a cancel from", "# immediate mode by the presence of the user_setup_url", "# parameter.", "if", "message", ".", "isOpenID1", "(", ")", ":", "user_setup_url", "=", "me...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/openid/consumer/consumer.py#L686-L698
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/versioned_parameter.py
python
VersionedParameter.value
(self)
return self._value
Gets the value of this VersionedParameter. The value of the parameter :return: The value of this VersionedParameter. :rtype: str
Gets the value of this VersionedParameter. The value of the parameter
[ "Gets", "the", "value", "of", "this", "VersionedParameter", ".", "The", "value", "of", "the", "parameter" ]
def value(self): """ Gets the value of this VersionedParameter. The value of the parameter :return: The value of this VersionedParameter. :rtype: str """ return self._value
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "_value" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/versioned_parameter.py#L136-L144
aws/serverless-application-model
ab6943a340a3f489af62b8c70c1366242b2887fe
samtranslator/utils/py27hash_fix.py
python
_template_has_httpapi_resource_with_default_authorizer
(template)
return False
Returns true if the template contains at least one AWS::Serverless::HttpApi resource with DefaultAuthorizer configured
Returns true if the template contains at least one AWS::Serverless::HttpApi resource with DefaultAuthorizer configured
[ "Returns", "true", "if", "the", "template", "contains", "at", "least", "one", "AWS", "::", "Serverless", "::", "HttpApi", "resource", "with", "DefaultAuthorizer", "configured" ]
def _template_has_httpapi_resource_with_default_authorizer(template): """ Returns true if the template contains at least one AWS::Serverless::HttpApi resource with DefaultAuthorizer configured """ # Check whether DefaultAuthorizer is defined in Globals.HttpApi has_global_httpapi_default_authorizer = False if "Globals" in template and isinstance(template["Globals"], dict): globals_dict = template["Globals"] if "HttpApi" in globals_dict and isinstance(globals_dict["HttpApi"], dict): globals_httpapi_dict = globals_dict["HttpApi"] if "Auth" in globals_httpapi_dict and isinstance(globals_httpapi_dict["Auth"], dict): has_global_httpapi_default_authorizer = bool(globals_httpapi_dict["Auth"].get("DefaultAuthorizer")) # Check if there is explicit HttpApi resource for resource_dict in template.get("Resources", {}).values(): if isinstance(resource_dict, dict) and resource_dict.get("Type") == "AWS::Serverless::HttpApi": auth = resource_dict.get("Properties", {}).get("Auth", {}) if ( auth and isinstance(auth, dict) and auth.get("DefaultAuthorizer") ) or has_global_httpapi_default_authorizer: return True # Check if there is any httpapi event for implicit api if has_global_httpapi_default_authorizer: for resource_dict in template.get("Resources", {}).values(): if isinstance(resource_dict, dict) and resource_dict.get("Type") == "AWS::Serverless::Function": events = resource_dict.get("Properties", {}).get("Events", {}) if isinstance(events, dict): for event_dict in events.values(): if event_dict and isinstance(event_dict, dict) and event_dict.get("Type") == "HttpApi": return True return False
[ "def", "_template_has_httpapi_resource_with_default_authorizer", "(", "template", ")", ":", "# Check whether DefaultAuthorizer is defined in Globals.HttpApi", "has_global_httpapi_default_authorizer", "=", "False", "if", "\"Globals\"", "in", "template", "and", "isinstance", "(", "te...
https://github.com/aws/serverless-application-model/blob/ab6943a340a3f489af62b8c70c1366242b2887fe/samtranslator/utils/py27hash_fix.py#L600-L632
pyjs/pyjs
6c4a3d3a67300cd5df7f95a67ca9dcdc06950523
examples/dynamictable/__main__.py
python
setup
(targets)
Setup example for translation, MUST call util.setup(targets).
Setup example for translation, MUST call util.setup(targets).
[ "Setup", "example", "for", "translation", "MUST", "call", "util", ".", "setup", "(", "targets", ")", "." ]
def setup(targets): '''Setup example for translation, MUST call util.setup(targets).''' util.setup(targets)
[ "def", "setup", "(", "targets", ")", ":", "util", ".", "setup", "(", "targets", ")" ]
https://github.com/pyjs/pyjs/blob/6c4a3d3a67300cd5df7f95a67ca9dcdc06950523/examples/dynamictable/__main__.py#L16-L18
williamSYSU/TextGAN-PyTorch
891635af6845edfee382de147faa4fc00c7e90eb
instructor/oracle_data/relgan_instructor.py
python
RelGANInstructor.pretrain_generator
(self, epochs)
Max Likelihood Pre-training for the generator
Max Likelihood Pre-training for the generator
[ "Max", "Likelihood", "Pre", "-", "training", "for", "the", "generator" ]
def pretrain_generator(self, epochs): """ Max Likelihood Pre-training for the generator """ for epoch in range(epochs): self.sig.update() if self.sig.pre_sig: # ===Train=== pre_loss = self.train_gen_epoch(self.gen, self.oracle_data.loader, self.mle_criterion, self.gen_opt) # ===Test=== if epoch % cfg.pre_log_step == 0 or epoch == epochs - 1: self.log.info( '[MLE-GEN] epoch %d : pre_loss = %.4f, %s' % (epoch, pre_loss, self.cal_metrics(fmt_str=True))) if cfg.if_save and not cfg.if_test: self._save('MLE', epoch) else: self.log.info('>>> Stop by pre signal, skip to adversarial training...') break
[ "def", "pretrain_generator", "(", "self", ",", "epochs", ")", ":", "for", "epoch", "in", "range", "(", "epochs", ")", ":", "self", ".", "sig", ".", "update", "(", ")", "if", "self", ".", "sig", ".", "pre_sig", ":", "# ===Train===", "pre_loss", "=", "...
https://github.com/williamSYSU/TextGAN-PyTorch/blob/891635af6845edfee382de147faa4fc00c7e90eb/instructor/oracle_data/relgan_instructor.py#L79-L98
JoelBender/bacpypes
41104c2b565b2ae9a637c941dfb0fe04195c5e96
py27/bacpypes/primitivedata.py
python
Time.now
(self, when=None)
return self
Set the current value to the correct tuple based on the seconds since the epoch. If 'when' is not provided, get the current time from the task manager.
Set the current value to the correct tuple based on the seconds since the epoch. If 'when' is not provided, get the current time from the task manager.
[ "Set", "the", "current", "value", "to", "the", "correct", "tuple", "based", "on", "the", "seconds", "since", "the", "epoch", ".", "If", "when", "is", "not", "provided", "get", "the", "current", "time", "from", "the", "task", "manager", "." ]
def now(self, when=None): """Set the current value to the correct tuple based on the seconds since the epoch. If 'when' is not provided, get the current time from the task manager. """ if when is None: when = _TaskManager().get_time() tup = time.localtime(when) self.value = (tup[3], tup[4], tup[5], int((when - int(when)) * 100)) return self
[ "def", "now", "(", "self", ",", "when", "=", "None", ")", ":", "if", "when", "is", "None", ":", "when", "=", "_TaskManager", "(", ")", ".", "get_time", "(", ")", "tup", "=", "time", ".", "localtime", "(", "when", ")", "self", ".", "value", "=", ...
https://github.com/JoelBender/bacpypes/blob/41104c2b565b2ae9a637c941dfb0fe04195c5e96/py27/bacpypes/primitivedata.py#L1588-L1599
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/sqlalchemy/orm/strategy_options.py
python
load_only
(loadopt, *attrs)
return cloned
Indicate that for a particular entity, only the given list of column-based attribute names should be loaded; all others will be deferred. This function is part of the :class:`.Load` interface and supports both method-chained and standalone operation. Example - given a class ``User``, load only the ``name`` and ``fullname`` attributes:: session.query(User).options(load_only("name", "fullname")) Example - given a relationship ``User.addresses -> Address``, specify subquery loading for the ``User.addresses`` collection, but on each ``Address`` object load only the ``email_address`` attribute:: session.query(User).options( subqueryload("addreses").load_only("email_address") ) For a :class:`.Query` that has multiple entities, the lead entity can be specifically referred to using the :class:`.Load` constructor:: session.query(User, Address).join(User.addresses).options( Load(User).load_only("name", "fullname"), Load(Address).load_only("email_addres") ) .. versionadded:: 0.9.0
Indicate that for a particular entity, only the given list of column-based attribute names should be loaded; all others will be deferred.
[ "Indicate", "that", "for", "a", "particular", "entity", "only", "the", "given", "list", "of", "column", "-", "based", "attribute", "names", "should", "be", "loaded", ";", "all", "others", "will", "be", "deferred", "." ]
def load_only(loadopt, *attrs): """Indicate that for a particular entity, only the given list of column-based attribute names should be loaded; all others will be deferred. This function is part of the :class:`.Load` interface and supports both method-chained and standalone operation. Example - given a class ``User``, load only the ``name`` and ``fullname`` attributes:: session.query(User).options(load_only("name", "fullname")) Example - given a relationship ``User.addresses -> Address``, specify subquery loading for the ``User.addresses`` collection, but on each ``Address`` object load only the ``email_address`` attribute:: session.query(User).options( subqueryload("addreses").load_only("email_address") ) For a :class:`.Query` that has multiple entities, the lead entity can be specifically referred to using the :class:`.Load` constructor:: session.query(User, Address).join(User.addresses).options( Load(User).load_only("name", "fullname"), Load(Address).load_only("email_addres") ) .. versionadded:: 0.9.0 """ cloned = loadopt.set_column_strategy( attrs, {"deferred": False, "instrument": True} ) cloned.set_column_strategy("*", {"deferred": True, "instrument": True}, {"undefer_pks": True}) return cloned
[ "def", "load_only", "(", "loadopt", ",", "*", "attrs", ")", ":", "cloned", "=", "loadopt", ".", "set_column_strategy", "(", "attrs", ",", "{", "\"deferred\"", ":", "False", ",", "\"instrument\"", ":", "True", "}", ")", "cloned", ".", "set_column_strategy", ...
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/sqlalchemy/orm/strategy_options.py#L561-L601
nextgenusfs/funannotate
f737bedfca5c5fd1e9a356bd400a4391926f76e4
funannotate/update.py
python
pairwiseAlign
(query, ref)
return pident
do global alignment and return pident
do global alignment and return pident
[ "do", "global", "alignment", "and", "return", "pident" ]
def pairwiseAlign(query, ref): from Bio import pairwise2 ''' do global alignment and return pident ''' if query == ref: return 100.0 align = pairwise2.align.globalxx(query, ref) length = max(len(query), len(ref)) pident = (align[0][2] / float(length)) * 100 return pident
[ "def", "pairwiseAlign", "(", "query", ",", "ref", ")", ":", "from", "Bio", "import", "pairwise2", "if", "query", "==", "ref", ":", "return", "100.0", "align", "=", "pairwise2", ".", "align", ".", "globalxx", "(", "query", ",", "ref", ")", "length", "="...
https://github.com/nextgenusfs/funannotate/blob/f737bedfca5c5fd1e9a356bd400a4391926f76e4/funannotate/update.py#L1328-L1338
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/expressions/matmul.py
python
only_squares
(*matrices)
return out
factor matrices only if they are square
factor matrices only if they are square
[ "factor", "matrices", "only", "if", "they", "are", "square" ]
def only_squares(*matrices): """ factor matrices only if they are square """ if matrices[0].rows != matrices[-1].cols: raise RuntimeError("Invalid matrices being multiplied") out = [] start = 0 for i, M in enumerate(matrices): if M.cols == matrices[start].rows: out.append(MatMul(*matrices[start:i+1]).doit()) start = i+1 return out
[ "def", "only_squares", "(", "*", "matrices", ")", ":", "if", "matrices", "[", "0", "]", ".", "rows", "!=", "matrices", "[", "-", "1", "]", ".", "cols", ":", "raise", "RuntimeError", "(", "\"Invalid matrices being multiplied\"", ")", "out", "=", "[", "]",...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/expressions/matmul.py#L226-L236
wummel/patool
723006abd43d0926581b11df0cd37e46a30525eb
patoolib/programs/star.py
python
list_tar
(archive, compression, cmd, verbosity, interactive)
return cmdlist
List a TAR archive.
List a TAR archive.
[ "List", "a", "TAR", "archive", "." ]
def list_tar (archive, compression, cmd, verbosity, interactive): """List a TAR archive.""" cmdlist = [cmd, '-n'] add_star_opts(cmdlist, compression, verbosity) cmdlist.append("file=%s" % archive) return cmdlist
[ "def", "list_tar", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ")", ":", "cmdlist", "=", "[", "cmd", ",", "'-n'", "]", "add_star_opts", "(", "cmdlist", ",", "compression", ",", "verbosity", ")", "cmdlist", ".", "...
https://github.com/wummel/patool/blob/723006abd43d0926581b11df0cd37e46a30525eb/patoolib/programs/star.py#L26-L31
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/SeqIO/SffIO.py
python
SffIterator.parse
(self, handle)
return records
Start parsing the file, and return a SeqRecord generator.
Start parsing the file, and return a SeqRecord generator.
[ "Start", "parsing", "the", "file", "and", "return", "a", "SeqRecord", "generator", "." ]
def parse(self, handle): """Start parsing the file, and return a SeqRecord generator.""" try: if 0 != handle.tell(): raise ValueError("Not at start of file, offset %i" % handle.tell()) except AttributeError: # Probably a network handle or something like that handle = _AddTellHandle(handle) records = self.iterate(handle) return records
[ "def", "parse", "(", "self", ",", "handle", ")", ":", "try", ":", "if", "0", "!=", "handle", ".", "tell", "(", ")", ":", "raise", "ValueError", "(", "\"Not at start of file, offset %i\"", "%", "handle", ".", "tell", "(", ")", ")", "except", "AttributeErr...
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/SeqIO/SffIO.py#L992-L1001
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/backend/backends.py
python
Backend.get_target_generated_dir
( self, target: T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex], gensrc: T.Union[build.CustomTarget, build.CustomTargetIndex, build.GeneratedList], src: str)
return os.path.join(self.get_target_private_dir(target), src)
Takes a BuildTarget, a generator source (CustomTarget or GeneratedList), and a generated source filename. Returns the full path of the generated source relative to the build root
Takes a BuildTarget, a generator source (CustomTarget or GeneratedList), and a generated source filename. Returns the full path of the generated source relative to the build root
[ "Takes", "a", "BuildTarget", "a", "generator", "source", "(", "CustomTarget", "or", "GeneratedList", ")", "and", "a", "generated", "source", "filename", ".", "Returns", "the", "full", "path", "of", "the", "generated", "source", "relative", "to", "the", "build"...
def get_target_generated_dir( self, target: T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex], gensrc: T.Union[build.CustomTarget, build.CustomTargetIndex, build.GeneratedList], src: str) -> str: """ Takes a BuildTarget, a generator source (CustomTarget or GeneratedList), and a generated source filename. Returns the full path of the generated source relative to the build root """ # CustomTarget generators output to the build dir of the CustomTarget if isinstance(gensrc, (build.CustomTarget, build.CustomTargetIndex)): return os.path.join(self.get_target_dir(gensrc), src) # GeneratedList generators output to the private build directory of the # target that the GeneratedList is used in return os.path.join(self.get_target_private_dir(target), src)
[ "def", "get_target_generated_dir", "(", "self", ",", "target", ":", "T", ".", "Union", "[", "build", ".", "BuildTarget", ",", "build", ".", "CustomTarget", ",", "build", ".", "CustomTargetIndex", "]", ",", "gensrc", ":", "T", ".", "Union", "[", "build", ...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/backend/backends.py#L418-L432
nvaccess/nvda
20d5a25dced4da34338197f0ef6546270ebca5d0
source/browseMode.py
python
QuickNavItem.report
(self,readUnit=None)
Reports the contents of this item. @param readUnit: the optional unit (e.g. line, paragraph) that should be used to announce the item position when moved to. If not given, then the full sise of the item is used. @type readUnit: a L{textInfos}.UNIT_* constant.
Reports the contents of this item.
[ "Reports", "the", "contents", "of", "this", "item", "." ]
def report(self,readUnit=None): """ Reports the contents of this item. @param readUnit: the optional unit (e.g. line, paragraph) that should be used to announce the item position when moved to. If not given, then the full sise of the item is used. @type readUnit: a L{textInfos}.UNIT_* constant. """ raise NotImplementedError
[ "def", "report", "(", "self", ",", "readUnit", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/browseMode.py#L133-L139
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_persistent_volume_claim_condition.py
python
V1PersistentVolumeClaimCondition.reason
(self, reason)
Sets the reason of this V1PersistentVolumeClaimCondition. Unique, this should be a short, machine understandable string that gives the reason for condition's last transition. If it reports \"ResizeStarted\" that means the underlying persistent volume is being resized. # noqa: E501 :param reason: The reason of this V1PersistentVolumeClaimCondition. # noqa: E501 :type: str
Sets the reason of this V1PersistentVolumeClaimCondition.
[ "Sets", "the", "reason", "of", "this", "V1PersistentVolumeClaimCondition", "." ]
def reason(self, reason): """Sets the reason of this V1PersistentVolumeClaimCondition. Unique, this should be a short, machine understandable string that gives the reason for condition's last transition. If it reports \"ResizeStarted\" that means the underlying persistent volume is being resized. # noqa: E501 :param reason: The reason of this V1PersistentVolumeClaimCondition. # noqa: E501 :type: str """ self._reason = reason
[ "def", "reason", "(", "self", ",", "reason", ")", ":", "self", ".", "_reason", "=", "reason" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_persistent_volume_claim_condition.py#L159-L168
MillionIntegrals/vel
f3ce7da64362ad207f40f2c0d58d9300a25df3e8
vel/api/info.py
python
EpochInfo.state_dict
(self)
return hidden_state
Calculate hidden state dictionary
Calculate hidden state dictionary
[ "Calculate", "hidden", "state", "dictionary" ]
def state_dict(self) -> dict: """ Calculate hidden state dictionary """ hidden_state = {} if self.optimizer is not None: hidden_state['optimizer'] = self.optimizer.state_dict() for callback in self.callbacks: callback.write_state_dict(self.training_info, hidden_state) return hidden_state
[ "def", "state_dict", "(", "self", ")", "->", "dict", ":", "hidden_state", "=", "{", "}", "if", "self", ".", "optimizer", "is", "not", "None", ":", "hidden_state", "[", "'optimizer'", "]", "=", "self", ".", "optimizer", ".", "state_dict", "(", ")", "for...
https://github.com/MillionIntegrals/vel/blob/f3ce7da64362ad207f40f2c0d58d9300a25df3e8/vel/api/info.py#L186-L196
facebookresearch/mmf
fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f
mmf/datasets/builders/coco/detection_dataset.py
python
DetectionCOCODataset.__init__
(self, config, dataset_type, imdb_file_index, *args, **kwargs)
[]
def __init__(self, config, dataset_type, imdb_file_index, *args, **kwargs): if "name" in kwargs: name = kwargs["name"] elif "dataset_name" in kwargs: name = kwargs["dataset_name"] else: name = "detection_coco" super().__init__(name, config, dataset_type, *args, **kwargs) self.dataset_name = name image_dir = self.config.images[self._dataset_type][imdb_file_index] self.image_dir = os.path.join(self.config.data_dir, image_dir) coco_json = self.config.annotations[self._dataset_type][imdb_file_index] self.coco_json = os.path.join(self.config.data_dir, coco_json) self.coco_dataset = torchvision.datasets.CocoDetection( self.image_dir, self.coco_json ) self.postprocessors = {"bbox": PostProcess()}
[ "def", "__init__", "(", "self", ",", "config", ",", "dataset_type", ",", "imdb_file_index", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "\"name\"", "in", "kwargs", ":", "name", "=", "kwargs", "[", "\"name\"", "]", "elif", "\"dataset_name\"...
https://github.com/facebookresearch/mmf/blob/fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f/mmf/datasets/builders/coco/detection_dataset.py#L15-L34
microsoft/ptvsd
99c8513921021d2cc7cd82e132b65c644c256768
src/ptvsd/_version.py
python
render_git_describe_long
(pieces)
return rendered
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
TAG-DISTANCE-gHEX[-dirty].
[ "TAG", "-", "DISTANCE", "-", "gHEX", "[", "-", "dirty", "]", "." ]
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered
[ "def", "render_git_describe_long", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "rendered", "+=", "\"-%d-g%s\"", "%", "(", "pieces", "[", "\"distance\"", "]", ",", "pieces", ...
https://github.com/microsoft/ptvsd/blob/99c8513921021d2cc7cd82e132b65c644c256768/src/ptvsd/_version.py#L429-L446
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/lib/format.py
python
_read_array_header
(fp, version)
return d['shape'], d['fortran_order'], dtype
see read_array_header_1_0
see read_array_header_1_0
[ "see", "read_array_header_1_0" ]
def _read_array_header(fp, version): """ see read_array_header_1_0 """ # Read an unsigned, little-endian short int which has the length of the # header. import struct if version == (1, 0): hlength_str = _read_bytes(fp, 2, "array header length") header_length = struct.unpack('<H', hlength_str)[0] header = _read_bytes(fp, header_length, "array header") elif version == (2, 0): hlength_str = _read_bytes(fp, 4, "array header length") header_length = struct.unpack('<I', hlength_str)[0] header = _read_bytes(fp, header_length, "array header") else: raise ValueError("Invalid version %r" % version) # The header is a pretty-printed string representation of a literal # Python dictionary with trailing newlines padded to a 16-byte # boundary. The keys are strings. # "shape" : tuple of int # "fortran_order" : bool # "descr" : dtype.descr header = _filter_header(header) try: d = safe_eval(header) except SyntaxError as e: msg = "Cannot parse header: %r\nException: %r" raise ValueError(msg % (header, e)) if not isinstance(d, dict): msg = "Header is not a dictionary: %r" raise ValueError(msg % d) keys = sorted(d.keys()) if keys != ['descr', 'fortran_order', 'shape']: msg = "Header does not contain the correct keys: %r" raise ValueError(msg % (keys,)) # Sanity-check the values. if (not isinstance(d['shape'], tuple) or not numpy.all([isinstance(x, (int, long)) for x in d['shape']])): msg = "shape is not valid: %r" raise ValueError(msg % (d['shape'],)) if not isinstance(d['fortran_order'], bool): msg = "fortran_order is not a valid bool: %r" raise ValueError(msg % (d['fortran_order'],)) try: dtype = numpy.dtype(d['descr']) except TypeError as e: msg = "descr is not a valid dtype descriptor: %r" raise ValueError(msg % (d['descr'],)) return d['shape'], d['fortran_order'], dtype
[ "def", "_read_array_header", "(", "fp", ",", "version", ")", ":", "# Read an unsigned, little-endian short int which has the length of the", "# header.", "import", "struct", "if", "version", "==", "(", "1", ",", "0", ")", ":", "hlength_str", "=", "_read_bytes", "(", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/lib/format.py#L464-L516
wkeeling/selenium-wire
5a5a83c0189e0a10fbcf100d619148d6c1bc7dad
seleniumwire/thirdparty/mitmproxy/optmanager.py
python
OptManager.process_deferred
(self)
Processes options that were deferred in previous calls to set, and have since been added.
Processes options that were deferred in previous calls to set, and have since been added.
[ "Processes", "options", "that", "were", "deferred", "in", "previous", "calls", "to", "set", "and", "have", "since", "been", "added", "." ]
def process_deferred(self): """ Processes options that were deferred in previous calls to set, and have since been added. """ update = {} for optname, optval in self.deferred.items(): if optname in self._options: optval = self.parse_setval(self._options[optname], optval) update[optname] = optval self.update(**update) for k in update.keys(): del self.deferred[k]
[ "def", "process_deferred", "(", "self", ")", ":", "update", "=", "{", "}", "for", "optname", ",", "optval", "in", "self", ".", "deferred", ".", "items", "(", ")", ":", "if", "optname", "in", "self", ".", "_options", ":", "optval", "=", "self", ".", ...
https://github.com/wkeeling/selenium-wire/blob/5a5a83c0189e0a10fbcf100d619148d6c1bc7dad/seleniumwire/thirdparty/mitmproxy/optmanager.py#L313-L325
NeuromorphicProcessorProject/snn_toolbox
a85ada7b5d060500703285ef8a68f06ea1ffda65
snntoolbox/parsing/utils.py
python
AbstractModelParser.parse_convolution
(self, layer, attributes)
Parse a convolutional layer. Parameters ---------- layer: Layer. attributes: dict The layer attributes as key-value pairs in a dict.
Parse a convolutional layer.
[ "Parse", "a", "convolutional", "layer", "." ]
def parse_convolution(self, layer, attributes): """Parse a convolutional layer. Parameters ---------- layer: Layer. attributes: dict The layer attributes as key-value pairs in a dict. """ pass
[ "def", "parse_convolution", "(", "self", ",", "layer", ",", "attributes", ")", ":", "pass" ]
https://github.com/NeuromorphicProcessorProject/snn_toolbox/blob/a85ada7b5d060500703285ef8a68f06ea1ffda65/snntoolbox/parsing/utils.py#L609-L621
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/python/log.py
python
Logger.logPrefix
(self)
return "-"
Override this method to insert custom logging behavior. Its return value will be inserted in front of every line. It may be called more times than the number of output lines.
Override this method to insert custom logging behavior. Its return value will be inserted in front of every line. It may be called more times than the number of output lines.
[ "Override", "this", "method", "to", "insert", "custom", "logging", "behavior", ".", "Its", "return", "value", "will", "be", "inserted", "in", "front", "of", "every", "line", ".", "It", "may", "be", "called", "more", "times", "than", "the", "number", "of", ...
def logPrefix(self): """ Override this method to insert custom logging behavior. Its return value will be inserted in front of every line. It may be called more times than the number of output lines. """ return "-"
[ "def", "logPrefix", "(", "self", ")", ":", "return", "\"-\"" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/python/log.py#L141-L147
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/algo/discovery/inductive/variants/im_clean/cuts/sequence.py
python
project
(log, groups, activity_key)
return logs
This method projects the log based on a presumed sequence cut and a list of activity groups Parameters ---------- log original log groups list of activity sets to be used in projection (activities can only appear in one group) activity_key key to use in the event to derive the activity name Returns ------- list of corresponding logs according to the sequence cut.
This method projects the log based on a presumed sequence cut and a list of activity groups Parameters ---------- log original log groups list of activity sets to be used in projection (activities can only appear in one group) activity_key key to use in the event to derive the activity name
[ "This", "method", "projects", "the", "log", "based", "on", "a", "presumed", "sequence", "cut", "and", "a", "list", "of", "activity", "groups", "Parameters", "----------", "log", "original", "log", "groups", "list", "of", "activity", "sets", "to", "be", "used...
def project(log, groups, activity_key): ''' This method projects the log based on a presumed sequence cut and a list of activity groups Parameters ---------- log original log groups list of activity sets to be used in projection (activities can only appear in one group) activity_key key to use in the event to derive the activity name Returns ------- list of corresponding logs according to the sequence cut. ''' # refactored to support both IM and IMf logs = list() for group in groups: logs.append(EventLog()) for t in log: i = 0 split_point = 0 act_union = set() while i < len(groups): new_split_point = find_split_point(t, groups[i], split_point, act_union, activity_key) trace_i = Trace() j = split_point while j < new_split_point: if t[j][activity_key] in groups[i]: trace_i.append(t[j]) j = j + 1 logs[i].append(trace_i) split_point = new_split_point act_union = act_union.union(set(groups[i])) i = i + 1 return logs
[ "def", "project", "(", "log", ",", "groups", ",", "activity_key", ")", ":", "# refactored to support both IM and IMf", "logs", "=", "list", "(", ")", "for", "group", "in", "groups", ":", "logs", ".", "append", "(", "EventLog", "(", ")", ")", "for", "t", ...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/algo/discovery/inductive/variants/im_clean/cuts/sequence.py#L64-L100
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/ADT/AutoDockTools/autoanalyzeCommands.py
python
StatesPlayerWidget.MakeRef_cb
(self, event=None)
None<-MakeRef_cb(mol, event=None) makes current molecule coordinates rmstool refCoords
None<-MakeRef_cb(mol, event=None)
[ "None<", "-", "MakeRef_cb", "(", "mol", "event", "=", "None", ")" ]
def MakeRef_cb(self, event=None): """None<-MakeRef_cb(mol, event=None) makes current molecule coordinates rmstool refCoords """ clusterer = self.vf.docked.clusterer rmsTool = clusterer.rmsTool if clusterer.usesSubset: rmsTool.setRefCoords(clusterer.subset.coords[:]) else: rmsTool.setRefCoords(self.mol.allAtoms.coords[:]) clusterer.rmsToolRef = self.form.ent2.get()
[ "def", "MakeRef_cb", "(", "self", ",", "event", "=", "None", ")", ":", "clusterer", "=", "self", ".", "vf", ".", "docked", ".", "clusterer", "rmsTool", "=", "clusterer", ".", "rmsTool", "if", "clusterer", ".", "usesSubset", ":", "rmsTool", ".", "setRefCo...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/ADT/AutoDockTools/autoanalyzeCommands.py#L5941-L5952
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
tools/sqlmap/extra/safe2bin/safe2bin.py
python
safecharencode
(value)
return retVal
Returns safe representation of a given basestring value >>> safecharencode(u'test123') u'test123' >>> safecharencode(u'test\x01\x02\xff') u'test\\01\\02\\03\\ff'
Returns safe representation of a given basestring value
[ "Returns", "safe", "representation", "of", "a", "given", "basestring", "value" ]
def safecharencode(value): """ Returns safe representation of a given basestring value >>> safecharencode(u'test123') u'test123' >>> safecharencode(u'test\x01\x02\xff') u'test\\01\\02\\03\\ff' """ retVal = value if isinstance(value, basestring): if any(_ not in SAFE_CHARS for _ in value): retVal = retVal.replace('\\', SLASH_MARKER) for char in SAFE_ENCODE_SLASH_REPLACEMENTS: retVal = retVal.replace(char, repr(char).strip('\'')) retVal = reduce(lambda x, y: x + (y if (y in string.printable or ord(y) > 255) else '\\x%02x' % ord(y)), retVal, (unicode if isinstance(value, unicode) else str)()) retVal = retVal.replace(SLASH_MARKER, "\\\\") elif isinstance(value, list): for i in xrange(len(value)): retVal[i] = safecharencode(value[i]) return retVal
[ "def", "safecharencode", "(", "value", ")", ":", "retVal", "=", "value", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "if", "any", "(", "_", "not", "in", "SAFE_CHARS", "for", "_", "in", "value", ")", ":", "retVal", "=", "retVal", "....
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/sqlmap/extra/safe2bin/safe2bin.py#L34-L60
daoluan/decode-Django
d46a858b45b56de48b0355f50dd9e45402d04cfd
Django-1.5.1/django/contrib/gis/maps/google/gmap.py
python
GoogleMapSet.icons
(self)
return icons
Returns a sequence of all icons in each map of the set.
Returns a sequence of all icons in each map of the set.
[ "Returns", "a", "sequence", "of", "all", "icons", "in", "each", "map", "of", "the", "set", "." ]
def icons(self): "Returns a sequence of all icons in each map of the set." icons = set() for map in self.maps: icons |= map.icons return icons
[ "def", "icons", "(", "self", ")", ":", "icons", "=", "set", "(", ")", "for", "map", "in", "self", ".", "maps", ":", "icons", "|=", "map", ".", "icons", "return", "icons" ]
https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/contrib/gis/maps/google/gmap.py#L228-L232
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter9/pycrypto-2.6.1/build/lib.win32-2.7/Crypto/Util/number.py
python
bytes_to_long
(s)
return acc
bytes_to_long(string) : long Convert a byte string to a long integer. This is (essentially) the inverse of long_to_bytes().
bytes_to_long(string) : long Convert a byte string to a long integer.
[ "bytes_to_long", "(", "string", ")", ":", "long", "Convert", "a", "byte", "string", "to", "a", "long", "integer", "." ]
def bytes_to_long(s): """bytes_to_long(string) : long Convert a byte string to a long integer. This is (essentially) the inverse of long_to_bytes(). """ acc = 0L unpack = struct.unpack length = len(s) if length % 4: extra = (4 - length % 4) s = b('\000') * extra + s length = length + extra for i in range(0, length, 4): acc = (acc << 32) + unpack('>I', s[i:i+4])[0] return acc
[ "def", "bytes_to_long", "(", "s", ")", ":", "acc", "=", "0L", "unpack", "=", "struct", ".", "unpack", "length", "=", "len", "(", "s", ")", "if", "length", "%", "4", ":", "extra", "=", "(", "4", "-", "length", "%", "4", ")", "s", "=", "b", "("...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter9/pycrypto-2.6.1/build/lib.win32-2.7/Crypto/Util/number.py#L417-L432
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/tools/interfaces/sensors/leapmotion.py
python
LeapMotionInterface.rightmost_hand
(self)
return self.hands.rightmost
Return the right most hand.
Return the right most hand.
[ "Return", "the", "right", "most", "hand", "." ]
def rightmost_hand(self): """Return the right most hand.""" return self.hands.rightmost
[ "def", "rightmost_hand", "(", "self", ")", ":", "return", "self", ".", "hands", ".", "rightmost" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/tools/interfaces/sensors/leapmotion.py#L141-L143
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/sqlalchemy/ext/declarative/api.py
python
synonym_for
(name, map_column=False)
return decorate
Decorator, make a Python @property a query synonym for a column. A decorator version of :func:`~sqlalchemy.orm.synonym`. The function being decorated is the 'descriptor', otherwise passes its arguments through to synonym():: @synonym_for('col') @property def prop(self): return 'special sauce' The regular ``synonym()`` is also usable directly in a declarative setting and may be convenient for read/write properties:: prop = synonym('col', descriptor=property(_read_prop, _write_prop))
Decorator, make a Python @property a query synonym for a column.
[ "Decorator", "make", "a", "Python", "@property", "a", "query", "synonym", "for", "a", "column", "." ]
def synonym_for(name, map_column=False): """Decorator, make a Python @property a query synonym for a column. A decorator version of :func:`~sqlalchemy.orm.synonym`. The function being decorated is the 'descriptor', otherwise passes its arguments through to synonym():: @synonym_for('col') @property def prop(self): return 'special sauce' The regular ``synonym()`` is also usable directly in a declarative setting and may be convenient for read/write properties:: prop = synonym('col', descriptor=property(_read_prop, _write_prop)) """ def decorate(fn): return _orm_synonym(name, map_column=map_column, descriptor=fn) return decorate
[ "def", "synonym_for", "(", "name", ",", "map_column", "=", "False", ")", ":", "def", "decorate", "(", "fn", ")", ":", "return", "_orm_synonym", "(", "name", ",", "map_column", "=", "map_column", ",", "descriptor", "=", "fn", ")", "return", "decorate" ]
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/sqlalchemy/ext/declarative/api.py#L62-L82
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/email/header.py
python
Header.encode
(self, splitchars=';, ')
return value
Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. This method will do its best to convert the string to the correct character set used in email, and encode and line wrap it safely with the appropriate scheme for that character set. If the given charset is not known or an error occurs during conversion, this function will return the header untouched. Optional splitchars is a string containing characters to split long ASCII lines on, in rough support of RFC 2822's `highest level syntactic breaks'. This doesn't affect RFC 2047 encoded lines.
Encode a message header into an RFC-compliant format.
[ "Encode", "a", "message", "header", "into", "an", "RFC", "-", "compliant", "format", "." ]
def encode(self, splitchars=';, '): """Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. This method will do its best to convert the string to the correct character set used in email, and encode and line wrap it safely with the appropriate scheme for that character set. If the given charset is not known or an error occurs during conversion, this function will return the header untouched. Optional splitchars is a string containing characters to split long ASCII lines on, in rough support of RFC 2822's `highest level syntactic breaks'. This doesn't affect RFC 2047 encoded lines. """ newchunks = [] maxlinelen = self._firstlinelen lastlen = 0 for s, charset in self._chunks: # The first bit of the next chunk should be just long enough to # fill the next line. Don't forget the space separating the # encoded words. targetlen = maxlinelen - lastlen - 1 if targetlen < charset.encoded_header_len(''): # Stick it on the next line targetlen = maxlinelen newchunks += self._split(s, charset, targetlen, splitchars) lastchunk, lastcharset = newchunks[-1] lastlen = lastcharset.encoded_header_len(lastchunk) value = self._encode_chunks(newchunks, maxlinelen) if _embeded_header.search(value): raise HeaderParseError("header value appears to contain " "an embedded header: {!r}".format(value)) return value
[ "def", "encode", "(", "self", ",", "splitchars", "=", "';, '", ")", ":", "newchunks", "=", "[", "]", "maxlinelen", "=", "self", ".", "_firstlinelen", "lastlen", "=", "0", "for", "s", ",", "charset", "in", "self", ".", "_chunks", ":", "# The first bit of ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/email/header.py#L374-L414
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/navs/forms.py
python
NavForm.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): super(NavForm, self).__init__(*args, **kwargs) self.fields['title'].validators.append(UnicodeNameValidator())
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "NavForm", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "fields", "[", "'title'", "]", ".", "v...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/navs/forms.py#L45-L47
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
apps/topi_recipe/rnn/lstm.py
python
tvm_callback_cuda_compile
(code)
return ptx
Use nvcc compiler for better perf.
Use nvcc compiler for better perf.
[ "Use", "nvcc", "compiler", "for", "better", "perf", "." ]
def tvm_callback_cuda_compile(code): """Use nvcc compiler for better perf.""" ptx = nvcc.compile_cuda(code, target_format="ptx") return ptx
[ "def", "tvm_callback_cuda_compile", "(", "code", ")", ":", "ptx", "=", "nvcc", ".", "compile_cuda", "(", "code", ",", "target_format", "=", "\"ptx\"", ")", "return", "ptx" ]
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/apps/topi_recipe/rnn/lstm.py#L34-L37
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/released/identity/identity_client.py
python
IdentityClient.get_user_identity_ids_by_domain_id
(self, domain_id)
return self._deserialize('[str]', self._unwrap_collection(response))
GetUserIdentityIdsByDomainId. :param str domain_id: :rtype: [str]
GetUserIdentityIdsByDomainId. :param str domain_id: :rtype: [str]
[ "GetUserIdentityIdsByDomainId", ".", ":", "param", "str", "domain_id", ":", ":", "rtype", ":", "[", "str", "]" ]
def get_user_identity_ids_by_domain_id(self, domain_id): """GetUserIdentityIdsByDomainId. :param str domain_id: :rtype: [str] """ query_parameters = {} if domain_id is not None: query_parameters['domainId'] = self._serialize.query('domain_id', domain_id, 'str') response = self._send(http_method='GET', location_id='28010c54-d0c0-4c89-a5b0-1c9e188b9fb7', version='5.1', query_parameters=query_parameters) return self._deserialize('[str]', self._unwrap_collection(response))
[ "def", "get_user_identity_ids_by_domain_id", "(", "self", ",", "domain_id", ")", ":", "query_parameters", "=", "{", "}", "if", "domain_id", "is", "not", "None", ":", "query_parameters", "[", "'domainId'", "]", "=", "self", ".", "_serialize", ".", "query", "(",...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/released/identity/identity_client.py#L101-L113
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/encodings/mac_croatian.py
python
getregentry
()
return codecs.CodecInfo( name='mac-croatian', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
[]
def getregentry(): return codecs.CodecInfo( name='mac-croatian', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
[ "def", "getregentry", "(", ")", ":", "return", "codecs", ".", "CodecInfo", "(", "name", "=", "'mac-croatian'", ",", "encode", "=", "Codec", "(", ")", ".", "encode", ",", "decode", "=", "Codec", "(", ")", ".", "decode", ",", "incrementalencoder", "=", "...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/encodings/mac_croatian.py#L33-L42
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/email/iterators.py
python
typed_subpart_iterator
(msg, maintype='text', subtype=None)
return
Iterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched.
Iterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched.
[ "Iterate", "over", "the", "subparts", "with", "a", "given", "MIME", "type", ".", "Use", "maintype", "as", "the", "main", "MIME", "type", "to", "match", "against", ";", "this", "defaults", "to", "text", ".", "Optional", "subtype", "is", "the", "MIME", "su...
def typed_subpart_iterator(msg, maintype='text', subtype=None): """Iterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched. """ for subpart in msg.walk(): if subpart.get_content_maintype() == maintype: if subtype is None or subpart.get_content_subtype() == subtype: yield subpart return
[ "def", "typed_subpart_iterator", "(", "msg", ",", "maintype", "=", "'text'", ",", "subtype", "=", "None", ")", ":", "for", "subpart", "in", "msg", ".", "walk", "(", ")", ":", "if", "subpart", ".", "get_content_maintype", "(", ")", "==", "maintype", ":", ...
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/email/iterators.py#L39-L51
zacharyvoase/markdoc
694914ccb198d74e37321fc601061fe7f725b1ce
distribute_setup.py
python
_patch_file
(path, content)
return True
Will backup the file then patch it
Will backup the file then patch it
[ "Will", "backup", "the", "file", "then", "patch", "it" ]
def _patch_file(path, content): """Will backup the file then patch it""" existing_content = open(path).read() if existing_content == content: # already patched log.warn('Already patched.') return False log.warn('Patching...') _rename_path(path) f = open(path, 'w') try: f.write(content) finally: f.close() return True
[ "def", "_patch_file", "(", "path", ",", "content", ")", ":", "existing_content", "=", "open", "(", "path", ")", ".", "read", "(", ")", "if", "existing_content", "==", "content", ":", "# already patched", "log", ".", "warn", "(", "'Already patched.'", ")", ...
https://github.com/zacharyvoase/markdoc/blob/694914ccb198d74e37321fc601061fe7f725b1ce/distribute_setup.py#L207-L221
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/smtpd.py
python
SMTPChannel.smtp_HELO
(self, arg)
[]
def smtp_HELO(self, arg): if not arg: self.push('501 Syntax: HELO hostname') return if self.__greeting: self.push('503 Duplicate HELO/EHLO') else: self.__greeting = arg self.push('250 %s' % self.__fqdn)
[ "def", "smtp_HELO", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ":", "self", ".", "push", "(", "'501 Syntax: HELO hostname'", ")", "return", "if", "self", ".", "__greeting", ":", "self", ".", "push", "(", "'503 Duplicate HELO/EHLO'", ")", "else"...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/smtpd.py#L192-L200
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/gdata/apps/service.py
python
AppsService.UpdateUser
(self, user_name, user_entry)
Update a user account.
Update a user account.
[ "Update", "a", "user", "account", "." ]
def UpdateUser(self, user_name, user_entry): """Update a user account.""" uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name) try: return gdata.apps.UserEntryFromString(str(self.Put(user_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0])
[ "def", "UpdateUser", "(", "self", ",", "user_name", ",", "user_entry", ")", ":", "uri", "=", "\"%s/user/%s/%s\"", "%", "(", "self", ".", "_baseURL", "(", ")", ",", "API_VER", ",", "user_name", ")", "try", ":", "return", "gdata", ".", "apps", ".", "User...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/gdata/apps/service.py#L315-L322
ioflo/ioflo
177ac656d7c4ff801aebb0d8b401db365a5248ce
ioflo/aid/navigating.py
python
SphereLLbyRBtoLL
(lat0,lon0,range,bearing)
return (lat1, lon1)
Computes new lat lon location on sphere from the flat earth approx of change in range meters at bearing degrees from from the given location lat0 lon0 point lat0 lon0 in total fractional degrees north east positive returns tuple (lat1,lon1) Uses sphere 1 nm = 1 minute 1852 meters per nautical mile
Computes new lat lon location on sphere from the flat earth approx of change in range meters at bearing degrees from from the given location lat0 lon0 point lat0 lon0 in total fractional degrees north east positive returns tuple (lat1,lon1) Uses sphere 1 nm = 1 minute 1852 meters per nautical mile
[ "Computes", "new", "lat", "lon", "location", "on", "sphere", "from", "the", "flat", "earth", "approx", "of", "change", "in", "range", "meters", "at", "bearing", "degrees", "from", "from", "the", "given", "location", "lat0", "lon0", "point", "lat0", "lon0", ...
def SphereLLbyRBtoLL(lat0,lon0,range,bearing): """Computes new lat lon location on sphere from the flat earth approx of change in range meters at bearing degrees from from the given location lat0 lon0 point lat0 lon0 in total fractional degrees north east positive returns tuple (lat1,lon1) Uses sphere 1 nm = 1 minute 1852 meters per nautical mile """ r = 6366710.0 #radius of earth in meters = 1852 * 60 * 180/pi dn = range * math.cos(DEGTORAD * bearing) de = range * math.sin(DEGTORAD * bearing) dlat = dn/(r * DEGTORAD) lat1 = lat0 + dlat avlat = (lat1 + lat0)/2.0 try: dlon = de / (r * DEGTORAD * math.cos(DEGTORAD * avlat)) except ZeroDivisionError: dlon = 0.0 lon1 = lon0 + dlon avlat = (lat1 + lat0)/2.0 return (lat1, lon1)
[ "def", "SphereLLbyRBtoLL", "(", "lat0", ",", "lon0", ",", "range", ",", "bearing", ")", ":", "r", "=", "6366710.0", "#radius of earth in meters = 1852 * 60 * 180/pi", "dn", "=", "range", "*", "math", ".", "cos", "(", "DEGTORAD", "*", "bearing", ")", "de", "=...
https://github.com/ioflo/ioflo/blob/177ac656d7c4ff801aebb0d8b401db365a5248ce/ioflo/aid/navigating.py#L361-L387
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/gse/v20191112/models.py
python
UpdateFleetAttributesResponse.__init__
(self)
r""" :param FleetId: 服务器舰队Id 注意:此字段可能返回 null,表示取不到有效值。 :type FleetId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param FleetId: 服务器舰队Id 注意:此字段可能返回 null,表示取不到有效值。 :type FleetId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "FleetId", ":", "服务器舰队Id", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "FleetId", ":", "str", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时需要提供该次请求的", "RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): r""" :param FleetId: 服务器舰队Id 注意:此字段可能返回 null,表示取不到有效值。 :type FleetId: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.FleetId = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "FleetId", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/gse/v20191112/models.py#L6565-L6574
anoopkunchukuttan/indic_nlp_library
1e0f224dcf9d00664e0435399b087a4c6f07787d
indicnlp/tokenize/sentence_tokenize.py
python
is_acronym_abbvr
(text,lang)
return unicode_transliterate.UnicodeIndicTransliterator.transliterate(text,lang,'hi') in ack_chars
Is the text a non-breaking phrase Args: text (str): text to check for non-breaking phrase lang (str): ISO 639-2 language code Returns: boolean: true if `text` is a non-breaking phrase
Is the text a non-breaking phrase
[ "Is", "the", "text", "a", "non", "-", "breaking", "phrase" ]
def is_acronym_abbvr(text,lang): """Is the text a non-breaking phrase Args: text (str): text to check for non-breaking phrase lang (str): ISO 639-2 language code Returns: boolean: true if `text` is a non-breaking phrase """ ack_chars = { ## acronym for latin characters 'ए', 'ऎ', 'बी', 'बि', 'सी', 'सि', 'डी', 'डि', 'ई', 'इ', 'एफ', 'ऎफ', 'जी', 'जि', 'एच','ऎच', 'आई', 'आइ','ऐ', 'जे', 'जॆ', 'के', 'कॆ', 'एल', 'ऎल', 'एम','ऎम', 'एन','ऎन', 'ओ', 'ऒ', 'पी', 'पि', 'क्यू', 'क्यु', 'आर', 'एस','ऎस', 'टी', 'टि', 'यू', 'यु', 'वी', 'वि', 'व्ही', 'व्हि', 'डब्ल्यू', 'डब्ल्यु', 'एक्स','ऎक्स', 'वाय', 'जेड', 'ज़ेड', ## add halant to the previous English character mappings. 'एफ्', 'ऎफ्', 'एच्', 'ऎच्', 'एल्', 'ऎल्', 'एम्', 'ऎम्', 'एन्', 'ऎन्', 'आर्', 'एस्', 'ऎस्', 'एक्स्', 'ऎक्स्', 'वाय्', 'जेड्', 'ज़ेड्', #Indic vowels 'ऄ', 'अ', 'आ', 'इ', 'ई', 'उ', 'ऊ', 'ऋ', 'ऌ', 'ऍ', 'ऎ', 'ए', 'ऐ', 'ऑ', 'ऒ', 'ओ', 'औ', 'ॠ', 'ॡ', #Indic consonants 'क', 'ख', 'ग', 'घ', 'ङ', 'च', 'छ', 'ज', 'झ', 'ञ', 'ट', 'ठ', 'ड', 'ढ', 'ण', 'त', 'थ', 'द', 'ध', 'न', 'ऩ', 'प', 'फ', 'ब', 'भ', 'म', 'य', 'र', 'ऱ', 'ल', 'ळ', 'ऴ', 'व', 'श', 'ष', 'स', 'ह', ## abbreviation 'श्री', 'डॉ', 'कु', 'चि', 'सौ', } return unicode_transliterate.UnicodeIndicTransliterator.transliterate(text,lang,'hi') in ack_chars
[ "def", "is_acronym_abbvr", "(", "text", ",", "lang", ")", ":", "ack_chars", "=", "{", "## acronym for latin characters", "'ए', ", "'", "',", "", "'बी', 'ब", "ि", ", ", "", "'सी', 'स", "ि", ",", "", "'डी', 'ड", "ि", ",", "", "'ई', ", "'", "',", "", "'एफ...
https://github.com/anoopkunchukuttan/indic_nlp_library/blob/1e0f224dcf9d00664e0435399b087a4c6f07787d/indicnlp/tokenize/sentence_tokenize.py#L35-L161
oaubert/python-vlc
908ffdbd0844dc1849728c456e147788798c99da
generated/3.0/vlc.py
python
libvlc_media_get_tracks_info
(p_md)
return f(p_md)
Get media descriptor's elementary streams description Note, you need to call L{libvlc_media_parse}() or play the media at least once before calling this function. Not doing this will result in an empty array. \deprecated Use L{libvlc_media_tracks_get}() instead. @param p_md: media descriptor object. @param tracks: address to store an allocated array of Elementary Streams descriptions (must be freed by the caller) [OUT]. @return: the number of Elementary Streams.
Get media descriptor's elementary streams description Note, you need to call L{libvlc_media_parse}() or play the media at least once before calling this function. Not doing this will result in an empty array. \deprecated Use L{libvlc_media_tracks_get}() instead.
[ "Get", "media", "descriptor", "s", "elementary", "streams", "description", "Note", "you", "need", "to", "call", "L", "{", "libvlc_media_parse", "}", "()", "or", "play", "the", "media", "at", "least", "once", "before", "calling", "this", "function", ".", "Not...
def libvlc_media_get_tracks_info(p_md): '''Get media descriptor's elementary streams description Note, you need to call L{libvlc_media_parse}() or play the media at least once before calling this function. Not doing this will result in an empty array. \deprecated Use L{libvlc_media_tracks_get}() instead. @param p_md: media descriptor object. @param tracks: address to store an allocated array of Elementary Streams descriptions (must be freed by the caller) [OUT]. @return: the number of Elementary Streams. ''' f = _Cfunctions.get('libvlc_media_get_tracks_info', None) or \ _Cfunction('libvlc_media_get_tracks_info', ((1,), (2,),), None, ctypes.c_int, Media, ctypes.POINTER(ctypes.POINTER(MediaTrackInfo))) return f(p_md)
[ "def", "libvlc_media_get_tracks_info", "(", "p_md", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_media_get_tracks_info'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_get_tracks_info'", ",", "(", "(", "1", ",", ")", ",", "(", "2", ...
https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/3.0/vlc.py#L4733-L4746
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_route.py
python
OpenShiftCLI._replace
(self, fname, force=False)
return self.openshift_cmd(cmd)
replace the current object with oc replace
replace the current object with oc replace
[ "replace", "the", "current", "object", "with", "oc", "replace" ]
def _replace(self, fname, force=False): '''replace the current object with oc replace''' # We are removing the 'resourceVersion' to handle # a race condition when modifying oc objects yed = Yedit(fname) results = yed.delete('metadata.resourceVersion') if results[0]: yed.write() cmd = ['replace', '-f', fname] if force: cmd.append('--force') return self.openshift_cmd(cmd)
[ "def", "_replace", "(", "self", ",", "fname", ",", "force", "=", "False", ")", ":", "# We are removing the 'resourceVersion' to handle", "# a race condition when modifying oc objects", "yed", "=", "Yedit", "(", "fname", ")", "results", "=", "yed", ".", "delete", "("...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_route.py#L979-L991
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/colorama/ansi.py
python
AnsiCursor.DOWN
(self, n=1)
return CSI + str(n) + 'B'
[]
def DOWN(self, n=1): return CSI + str(n) + 'B'
[ "def", "DOWN", "(", "self", ",", "n", "=", "1", ")", ":", "return", "CSI", "+", "str", "(", "n", ")", "+", "'B'" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/colorama/ansi.py#L39-L40
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/shutil.py
python
copy2
(src, dst)
Copy data and all stat info ("cp -p src dst"). The destination may be a directory.
Copy data and all stat info ("cp -p src dst").
[ "Copy", "data", "and", "all", "stat", "info", "(", "cp", "-", "p", "src", "dst", ")", "." ]
def copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst)
[ "def", "copy2", "(", "src", ",", "dst", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "dst", ")", ":", "dst", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "os", ".", "path", ".", "basename", "(", "src", ")", ")", "copyfile", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/shutil.py#L141-L150
JacquesLucke/animation_nodes
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
animation_nodes/nodes/spline/smooth_bezier_spline.py
python
SmoothBezierSplineNode.create
(self)
[]
def create(self): socket = self.newInput(VectorizedSocket("Spline", "useSplineList", ("Spline", "spline"), ("Splines", "splines"))) socket.defaultDrawType = "TEXT_ONLY" socket.dataIsModified = True self.newInput("Float", "Smoothness", "smoothness", value = 0.3333) self.newOutput(VectorizedSocket("Spline", "useSplineList", ("Spline", "spline"), ("Splines", "splines")))
[ "def", "create", "(", "self", ")", ":", "socket", "=", "self", ".", "newInput", "(", "VectorizedSocket", "(", "\"Spline\"", ",", "\"useSplineList\"", ",", "(", "\"Spline\"", ",", "\"spline\"", ")", ",", "(", "\"Splines\"", ",", "\"splines\"", ")", ")", ")"...
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/spline/smooth_bezier_spline.py#L11-L20
twschiller/open-synthesis
4c765c1105eea31a039dde25e53ee8d3612dd206
openach/metrics.py
python
evidence_sort_key
(evaluations)
return ( -diagnosticity(evaluations), proportion_na(evaluations), proportion_unevaluated(evaluations), )
Return a key for sorting evidence. Ordering is (1) diagnosticity, (2) proportion N/A, and (3) proportion unevaluated.
Return a key for sorting evidence.
[ "Return", "a", "key", "for", "sorting", "evidence", "." ]
def evidence_sort_key(evaluations): """Return a key for sorting evidence. Ordering is (1) diagnosticity, (2) proportion N/A, and (3) proportion unevaluated. """ # could be made more efficient by not having to re-calculate mean_na_neutral and consensus vote return ( -diagnosticity(evaluations), proportion_na(evaluations), proportion_unevaluated(evaluations), )
[ "def", "evidence_sort_key", "(", "evaluations", ")", ":", "# could be made more efficient by not having to re-calculate mean_na_neutral and consensus vote", "return", "(", "-", "diagnosticity", "(", "evaluations", ")", ",", "proportion_na", "(", "evaluations", ")", ",", "prop...
https://github.com/twschiller/open-synthesis/blob/4c765c1105eea31a039dde25e53ee8d3612dd206/openach/metrics.py#L173-L183
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/categories/vector_spaces.py
python
VectorSpaces._call_
(self, x)
return V
Try to coerce ``x`` into an object of this category EXAMPLES:: sage: VectorSpaces(QQ)(ZZ^3) Vector space of dimension 3 over Rational Field TESTS: Check whether :trac:`30174` is fixed:: sage: Q3 = FiniteRankFreeModule(QQ, 3) sage: Modules(QQ)(Q3) is Q3 True
Try to coerce ``x`` into an object of this category
[ "Try", "to", "coerce", "x", "into", "an", "object", "of", "this", "category" ]
def _call_(self, x): """ Try to coerce ``x`` into an object of this category EXAMPLES:: sage: VectorSpaces(QQ)(ZZ^3) Vector space of dimension 3 over Rational Field TESTS: Check whether :trac:`30174` is fixed:: sage: Q3 = FiniteRankFreeModule(QQ, 3) sage: Modules(QQ)(Q3) is Q3 True """ try: V = x.vector_space(self.base_field()) if V.base_field() != self.base_field(): V = V.change_ring(self.base_field()) except (TypeError, AttributeError) as msg: raise TypeError("%s\nunable to coerce x (=%s) into %s"%(msg,x,self)) return V
[ "def", "_call_", "(", "self", ",", "x", ")", ":", "try", ":", "V", "=", "x", ".", "vector_space", "(", "self", ".", "base_field", "(", ")", ")", "if", "V", ".", "base_field", "(", ")", "!=", "self", ".", "base_field", "(", ")", ":", "V", "=", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/categories/vector_spaces.py#L91-L115
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/botocore/vendored/requests/packages/urllib3/response.py
python
HTTPResponse.get_redirect_location
(self)
return False
Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code.
Should we redirect and where to?
[ "Should", "we", "redirect", "and", "where", "to?" ]
def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False
[ "def", "get_redirect_location", "(", "self", ")", ":", "if", "self", ".", "status", "in", "self", ".", "REDIRECT_STATUSES", ":", "return", "self", ".", "headers", ".", "get", "(", "'location'", ")", "return", "False" ]
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/botocore/vendored/requests/packages/urllib3/response.py#L139-L150
novoid/Memacs
cc5b89a1da011a1ef08550e4da06c01881995b77
tmp/bank_statements/easybank.at/memacs-easybank.py
python
extract_known_datasets
(name, shortdescription, longdescription, descriptionparts)
return name, shortdescription
handle known entries in the CSV file
handle known entries in the CSV file
[ "handle", "known", "entries", "in", "the", "CSV", "file" ]
def extract_known_datasets(name, shortdescription, longdescription, descriptionparts): """handle known entries in the CSV file""" ## Auszahlung Maestro MC/000002270|BANKOMAT 29511 KARTE1 18.04.UM 11.34 if descriptionparts[0].startswith('Auszahlung Maestro '): logging.debug("found special case \"Auszahlung Maestro\"") name = None if len(descriptionparts)>1: shortdescription = descriptionparts[1].split(" ")[:2] ## the 1st two words of the 2nd part shortdescription = " ".join(shortdescription) else: logging.warning("could not find descriptionparts[1]; using " + \ "\"Auszahlung Maestro\" instead") shortdescription = "Auszahlung Maestro" logging.debug("shortdescr.=" + str(shortdescription)) ## Bezahlung Maestro MC/000002281|2108 K1 01.05.UM 17.43|OEBB 2483 FSA\\Ebreich sdorf 2483 ## Bezahlung Maestro MC/000002277|2108 K1 27.04.UM 17.10|OEBB 8020 FSA\\Graz 8020 ## Bezahlung Maestro MC/000002276|WIENER LINIE 3001 K1 28.04.UM 19.05|WIENER LINIEN 3001 \ ## Bezahlung Maestro MC/000002272|BRAUN 0001 K1 19.04.UM 23.21|BRAUN DE PRAUN \ ## Bezahlung Maestro MC/000002308|BILLA DANKT 6558 K1 11.06.UM 10.21|BILLA 6558 \ ## Bezahlung Maestro MC/000002337|AH10 K1 12.07.UM 11.46|Ecotec Computer Dat\\T imelkam 4850 elif descriptionparts[0].startswith('Bezahlung Maestro ') and len(descriptionparts)>2: logging.debug("found special case \"Bezahlung Maestro\"") shortdescription = descriptionparts[2].strip() ## the last part name = None ## does not really work well with Unicode ... (yet) ##if shortdescription.startswith(u"OEBB"): ## logging.debug("found special case \"ÖBB Fahrscheinautomat\"") ## #shortdescription.replace("\\",' ') ## logging.debug("sd[2]: [" + descriptionparts[2].strip() + "]") ## re.sub(ur'OEBB (\d\d\d\d) FSA\\(.*)\s\s+(\\\d)?(\d\d+).*', ur'ÖBB Fahrschein \4 \2', descriptionparts[2].strip()) elif descriptionparts[0].startswith('easykreditkarte MasterCard '): logging.debug("found special case \"easykreditkarte\"") name = None shortdescription = "MasterCard Abrechnung" elif len(descriptionparts)>1 and descriptionparts[0].startswith('Gutschrift Überweisung ') and \ descriptionparts[1].startswith('TECHNISCHE UNIVERSITAET GRAZ '): logging.debug("found special case \"Gutschrift Überweisung, TUG\"") name = "TU Graz" shortdescription = "Gehalt" elif len(descriptionparts)>1 and descriptionparts[1] == 'Vergütung für Kontoführung': logging.debug("found special case \"Vergütung für Kontoführung\"") name = "easybank" shortdescription = "Vergütung für Kontoführung" elif len(descriptionparts)>1 and descriptionparts[1] == 'Entgelt für Kontoführung': logging.debug("found special case \"Entgelt für Kontoführung\"") name = "easybank" shortdescription = "Entgelt für Kontoführung" if name: logging.debug("changed name to: " + name) if shortdescription: logging.debug("changed shortdescription to: " + shortdescription) return name, shortdescription
[ "def", "extract_known_datasets", "(", "name", ",", "shortdescription", ",", "longdescription", ",", "descriptionparts", ")", ":", "## Auszahlung Maestro MC/000002270|BANKOMAT 29511 KARTE1 18.04.UM 11.34", "if", "descriptionparts", "[", "0", "]", ".", "...
https://github.com/novoid/Memacs/blob/cc5b89a1da011a1ef08550e4da06c01881995b77/tmp/bank_statements/easybank.at/memacs-easybank.py#L133-L192
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team.py
python
RemoveCustomQuotaResult.is_invalid_user
(self)
return self._tag == 'invalid_user'
Check if the union tag is ``invalid_user``. :rtype: bool
Check if the union tag is ``invalid_user``.
[ "Check", "if", "the", "union", "tag", "is", "invalid_user", "." ]
def is_invalid_user(self): """ Check if the union tag is ``invalid_user``. :rtype: bool """ return self._tag == 'invalid_user'
[ "def", "is_invalid_user", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'invalid_user'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team.py#L9899-L9905
confluentinc/confluent-kafka-python
2ac0d72b24b14e5246445ad9ce66ec9c8828ef4e
src/confluent_kafka/serialization/__init__.py
python
StringSerializer.__init__
(self, codec='utf_8')
[]
def __init__(self, codec='utf_8'): self.codec = codec
[ "def", "__init__", "(", "self", ",", "codec", "=", "'utf_8'", ")", ":", "self", ".", "codec", "=", "codec" ]
https://github.com/confluentinc/confluent-kafka-python/blob/2ac0d72b24b14e5246445ad9ce66ec9c8828ef4e/src/confluent_kafka/serialization/__init__.py#L344-L345
BirdAPI/Google-Search-API
e091df9b0bd399fbb249b5eec78479ec27cd942d
BeautifulSoup.py
python
Tag.decompose
(self)
Recursively destroys the contents of this tree.
Recursively destroys the contents of this tree.
[ "Recursively", "destroys", "the", "contents", "of", "this", "tree", "." ]
def decompose(self): """Recursively destroys the contents of this tree.""" self.extract() if len(self.contents) == 0: return current = self.contents[0] while current is not None: next = current.next if isinstance(current, Tag): del current.contents[:] current.parent = None current.previous = None current.previousSibling = None current.next = None current.nextSibling = None current = next
[ "def", "decompose", "(", "self", ")", ":", "self", ".", "extract", "(", ")", "if", "len", "(", "self", ".", "contents", ")", "==", "0", ":", "return", "current", "=", "self", ".", "contents", "[", "0", "]", "while", "current", "is", "not", "None", ...
https://github.com/BirdAPI/Google-Search-API/blob/e091df9b0bd399fbb249b5eec78479ec27cd942d/BeautifulSoup.py#L778-L793
OpenRCE/paimei
d78f574129f9aade35af03ced08765ea2a15288c
console/modules/_PAIMEIexplorer/ExplorerTreeCtrl.py
python
ExplorerTreeCtrl.on_item_right_down
(self, event)
Grab the x/y coordinates when the right mouse button is clicked.
Grab the x/y coordinates when the right mouse button is clicked.
[ "Grab", "the", "x", "/", "y", "coordinates", "when", "the", "right", "mouse", "button", "is", "clicked", "." ]
def on_item_right_down (self, event): ''' Grab the x/y coordinates when the right mouse button is clicked. ''' self.x = event.GetX() self.y = event.GetY() item, flags = self.HitTest((self.x, self.y)) if flags & wx.TREE_HITTEST_ONITEM: self.SelectItem(item) else: self.x = None self.y = None
[ "def", "on_item_right_down", "(", "self", ",", "event", ")", ":", "self", ".", "x", "=", "event", ".", "GetX", "(", ")", "self", ".", "y", "=", "event", ".", "GetY", "(", ")", "item", ",", "flags", "=", "self", ".", "HitTest", "(", "(", "self", ...
https://github.com/OpenRCE/paimei/blob/d78f574129f9aade35af03ced08765ea2a15288c/console/modules/_PAIMEIexplorer/ExplorerTreeCtrl.py#L167-L181
scikit-multiflow/scikit-multiflow
d073a706b5006cba2584761286b7fa17e74e87be
src/skmultiflow/options/base_option.py
python
Option.get_cli_char
(self)
get_cli_char Get the parser string for the option. Returns ------- char or string The parser string for the option. Notes ----- Deprecated. Do not use this function.
get_cli_char Get the parser string for the option. Returns ------- char or string The parser string for the option. Notes ----- Deprecated. Do not use this function.
[ "get_cli_char", "Get", "the", "parser", "string", "for", "the", "option", ".", "Returns", "-------", "char", "or", "string", "The", "parser", "string", "for", "the", "option", ".", "Notes", "-----", "Deprecated", ".", "Do", "not", "use", "this", "function", ...
def get_cli_char(self): """ get_cli_char Get the parser string for the option. Returns ------- char or string The parser string for the option. Notes ----- Deprecated. Do not use this function. """ raise NotImplementedError
[ "def", "get_cli_char", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/scikit-multiflow/scikit-multiflow/blob/d073a706b5006cba2584761286b7fa17e74e87be/src/skmultiflow/options/base_option.py#L48-L63
ganglia/gmond_python_modules
2f7fcab3d27926ef4a2feb1b53c09af16a43e729
gpu/nvidia/nvidia-ml-py-3.295.00/build/lib/pynvml.py
python
nvmlDeviceGetClockInfo
(handle, type)
return c_clock.value
[]
def nvmlDeviceGetClockInfo(handle, type): c_clock = c_uint() fn = _nvmlGetFunctionPointer("nvmlDeviceGetClockInfo") ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) _nvmlCheckReturn(ret) return c_clock.value
[ "def", "nvmlDeviceGetClockInfo", "(", "handle", ",", "type", ")", ":", "c_clock", "=", "c_uint", "(", ")", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvmlDeviceGetClockInfo\"", ")", "ret", "=", "fn", "(", "handle", ",", "_nvmlClockType_t", "(", "type", ")",...
https://github.com/ganglia/gmond_python_modules/blob/2f7fcab3d27926ef4a2feb1b53c09af16a43e729/gpu/nvidia/nvidia-ml-py-3.295.00/build/lib/pynvml.py#L585-L590
TesterlifeRaymond/doraemon
d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333
venv/lib/python3.6/site-packages/pip/_vendor/pyparsing.py
python
ParseResults.get
(self, key, defaultValue=None)
Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None
Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified.
[ "Returns", "named", "result", "matching", "the", "given", "key", "or", "if", "there", "is", "no", "such", "name", "then", "returns", "the", "given", "C", "{", "defaultValue", "}", "or", "C", "{", "None", "}", "if", "no", "C", "{", "defaultValue", "}", ...
def get(self, key, defaultValue=None): """ Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None """ if key in self: return self[key] else: return defaultValue
[ "def", "get", "(", "self", ",", "key", ",", "defaultValue", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", "[", "key", "]", "else", ":", "return", "defaultValue" ]
https://github.com/TesterlifeRaymond/doraemon/blob/d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333/venv/lib/python3.6/site-packages/pip/_vendor/pyparsing.py#L540-L560