repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
codeforamerica/epa_python
epa/radinfo/radinfo.py
RADInfo.regulation
def regulation(self, column=None, value=None, **kwargs): """ Provides relevant information about applicable regulations. >>> RADInfo().regulation('title_id', 40) """ return self._resolve_call('RAD_REGULATION', column, value, **kwargs)
python
def regulation(self, column=None, value=None, **kwargs): """ Provides relevant information about applicable regulations. >>> RADInfo().regulation('title_id', 40) """ return self._resolve_call('RAD_REGULATION', column, value, **kwargs)
[ "def", "regulation", "(", "self", ",", "column", "=", "None", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_resolve_call", "(", "'RAD_REGULATION'", ",", "column", ",", "value", ",", "*", "*", "kwargs", ")" ]
Provides relevant information about applicable regulations. >>> RADInfo().regulation('title_id', 40)
[ "Provides", "relevant", "information", "about", "applicable", "regulations", "." ]
62a53da62936bea8daa487a01a52b973e9062b2c
https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/radinfo/radinfo.py#L49-L55
train
55,400
codeforamerica/epa_python
epa/radinfo/radinfo.py
RADInfo.regulatory_program
def regulatory_program(self, column=None, value=None, **kwargs): """ Identifies the regulatory authority governing a facility, and, by virtue of that identification, also identifies the regulatory program of interest and the type of facility. >>> RADInfo().regulatory_program('sec_cit_ref_flag', 'N') """ return self._resolve_call('RAD_REGULATORY_PROG', column, value, **kwargs)
python
def regulatory_program(self, column=None, value=None, **kwargs): """ Identifies the regulatory authority governing a facility, and, by virtue of that identification, also identifies the regulatory program of interest and the type of facility. >>> RADInfo().regulatory_program('sec_cit_ref_flag', 'N') """ return self._resolve_call('RAD_REGULATORY_PROG', column, value, **kwargs)
[ "def", "regulatory_program", "(", "self", ",", "column", "=", "None", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_resolve_call", "(", "'RAD_REGULATORY_PROG'", ",", "column", ",", "value", ",", "*", "*", "kwargs"...
Identifies the regulatory authority governing a facility, and, by virtue of that identification, also identifies the regulatory program of interest and the type of facility. >>> RADInfo().regulatory_program('sec_cit_ref_flag', 'N')
[ "Identifies", "the", "regulatory", "authority", "governing", "a", "facility", "and", "by", "virtue", "of", "that", "identification", "also", "identifies", "the", "regulatory", "program", "of", "interest", "and", "the", "type", "of", "facility", "." ]
62a53da62936bea8daa487a01a52b973e9062b2c
https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/radinfo/radinfo.py#L57-L66
train
55,401
Carreau/telemetry
telemetry/__init__.py
collect_basic_info
def collect_basic_info(): """ collect basic info about the system, os, python version... """ s = sys.version_info _collect(json.dumps({'sys.version_info':tuple(s)})) _collect(sys.version) return sys.version
python
def collect_basic_info(): """ collect basic info about the system, os, python version... """ s = sys.version_info _collect(json.dumps({'sys.version_info':tuple(s)})) _collect(sys.version) return sys.version
[ "def", "collect_basic_info", "(", ")", ":", "s", "=", "sys", ".", "version_info", "_collect", "(", "json", ".", "dumps", "(", "{", "'sys.version_info'", ":", "tuple", "(", "s", ")", "}", ")", ")", "_collect", "(", "sys", ".", "version", ")", "return", ...
collect basic info about the system, os, python version...
[ "collect", "basic", "info", "about", "the", "system", "os", "python", "version", "..." ]
6d456e982e3d7fd4eb6a8f43cd94925bb69ab855
https://github.com/Carreau/telemetry/blob/6d456e982e3d7fd4eb6a8f43cd94925bb69ab855/telemetry/__init__.py#L47-L55
train
55,402
Carreau/telemetry
telemetry/__init__.py
call
def call(function): """ decorator that collect function call count. """ message = 'call:%s.%s' % (function.__module__,function.__name__) @functools.wraps(function) def wrapper(*args, **kwargs): _collect(message) return function(*args, **kwargs) return wrapper
python
def call(function): """ decorator that collect function call count. """ message = 'call:%s.%s' % (function.__module__,function.__name__) @functools.wraps(function) def wrapper(*args, **kwargs): _collect(message) return function(*args, **kwargs) return wrapper
[ "def", "call", "(", "function", ")", ":", "message", "=", "'call:%s.%s'", "%", "(", "function", ".", "__module__", ",", "function", ".", "__name__", ")", "@", "functools", ".", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "*"...
decorator that collect function call count.
[ "decorator", "that", "collect", "function", "call", "count", "." ]
6d456e982e3d7fd4eb6a8f43cd94925bb69ab855
https://github.com/Carreau/telemetry/blob/6d456e982e3d7fd4eb6a8f43cd94925bb69ab855/telemetry/__init__.py#L76-L86
train
55,403
HPENetworking/topology_lib_ip
lib/topology_lib_ip/library.py
_parse_ip_addr_show
def _parse_ip_addr_show(raw_result): """ Parse the 'ip addr list dev' command raw output. :param str raw_result: os raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'os_index' : '0', 'dev' : 'eth0', 'falgs_str': 'BROADCAST,MULTICAST,UP,LOWER_UP', 'mtu': 1500, 'state': 'down', 'link_type' 'ether', 'mac_address': '00:50:56:01:2e:f6', 'inet': '20.1.1.2', 'inet_mask': '24', 'inet6': 'fe80::42:acff:fe11:2', 'inte6_mask': '64' } """ # does link exist? show_re = ( r'"(?P<dev>\S+)"\s+does not exist' ) re_result = search(show_re, raw_result) result = None if not (re_result): # match top two lines for serveral 'always there' variables show_re = ( r'\s*(?P<os_index>\d+):\s+(?P<dev>\S+):\s+<(?P<falgs_str>.*)?>.*?' r'mtu\s+(?P<mtu>\d+).+?state\s+(?P<state>\w+).*' r'\s*link/(?P<link_type>\w+)\s+(?P<mac_address>\S+)' ) re_result = search(show_re, raw_result, DOTALL) result = re_result.groupdict() # seek inet if its there show_re = ( r'((inet )\s*(?P<inet>[^/]+)/(?P<inet_mask>\d{1,2}))' ) re_result = search(show_re, raw_result) if (re_result): result.update(re_result.groupdict()) # seek inet6 if its there show_re = ( r'((?<=inet6 )(?P<inet6>[^/]+)/(?P<inet6_mask>\d{1,2}))' ) re_result = search(show_re, raw_result) if (re_result): result.update(re_result.groupdict()) # cleanup dictionary before returning for key, value in result.items(): if value is not None: if value.isdigit(): result[key] = int(value) return result
python
def _parse_ip_addr_show(raw_result): """ Parse the 'ip addr list dev' command raw output. :param str raw_result: os raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'os_index' : '0', 'dev' : 'eth0', 'falgs_str': 'BROADCAST,MULTICAST,UP,LOWER_UP', 'mtu': 1500, 'state': 'down', 'link_type' 'ether', 'mac_address': '00:50:56:01:2e:f6', 'inet': '20.1.1.2', 'inet_mask': '24', 'inet6': 'fe80::42:acff:fe11:2', 'inte6_mask': '64' } """ # does link exist? show_re = ( r'"(?P<dev>\S+)"\s+does not exist' ) re_result = search(show_re, raw_result) result = None if not (re_result): # match top two lines for serveral 'always there' variables show_re = ( r'\s*(?P<os_index>\d+):\s+(?P<dev>\S+):\s+<(?P<falgs_str>.*)?>.*?' r'mtu\s+(?P<mtu>\d+).+?state\s+(?P<state>\w+).*' r'\s*link/(?P<link_type>\w+)\s+(?P<mac_address>\S+)' ) re_result = search(show_re, raw_result, DOTALL) result = re_result.groupdict() # seek inet if its there show_re = ( r'((inet )\s*(?P<inet>[^/]+)/(?P<inet_mask>\d{1,2}))' ) re_result = search(show_re, raw_result) if (re_result): result.update(re_result.groupdict()) # seek inet6 if its there show_re = ( r'((?<=inet6 )(?P<inet6>[^/]+)/(?P<inet6_mask>\d{1,2}))' ) re_result = search(show_re, raw_result) if (re_result): result.update(re_result.groupdict()) # cleanup dictionary before returning for key, value in result.items(): if value is not None: if value.isdigit(): result[key] = int(value) return result
[ "def", "_parse_ip_addr_show", "(", "raw_result", ")", ":", "# does link exist?", "show_re", "=", "(", "r'\"(?P<dev>\\S+)\"\\s+does not exist'", ")", "re_result", "=", "search", "(", "show_re", ",", "raw_result", ")", "result", "=", "None", "if", "not", "(", "re_re...
Parse the 'ip addr list dev' command raw output. :param str raw_result: os raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'os_index' : '0', 'dev' : 'eth0', 'falgs_str': 'BROADCAST,MULTICAST,UP,LOWER_UP', 'mtu': 1500, 'state': 'down', 'link_type' 'ether', 'mac_address': '00:50:56:01:2e:f6', 'inet': '20.1.1.2', 'inet_mask': '24', 'inet6': 'fe80::42:acff:fe11:2', 'inte6_mask': '64' }
[ "Parse", "the", "ip", "addr", "list", "dev", "command", "raw", "output", "." ]
c69cc3db80d96575d787fdc903a9370d2df1c5ae
https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/lib/topology_lib_ip/library.py#L31-L96
train
55,404
HPENetworking/topology_lib_ip
lib/topology_lib_ip/library.py
interface
def interface(enode, portlbl, addr=None, up=None, shell=None): """ Configure a interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped to real port automatically. :param str addr: IPv4 or IPv6 address to add to the interface: - IPv4 address and netmask to assign to the interface in the form ``'192.168.20.20/24'``. - IPv6 address and subnets to assign to the interface in the form ``'2001::1/120'``. :param bool up: Bring up or down the interface. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert portlbl port = enode.ports[portlbl] if addr is not None: assert ip_interface(addr) cmd = 'ip addr add {addr} dev {port}'.format(addr=addr, port=port) response = enode(cmd, shell=shell) assert not response if up is not None: cmd = 'ip link set dev {port} {state}'.format( port=port, state='up' if up else 'down' ) response = enode(cmd, shell=shell) assert not response
python
def interface(enode, portlbl, addr=None, up=None, shell=None): """ Configure a interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped to real port automatically. :param str addr: IPv4 or IPv6 address to add to the interface: - IPv4 address and netmask to assign to the interface in the form ``'192.168.20.20/24'``. - IPv6 address and subnets to assign to the interface in the form ``'2001::1/120'``. :param bool up: Bring up or down the interface. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert portlbl port = enode.ports[portlbl] if addr is not None: assert ip_interface(addr) cmd = 'ip addr add {addr} dev {port}'.format(addr=addr, port=port) response = enode(cmd, shell=shell) assert not response if up is not None: cmd = 'ip link set dev {port} {state}'.format( port=port, state='up' if up else 'down' ) response = enode(cmd, shell=shell) assert not response
[ "def", "interface", "(", "enode", ",", "portlbl", ",", "addr", "=", "None", ",", "up", "=", "None", ",", "shell", "=", "None", ")", ":", "assert", "portlbl", "port", "=", "enode", ".", "ports", "[", "portlbl", "]", "if", "addr", "is", "not", "None"...
Configure a interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped to real port automatically. :param str addr: IPv4 or IPv6 address to add to the interface: - IPv4 address and netmask to assign to the interface in the form ``'192.168.20.20/24'``. - IPv6 address and subnets to assign to the interface in the form ``'2001::1/120'``. :param bool up: Bring up or down the interface. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell.
[ "Configure", "a", "interface", "." ]
c69cc3db80d96575d787fdc903a9370d2df1c5ae
https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/lib/topology_lib_ip/library.py#L149-L183
train
55,405
HPENetworking/topology_lib_ip
lib/topology_lib_ip/library.py
remove_ip
def remove_ip(enode, portlbl, addr, shell=None): """ Remove an IP address from an interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped to real port automatically. :param str addr: IPv4 or IPv6 address to remove from the interface: - IPv4 address to remove from the interface in the form ``'192.168.20.20'`` or ``'192.168.20.20/24'``. - IPv6 address to remove from the interface in the form ``'2001::1'`` or ``'2001::1/120'``. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert portlbl assert ip_interface(addr) port = enode.ports[portlbl] cmd = 'ip addr del {addr} dev {port}'.format(addr=addr, port=port) response = enode(cmd, shell=shell) assert not response
python
def remove_ip(enode, portlbl, addr, shell=None): """ Remove an IP address from an interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped to real port automatically. :param str addr: IPv4 or IPv6 address to remove from the interface: - IPv4 address to remove from the interface in the form ``'192.168.20.20'`` or ``'192.168.20.20/24'``. - IPv6 address to remove from the interface in the form ``'2001::1'`` or ``'2001::1/120'``. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert portlbl assert ip_interface(addr) port = enode.ports[portlbl] cmd = 'ip addr del {addr} dev {port}'.format(addr=addr, port=port) response = enode(cmd, shell=shell) assert not response
[ "def", "remove_ip", "(", "enode", ",", "portlbl", ",", "addr", ",", "shell", "=", "None", ")", ":", "assert", "portlbl", "assert", "ip_interface", "(", "addr", ")", "port", "=", "enode", ".", "ports", "[", "portlbl", "]", "cmd", "=", "'ip addr del {addr}...
Remove an IP address from an interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped to real port automatically. :param str addr: IPv4 or IPv6 address to remove from the interface: - IPv4 address to remove from the interface in the form ``'192.168.20.20'`` or ``'192.168.20.20/24'``. - IPv6 address to remove from the interface in the form ``'2001::1'`` or ``'2001::1/120'``. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell.
[ "Remove", "an", "IP", "address", "from", "an", "interface", "." ]
c69cc3db80d96575d787fdc903a9370d2df1c5ae
https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/lib/topology_lib_ip/library.py#L233-L258
train
55,406
HPENetworking/topology_lib_ip
lib/topology_lib_ip/library.py
add_route
def add_route(enode, route, via, shell=None): """ Add a new static route. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str route: Route to add, an IP in the form ``'192.168.20.20/24'`` or ``'2001::0/24'`` or ``'default'``. :param str via: Via for the route as an IP in the form ``'192.168.20.20/24'`` or ``'2001::0/24'``. :param shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. :type shell: str or None """ via = ip_address(via) version = '-4' if (via.version == 6) or \ (route != 'default' and ip_network(route).version == 6): version = '-6' cmd = 'ip {version} route add {route} via {via}'.format( version=version, route=route, via=via ) response = enode(cmd, shell=shell) assert not response
python
def add_route(enode, route, via, shell=None): """ Add a new static route. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str route: Route to add, an IP in the form ``'192.168.20.20/24'`` or ``'2001::0/24'`` or ``'default'``. :param str via: Via for the route as an IP in the form ``'192.168.20.20/24'`` or ``'2001::0/24'``. :param shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. :type shell: str or None """ via = ip_address(via) version = '-4' if (via.version == 6) or \ (route != 'default' and ip_network(route).version == 6): version = '-6' cmd = 'ip {version} route add {route} via {via}'.format( version=version, route=route, via=via ) response = enode(cmd, shell=shell) assert not response
[ "def", "add_route", "(", "enode", ",", "route", ",", "via", ",", "shell", "=", "None", ")", ":", "via", "=", "ip_address", "(", "via", ")", "version", "=", "'-4'", "if", "(", "via", ".", "version", "==", "6", ")", "or", "(", "route", "!=", "'defa...
Add a new static route. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str route: Route to add, an IP in the form ``'192.168.20.20/24'`` or ``'2001::0/24'`` or ``'default'``. :param str via: Via for the route as an IP in the form ``'192.168.20.20/24'`` or ``'2001::0/24'``. :param shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. :type shell: str or None
[ "Add", "a", "new", "static", "route", "." ]
c69cc3db80d96575d787fdc903a9370d2df1c5ae
https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/lib/topology_lib_ip/library.py#L261-L287
train
55,407
HPENetworking/topology_lib_ip
lib/topology_lib_ip/library.py
add_link_type_vlan
def add_link_type_vlan(enode, portlbl, name, vlan_id, shell=None): """ Add a new virtual link with the type set to VLAN. Creates a new vlan device {name} on device {port}. Will raise an exception if value is already assigned. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped automatically. :param str name: specifies the name of the new virtual device. :param str vlan_id: specifies the VLAN identifier. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert name if name in enode.ports: raise ValueError('Port {name} already exists'.format(name=name)) assert portlbl assert vlan_id port = enode.ports[portlbl] cmd = 'ip link add link {dev} name {name} type vlan id {vlan_id}'.format( dev=port, name=name, vlan_id=vlan_id) response = enode(cmd, shell=shell) assert not response, 'Cannot add virtual link {name}'.format(name=name) enode.ports[name] = name
python
def add_link_type_vlan(enode, portlbl, name, vlan_id, shell=None): """ Add a new virtual link with the type set to VLAN. Creates a new vlan device {name} on device {port}. Will raise an exception if value is already assigned. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped automatically. :param str name: specifies the name of the new virtual device. :param str vlan_id: specifies the VLAN identifier. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert name if name in enode.ports: raise ValueError('Port {name} already exists'.format(name=name)) assert portlbl assert vlan_id port = enode.ports[portlbl] cmd = 'ip link add link {dev} name {name} type vlan id {vlan_id}'.format( dev=port, name=name, vlan_id=vlan_id) response = enode(cmd, shell=shell) assert not response, 'Cannot add virtual link {name}'.format(name=name) enode.ports[name] = name
[ "def", "add_link_type_vlan", "(", "enode", ",", "portlbl", ",", "name", ",", "vlan_id", ",", "shell", "=", "None", ")", ":", "assert", "name", "if", "name", "in", "enode", ".", "ports", ":", "raise", "ValueError", "(", "'Port {name} already exists'", ".", ...
Add a new virtual link with the type set to VLAN. Creates a new vlan device {name} on device {port}. Will raise an exception if value is already assigned. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped automatically. :param str name: specifies the name of the new virtual device. :param str vlan_id: specifies the VLAN identifier. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell.
[ "Add", "a", "new", "virtual", "link", "with", "the", "type", "set", "to", "VLAN", "." ]
c69cc3db80d96575d787fdc903a9370d2df1c5ae
https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/lib/topology_lib_ip/library.py#L290-L320
train
55,408
HPENetworking/topology_lib_ip
lib/topology_lib_ip/library.py
remove_link_type_vlan
def remove_link_type_vlan(enode, name, shell=None): """ Delete a virtual link. Deletes a vlan device with the name {name}. Will raise an expection if the port is not already present. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str name: specifies the name of the new virtual device. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert name if name not in enode.ports: raise ValueError('Port {name} doesn\'t exists'.format(name=name)) cmd = 'ip link del link dev {name}'.format(name=name) response = enode(cmd, shell=shell) assert not response, 'Cannot remove virtual link {name}'.format(name=name) del enode.ports[name]
python
def remove_link_type_vlan(enode, name, shell=None): """ Delete a virtual link. Deletes a vlan device with the name {name}. Will raise an expection if the port is not already present. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str name: specifies the name of the new virtual device. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert name if name not in enode.ports: raise ValueError('Port {name} doesn\'t exists'.format(name=name)) cmd = 'ip link del link dev {name}'.format(name=name) response = enode(cmd, shell=shell) assert not response, 'Cannot remove virtual link {name}'.format(name=name) del enode.ports[name]
[ "def", "remove_link_type_vlan", "(", "enode", ",", "name", ",", "shell", "=", "None", ")", ":", "assert", "name", "if", "name", "not", "in", "enode", ".", "ports", ":", "raise", "ValueError", "(", "'Port {name} doesn\\'t exists'", ".", "format", "(", "name",...
Delete a virtual link. Deletes a vlan device with the name {name}. Will raise an expection if the port is not already present. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str name: specifies the name of the new virtual device. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell.
[ "Delete", "a", "virtual", "link", "." ]
c69cc3db80d96575d787fdc903a9370d2df1c5ae
https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/lib/topology_lib_ip/library.py#L323-L346
train
55,409
HPENetworking/topology_lib_ip
lib/topology_lib_ip/library.py
show_interface
def show_interface(enode, dev, shell=None): """ Show the configured parameters and stats of an interface. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str dev: Unix network device name. Ex 1, 2, 3.. :rtype: dict :return: A combined dictionary as returned by both :func:`topology_lib_ip.parser._parse_ip_addr_show` :func:`topology_lib_ip.parser._parse_ip_stats_link_show` """ assert dev cmd = 'ip addr list dev {ldev}'.format(ldev=dev) response = enode(cmd, shell=shell) first_half_dict = _parse_ip_addr_show(response) d = None if (first_half_dict): cmd = 'ip -s link list dev {ldev}'.format(ldev=dev) response = enode(cmd, shell=shell) second_half_dict = _parse_ip_stats_link_show(response) d = first_half_dict.copy() d.update(second_half_dict) return d
python
def show_interface(enode, dev, shell=None): """ Show the configured parameters and stats of an interface. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str dev: Unix network device name. Ex 1, 2, 3.. :rtype: dict :return: A combined dictionary as returned by both :func:`topology_lib_ip.parser._parse_ip_addr_show` :func:`topology_lib_ip.parser._parse_ip_stats_link_show` """ assert dev cmd = 'ip addr list dev {ldev}'.format(ldev=dev) response = enode(cmd, shell=shell) first_half_dict = _parse_ip_addr_show(response) d = None if (first_half_dict): cmd = 'ip -s link list dev {ldev}'.format(ldev=dev) response = enode(cmd, shell=shell) second_half_dict = _parse_ip_stats_link_show(response) d = first_half_dict.copy() d.update(second_half_dict) return d
[ "def", "show_interface", "(", "enode", ",", "dev", ",", "shell", "=", "None", ")", ":", "assert", "dev", "cmd", "=", "'ip addr list dev {ldev}'", ".", "format", "(", "ldev", "=", "dev", ")", "response", "=", "enode", "(", "cmd", ",", "shell", "=", "she...
Show the configured parameters and stats of an interface. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str dev: Unix network device name. Ex 1, 2, 3.. :rtype: dict :return: A combined dictionary as returned by both :func:`topology_lib_ip.parser._parse_ip_addr_show` :func:`topology_lib_ip.parser._parse_ip_stats_link_show`
[ "Show", "the", "configured", "parameters", "and", "stats", "of", "an", "interface", "." ]
c69cc3db80d96575d787fdc903a9370d2df1c5ae
https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/lib/topology_lib_ip/library.py#L349-L376
train
55,410
jasedit/pymmd
pymmd/download.py
build_mmd
def build_mmd(target_folder=DEFAULT_LIBRARY_DIR): """Build and install the MultiMarkdown shared library.""" mmd_dir = tempfile.mkdtemp() mmd_repo = pygit2.clone_repository('https://github.com/jasedit/MultiMarkdown-5', mmd_dir, checkout_branch='fix_windows') mmd_repo.init_submodules() mmd_repo.update_submodules() build_dir = os.path.join(mmd_dir, 'build') old_pwd = os.getcwd() os.chdir(build_dir) cmake_cmd = ['cmake', '-DCMAKE_BUILD_TYPE=Release', '-DSHAREDBUILD=1', '..'] if platform.system() == 'Windows': is_64bit = platform.architecture()[0] == '64bit' generator = 'Visual Studio 14 2015{0}'.format(' Win64' if is_64bit else '') cmake_cmd.insert(-1, '-G') cmake_cmd.insert(-1, '{0}'.format(generator)) subprocess.call(cmake_cmd) PLATFORM_BUILDS[platform.system()]() lib_file = 'libMultiMarkdown' + SHLIB_EXT[platform.system()] if not os.path.exists(target_folder): os.mkdir(target_folder) src = os.path.join(build_dir, SHLIB_PREFIX[platform.system()], lib_file) dest = os.path.join(target_folder, lib_file) shutil.copyfile(src, dest) os.chdir(old_pwd) shutil.rmtree(mmd_dir, ignore_errors=True)
python
def build_mmd(target_folder=DEFAULT_LIBRARY_DIR): """Build and install the MultiMarkdown shared library.""" mmd_dir = tempfile.mkdtemp() mmd_repo = pygit2.clone_repository('https://github.com/jasedit/MultiMarkdown-5', mmd_dir, checkout_branch='fix_windows') mmd_repo.init_submodules() mmd_repo.update_submodules() build_dir = os.path.join(mmd_dir, 'build') old_pwd = os.getcwd() os.chdir(build_dir) cmake_cmd = ['cmake', '-DCMAKE_BUILD_TYPE=Release', '-DSHAREDBUILD=1', '..'] if platform.system() == 'Windows': is_64bit = platform.architecture()[0] == '64bit' generator = 'Visual Studio 14 2015{0}'.format(' Win64' if is_64bit else '') cmake_cmd.insert(-1, '-G') cmake_cmd.insert(-1, '{0}'.format(generator)) subprocess.call(cmake_cmd) PLATFORM_BUILDS[platform.system()]() lib_file = 'libMultiMarkdown' + SHLIB_EXT[platform.system()] if not os.path.exists(target_folder): os.mkdir(target_folder) src = os.path.join(build_dir, SHLIB_PREFIX[platform.system()], lib_file) dest = os.path.join(target_folder, lib_file) shutil.copyfile(src, dest) os.chdir(old_pwd) shutil.rmtree(mmd_dir, ignore_errors=True)
[ "def", "build_mmd", "(", "target_folder", "=", "DEFAULT_LIBRARY_DIR", ")", ":", "mmd_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "mmd_repo", "=", "pygit2", ".", "clone_repository", "(", "'https://github.com/jasedit/MultiMarkdown-5'", ",", "mmd_dir", ",", "check...
Build and install the MultiMarkdown shared library.
[ "Build", "and", "install", "the", "MultiMarkdown", "shared", "library", "." ]
37b5a717241b837ca15b8a4d4cc3c06b4456bfbd
https://github.com/jasedit/pymmd/blob/37b5a717241b837ca15b8a4d4cc3c06b4456bfbd/pymmd/download.py#L41-L68
train
55,411
jessamynsmith/pipreq
pipreq/command.py
Command.generate_requirements_files
def generate_requirements_files(self, base_dir='.'): """ Generate set of requirements files for config """ print("Creating requirements files\n") # TODO How to deal with requirements that are not simple, e.g. a github url shared = self._get_shared_section() requirements_dir = self._make_requirements_directory(base_dir) for section in self.config.sections(): if section == 'metadata': continue requirements = {} for option in self.config.options(section): requirements[option] = self.config.get(section, option) if not requirements: # No need to write out an empty file continue filename = os.path.join(requirements_dir, '%s.txt' % section) self._write_requirements_file(shared, section, requirements, filename)
python
def generate_requirements_files(self, base_dir='.'): """ Generate set of requirements files for config """ print("Creating requirements files\n") # TODO How to deal with requirements that are not simple, e.g. a github url shared = self._get_shared_section() requirements_dir = self._make_requirements_directory(base_dir) for section in self.config.sections(): if section == 'metadata': continue requirements = {} for option in self.config.options(section): requirements[option] = self.config.get(section, option) if not requirements: # No need to write out an empty file continue filename = os.path.join(requirements_dir, '%s.txt' % section) self._write_requirements_file(shared, section, requirements, filename)
[ "def", "generate_requirements_files", "(", "self", ",", "base_dir", "=", "'.'", ")", ":", "print", "(", "\"Creating requirements files\\n\"", ")", "# TODO How to deal with requirements that are not simple, e.g. a github url", "shared", "=", "self", ".", "_get_shared_section", ...
Generate set of requirements files for config
[ "Generate", "set", "of", "requirements", "files", "for", "config" ]
4081c1238722166445f58ae57e939207f8a6fb83
https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L76-L100
train
55,412
jessamynsmith/pipreq
pipreq/command.py
Command._write_default_sections
def _write_default_sections(self): """ Starting from scratch, so create a default rc file """ self.config.add_section('metadata') self.config.set('metadata', 'shared', 'common') self.config.add_section('common') self.config.add_section('development') self.config.add_section('production')
python
def _write_default_sections(self): """ Starting from scratch, so create a default rc file """ self.config.add_section('metadata') self.config.set('metadata', 'shared', 'common') self.config.add_section('common') self.config.add_section('development') self.config.add_section('production')
[ "def", "_write_default_sections", "(", "self", ")", ":", "self", ".", "config", ".", "add_section", "(", "'metadata'", ")", "self", ".", "config", ".", "set", "(", "'metadata'", ",", "'shared'", ",", "'common'", ")", "self", ".", "config", ".", "add_sectio...
Starting from scratch, so create a default rc file
[ "Starting", "from", "scratch", "so", "create", "a", "default", "rc", "file" ]
4081c1238722166445f58ae57e939207f8a6fb83
https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L121-L127
train
55,413
jessamynsmith/pipreq
pipreq/command.py
Command._parse_requirements
def _parse_requirements(self, input): """ Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silently ignored. Returns a tuple of tuples, where each inner tuple is: (package, version) """ results = [] for line in input: (package, version) = self._parse_line(line) if package: results.append((package, version)) return tuple(results)
python
def _parse_requirements(self, input): """ Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silently ignored. Returns a tuple of tuples, where each inner tuple is: (package, version) """ results = [] for line in input: (package, version) = self._parse_line(line) if package: results.append((package, version)) return tuple(results)
[ "def", "_parse_requirements", "(", "self", ",", "input", ")", ":", "results", "=", "[", "]", "for", "line", "in", "input", ":", "(", "package", ",", "version", ")", "=", "self", ".", "_parse_line", "(", "line", ")", "if", "package", ":", "results", "...
Parse a list of requirements specifications. Lines that look like "foobar==1.0" are parsed; all other lines are silently ignored. Returns a tuple of tuples, where each inner tuple is: (package, version)
[ "Parse", "a", "list", "of", "requirements", "specifications", ".", "Lines", "that", "look", "like", "foobar", "==", "1", ".", "0", "are", "parsed", ";", "all", "other", "lines", "are", "silently", "ignored", "." ]
4081c1238722166445f58ae57e939207f8a6fb83
https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L129-L144
train
55,414
jessamynsmith/pipreq
pipreq/command.py
Command.create_rc_file
def create_rc_file(self, packages): """ Create a set of requirements files for config """ print("Creating rcfile '%s'\n" % self.rc_filename) # TODO bug with == in config file if not self.config.sections(): self._write_default_sections() sections = {} section_text = [] for i, section in enumerate(self.config.sections()): if section == 'metadata': continue sections[i] = section section_text.append('%s. %s' % (i, section)) section_text = ' / '.join(section_text) self._remap_stdin() package_names = set() lines = packages.readlines() requirements = self._parse_requirements(lines) for (package, version) in requirements: package_names.add(package) section, configured_version = self._get_option(package) # Package already exists in configuration if section: # If there is a configured version, update it. If not, leave it unversioned. if configured_version: if configured_version != version: print("Updating '%s' version from '%s' to '%s'" % (package, configured_version, version)) self.config.set(section, package, version) continue section = self._get_section(package, sections, section_text) self._set_option(section, package, version) for section in self.config.sections(): if section == 'metadata': continue for option in self.config.options(section): if option not in package_names: print("Removing package '%s'" % option) self.config.remove_option(section, option) rc_file = open(self.rc_filename, 'w+') self.config.write(rc_file) rc_file.close()
python
def create_rc_file(self, packages): """ Create a set of requirements files for config """ print("Creating rcfile '%s'\n" % self.rc_filename) # TODO bug with == in config file if not self.config.sections(): self._write_default_sections() sections = {} section_text = [] for i, section in enumerate(self.config.sections()): if section == 'metadata': continue sections[i] = section section_text.append('%s. %s' % (i, section)) section_text = ' / '.join(section_text) self._remap_stdin() package_names = set() lines = packages.readlines() requirements = self._parse_requirements(lines) for (package, version) in requirements: package_names.add(package) section, configured_version = self._get_option(package) # Package already exists in configuration if section: # If there is a configured version, update it. If not, leave it unversioned. if configured_version: if configured_version != version: print("Updating '%s' version from '%s' to '%s'" % (package, configured_version, version)) self.config.set(section, package, version) continue section = self._get_section(package, sections, section_text) self._set_option(section, package, version) for section in self.config.sections(): if section == 'metadata': continue for option in self.config.options(section): if option not in package_names: print("Removing package '%s'" % option) self.config.remove_option(section, option) rc_file = open(self.rc_filename, 'w+') self.config.write(rc_file) rc_file.close()
[ "def", "create_rc_file", "(", "self", ",", "packages", ")", ":", "print", "(", "\"Creating rcfile '%s'\\n\"", "%", "self", ".", "rc_filename", ")", "# TODO bug with == in config file", "if", "not", "self", ".", "config", ".", "sections", "(", ")", ":", "self", ...
Create a set of requirements files for config
[ "Create", "a", "set", "of", "requirements", "files", "for", "config" ]
4081c1238722166445f58ae57e939207f8a6fb83
https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L156-L205
train
55,415
jessamynsmith/pipreq
pipreq/command.py
Command.upgrade_packages
def upgrade_packages(self, packages): """ Upgrade all specified packages to latest version """ print("Upgrading packages\n") package_list = [] requirements = self._parse_requirements(packages.readlines()) for (package, version) in requirements: package_list.append(package) if package_list: args = [ "pip", "install", "-U", ] args.extend(package_list) subprocess.check_call(args) else: print("No packages to upgrade")
python
def upgrade_packages(self, packages): """ Upgrade all specified packages to latest version """ print("Upgrading packages\n") package_list = [] requirements = self._parse_requirements(packages.readlines()) for (package, version) in requirements: package_list.append(package) if package_list: args = [ "pip", "install", "-U", ] args.extend(package_list) subprocess.check_call(args) else: print("No packages to upgrade")
[ "def", "upgrade_packages", "(", "self", ",", "packages", ")", ":", "print", "(", "\"Upgrading packages\\n\"", ")", "package_list", "=", "[", "]", "requirements", "=", "self", ".", "_parse_requirements", "(", "packages", ".", "readlines", "(", ")", ")", "for", ...
Upgrade all specified packages to latest version
[ "Upgrade", "all", "specified", "packages", "to", "latest", "version" ]
4081c1238722166445f58ae57e939207f8a6fb83
https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L207-L226
train
55,416
jessamynsmith/pipreq
pipreq/command.py
Command.determine_extra_packages
def determine_extra_packages(self, packages): """ Return all packages that are installed, but missing from "packages". Return value is a tuple of the package names """ args = [ "pip", "freeze", ] installed = subprocess.check_output(args, universal_newlines=True) installed_list = set() lines = installed.strip().split('\n') for (package, version) in self._parse_requirements(lines): installed_list.add(package) package_list = set() for (package, version) in self._parse_requirements(packages.readlines()): package_list.add(package) removal_list = installed_list - package_list return tuple(removal_list)
python
def determine_extra_packages(self, packages): """ Return all packages that are installed, but missing from "packages". Return value is a tuple of the package names """ args = [ "pip", "freeze", ] installed = subprocess.check_output(args, universal_newlines=True) installed_list = set() lines = installed.strip().split('\n') for (package, version) in self._parse_requirements(lines): installed_list.add(package) package_list = set() for (package, version) in self._parse_requirements(packages.readlines()): package_list.add(package) removal_list = installed_list - package_list return tuple(removal_list)
[ "def", "determine_extra_packages", "(", "self", ",", "packages", ")", ":", "args", "=", "[", "\"pip\"", ",", "\"freeze\"", ",", "]", "installed", "=", "subprocess", ".", "check_output", "(", "args", ",", "universal_newlines", "=", "True", ")", "installed_list"...
Return all packages that are installed, but missing from "packages". Return value is a tuple of the package names
[ "Return", "all", "packages", "that", "are", "installed", "but", "missing", "from", "packages", ".", "Return", "value", "is", "a", "tuple", "of", "the", "package", "names" ]
4081c1238722166445f58ae57e939207f8a6fb83
https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L228-L248
train
55,417
jessamynsmith/pipreq
pipreq/command.py
Command.remove_extra_packages
def remove_extra_packages(self, packages, dry_run=False): """ Remove all packages missing from list """ removal_list = self.determine_extra_packages(packages) if not removal_list: print("No packages to be removed") else: if dry_run: print("The following packages would be removed:\n %s\n" % "\n ".join(removal_list)) else: print("Removing packages\n") args = [ "pip", "uninstall", "-y", ] args.extend(list(removal_list)) subprocess.check_call(args)
python
def remove_extra_packages(self, packages, dry_run=False): """ Remove all packages missing from list """ removal_list = self.determine_extra_packages(packages) if not removal_list: print("No packages to be removed") else: if dry_run: print("The following packages would be removed:\n %s\n" % "\n ".join(removal_list)) else: print("Removing packages\n") args = [ "pip", "uninstall", "-y", ] args.extend(list(removal_list)) subprocess.check_call(args)
[ "def", "remove_extra_packages", "(", "self", ",", "packages", ",", "dry_run", "=", "False", ")", ":", "removal_list", "=", "self", ".", "determine_extra_packages", "(", "packages", ")", "if", "not", "removal_list", ":", "print", "(", "\"No packages to be removed\"...
Remove all packages missing from list
[ "Remove", "all", "packages", "missing", "from", "list" ]
4081c1238722166445f58ae57e939207f8a6fb83
https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L250-L268
train
55,418
randomir/plucky
plucky/structural.py
pluckable.rewrap
def rewrap(self, **kwargs): """Inplace constructor. Depending on `self.inplace`, rewrap `obj`, or just update internal vars, possibly including the `obj`. """ if self.inplace: for key, val in kwargs.items(): setattr(self, key, val) return self else: for key in ['obj', 'default', 'skipmissing', 'inplace', 'empty']: kwargs.setdefault(key, getattr(self, key)) return pluckable(**kwargs)
python
def rewrap(self, **kwargs): """Inplace constructor. Depending on `self.inplace`, rewrap `obj`, or just update internal vars, possibly including the `obj`. """ if self.inplace: for key, val in kwargs.items(): setattr(self, key, val) return self else: for key in ['obj', 'default', 'skipmissing', 'inplace', 'empty']: kwargs.setdefault(key, getattr(self, key)) return pluckable(**kwargs)
[ "def", "rewrap", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "inplace", ":", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "val", ")", "return", "self", "e...
Inplace constructor. Depending on `self.inplace`, rewrap `obj`, or just update internal vars, possibly including the `obj`.
[ "Inplace", "constructor", ".", "Depending", "on", "self", ".", "inplace", "rewrap", "obj", "or", "just", "update", "internal", "vars", "possibly", "including", "the", "obj", "." ]
16b7b59aa19d619d8e619dc15dc7eeffc9fe078a
https://github.com/randomir/plucky/blob/16b7b59aa19d619d8e619dc15dc7eeffc9fe078a/plucky/structural.py#L52-L63
train
55,419
randomir/plucky
plucky/structural.py
pluckable._sliced_list
def _sliced_list(self, selector): """For slice selectors operating on lists, we need to handle them differently, depending on ``skipmissing``. In explicit mode, we may have to expand the list with ``default`` values. """ if self.skipmissing: return self.obj[selector] # TODO: can be optimized by observing list bounds keys = xrange(selector.start or 0, selector.stop or sys.maxint, selector.step or 1) res = [] for key in keys: self._append(self.obj, key, res, skipmissing=False) return res
python
def _sliced_list(self, selector): """For slice selectors operating on lists, we need to handle them differently, depending on ``skipmissing``. In explicit mode, we may have to expand the list with ``default`` values. """ if self.skipmissing: return self.obj[selector] # TODO: can be optimized by observing list bounds keys = xrange(selector.start or 0, selector.stop or sys.maxint, selector.step or 1) res = [] for key in keys: self._append(self.obj, key, res, skipmissing=False) return res
[ "def", "_sliced_list", "(", "self", ",", "selector", ")", ":", "if", "self", ".", "skipmissing", ":", "return", "self", ".", "obj", "[", "selector", "]", "# TODO: can be optimized by observing list bounds", "keys", "=", "xrange", "(", "selector", ".", "start", ...
For slice selectors operating on lists, we need to handle them differently, depending on ``skipmissing``. In explicit mode, we may have to expand the list with ``default`` values.
[ "For", "slice", "selectors", "operating", "on", "lists", "we", "need", "to", "handle", "them", "differently", "depending", "on", "skipmissing", ".", "In", "explicit", "mode", "we", "may", "have", "to", "expand", "the", "list", "with", "default", "values", "....
16b7b59aa19d619d8e619dc15dc7eeffc9fe078a
https://github.com/randomir/plucky/blob/16b7b59aa19d619d8e619dc15dc7eeffc9fe078a/plucky/structural.py#L109-L124
train
55,420
scivision/sciencedates
sciencedates/tz.py
forceutc
def forceutc(t: Union[str, datetime.datetime, datetime.date, np.datetime64]) -> Union[datetime.datetime, datetime.date]: """ Add UTC to datetime-naive and convert to UTC for datetime aware input: python datetime (naive, utc, non-utc) or Numpy datetime64 #FIXME add Pandas and AstroPy time classes output: utc datetime """ # need to passthrough None for simpler external logic. # %% polymorph to datetime if isinstance(t, str): t = parse(t) elif isinstance(t, np.datetime64): t = t.astype(datetime.datetime) elif isinstance(t, datetime.datetime): pass elif isinstance(t, datetime.date): return t elif isinstance(t, (np.ndarray, list, tuple)): return np.asarray([forceutc(T) for T in t]) else: raise TypeError('datetime only input') # %% enforce UTC on datetime if t.tzinfo is None: # datetime-naive t = t.replace(tzinfo=UTC) else: # datetime-aware t = t.astimezone(UTC) # changes timezone, preserving absolute time. E.g. noon EST = 5PM UTC return t
python
def forceutc(t: Union[str, datetime.datetime, datetime.date, np.datetime64]) -> Union[datetime.datetime, datetime.date]: """ Add UTC to datetime-naive and convert to UTC for datetime aware input: python datetime (naive, utc, non-utc) or Numpy datetime64 #FIXME add Pandas and AstroPy time classes output: utc datetime """ # need to passthrough None for simpler external logic. # %% polymorph to datetime if isinstance(t, str): t = parse(t) elif isinstance(t, np.datetime64): t = t.astype(datetime.datetime) elif isinstance(t, datetime.datetime): pass elif isinstance(t, datetime.date): return t elif isinstance(t, (np.ndarray, list, tuple)): return np.asarray([forceutc(T) for T in t]) else: raise TypeError('datetime only input') # %% enforce UTC on datetime if t.tzinfo is None: # datetime-naive t = t.replace(tzinfo=UTC) else: # datetime-aware t = t.astimezone(UTC) # changes timezone, preserving absolute time. E.g. noon EST = 5PM UTC return t
[ "def", "forceutc", "(", "t", ":", "Union", "[", "str", ",", "datetime", ".", "datetime", ",", "datetime", ".", "date", ",", "np", ".", "datetime64", "]", ")", "->", "Union", "[", "datetime", ".", "datetime", ",", "datetime", ".", "date", "]", ":", ...
Add UTC to datetime-naive and convert to UTC for datetime aware input: python datetime (naive, utc, non-utc) or Numpy datetime64 #FIXME add Pandas and AstroPy time classes output: utc datetime
[ "Add", "UTC", "to", "datetime", "-", "naive", "and", "convert", "to", "UTC", "for", "datetime", "aware" ]
a713389e027b42d26875cf227450a5d7c6696000
https://github.com/scivision/sciencedates/blob/a713389e027b42d26875cf227450a5d7c6696000/sciencedates/tz.py#L8-L35
train
55,421
e7dal/bubble3
behave4cmd0/command_steps.py
step_a_new_working_directory
def step_a_new_working_directory(context): """ Creates a new, empty working directory """ command_util.ensure_context_attribute_exists(context, "workdir", None) command_util.ensure_workdir_exists(context) shutil.rmtree(context.workdir, ignore_errors=True)
python
def step_a_new_working_directory(context): """ Creates a new, empty working directory """ command_util.ensure_context_attribute_exists(context, "workdir", None) command_util.ensure_workdir_exists(context) shutil.rmtree(context.workdir, ignore_errors=True)
[ "def", "step_a_new_working_directory", "(", "context", ")", ":", "command_util", ".", "ensure_context_attribute_exists", "(", "context", ",", "\"workdir\"", ",", "None", ")", "command_util", ".", "ensure_workdir_exists", "(", "context", ")", "shutil", ".", "rmtree", ...
Creates a new, empty working directory
[ "Creates", "a", "new", "empty", "working", "directory" ]
59c735281a95b44f6263a25f4d6ce24fca520082
https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/command_steps.py#L79-L85
train
55,422
e7dal/bubble3
behave4cmd0/command_steps.py
step_use_curdir_as_working_directory
def step_use_curdir_as_working_directory(context): """ Uses the current directory as working directory """ context.workdir = os.path.abspath(".") command_util.ensure_workdir_exists(context)
python
def step_use_curdir_as_working_directory(context): """ Uses the current directory as working directory """ context.workdir = os.path.abspath(".") command_util.ensure_workdir_exists(context)
[ "def", "step_use_curdir_as_working_directory", "(", "context", ")", ":", "context", ".", "workdir", "=", "os", ".", "path", ".", "abspath", "(", "\".\"", ")", "command_util", ".", "ensure_workdir_exists", "(", "context", ")" ]
Uses the current directory as working directory
[ "Uses", "the", "current", "directory", "as", "working", "directory" ]
59c735281a95b44f6263a25f4d6ce24fca520082
https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/command_steps.py#L88-L93
train
55,423
e7dal/bubble3
behave4cmd0/command_steps.py
step_an_empty_file_named_filename
def step_an_empty_file_named_filename(context, filename): """ Creates an empty file. """ assert not os.path.isabs(filename) command_util.ensure_workdir_exists(context) filename2 = os.path.join(context.workdir, filename) pathutil.create_textfile_with_contents(filename2, "")
python
def step_an_empty_file_named_filename(context, filename): """ Creates an empty file. """ assert not os.path.isabs(filename) command_util.ensure_workdir_exists(context) filename2 = os.path.join(context.workdir, filename) pathutil.create_textfile_with_contents(filename2, "")
[ "def", "step_an_empty_file_named_filename", "(", "context", ",", "filename", ")", ":", "assert", "not", "os", ".", "path", ".", "isabs", "(", "filename", ")", "command_util", ".", "ensure_workdir_exists", "(", "context", ")", "filename2", "=", "os", ".", "path...
Creates an empty file.
[ "Creates", "an", "empty", "file", "." ]
59c735281a95b44f6263a25f4d6ce24fca520082
https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/command_steps.py#L122-L129
train
55,424
e7dal/bubble3
behave4cmd0/command_steps.py
step_i_run_command
def step_i_run_command(context, command): """ Run a command as subprocess, collect its output and returncode. """ command_util.ensure_workdir_exists(context) context.command_result = command_shell.run(command, cwd=context.workdir) command_util.workdir_save_coverage_files(context.workdir) if False and DEBUG: print(u"run_command: {0}".format(command)) print(u"run_command.output {0}".format(context.command_result.output))
python
def step_i_run_command(context, command): """ Run a command as subprocess, collect its output and returncode. """ command_util.ensure_workdir_exists(context) context.command_result = command_shell.run(command, cwd=context.workdir) command_util.workdir_save_coverage_files(context.workdir) if False and DEBUG: print(u"run_command: {0}".format(command)) print(u"run_command.output {0}".format(context.command_result.output))
[ "def", "step_i_run_command", "(", "context", ",", "command", ")", ":", "command_util", ".", "ensure_workdir_exists", "(", "context", ")", "context", ".", "command_result", "=", "command_shell", ".", "run", "(", "command", ",", "cwd", "=", "context", ".", "work...
Run a command as subprocess, collect its output and returncode.
[ "Run", "a", "command", "as", "subprocess", "collect", "its", "output", "and", "returncode", "." ]
59c735281a95b44f6263a25f4d6ce24fca520082
https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/command_steps.py#L136-L145
train
55,425
e7dal/bubble3
behave4cmd0/command_steps.py
step_command_output_should_contain_exactly_text
def step_command_output_should_contain_exactly_text(context, text): """ Verifies that the command output of the last command contains the expected text. .. code-block:: gherkin When I run "echo Hello" Then the command output should contain "Hello" """ expected_text = text if "{__WORKDIR__}" in text or "{__CWD__}" in text: expected_text = textutil.template_substitute(text, __WORKDIR__ = posixpath_normpath(context.workdir), __CWD__ = posixpath_normpath(os.getcwd()) ) actual_output = context.command_result.output textutil.assert_text_should_contain_exactly(actual_output, expected_text)
python
def step_command_output_should_contain_exactly_text(context, text): """ Verifies that the command output of the last command contains the expected text. .. code-block:: gherkin When I run "echo Hello" Then the command output should contain "Hello" """ expected_text = text if "{__WORKDIR__}" in text or "{__CWD__}" in text: expected_text = textutil.template_substitute(text, __WORKDIR__ = posixpath_normpath(context.workdir), __CWD__ = posixpath_normpath(os.getcwd()) ) actual_output = context.command_result.output textutil.assert_text_should_contain_exactly(actual_output, expected_text)
[ "def", "step_command_output_should_contain_exactly_text", "(", "context", ",", "text", ")", ":", "expected_text", "=", "text", "if", "\"{__WORKDIR__}\"", "in", "text", "or", "\"{__CWD__}\"", "in", "text", ":", "expected_text", "=", "textutil", ".", "template_substitut...
Verifies that the command output of the last command contains the expected text. .. code-block:: gherkin When I run "echo Hello" Then the command output should contain "Hello"
[ "Verifies", "that", "the", "command", "output", "of", "the", "last", "command", "contains", "the", "expected", "text", "." ]
59c735281a95b44f6263a25f4d6ce24fca520082
https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/command_steps.py#L253-L270
train
55,426
paltman-archive/nashvegas
nashvegas/utils.py
get_file_list
def get_file_list(path, max_depth=1, cur_depth=0): """ Recursively returns a list of all files up to ``max_depth`` in a directory. """ if os.path.exists(path): for name in os.listdir(path): if name.startswith('.'): continue full_path = os.path.join(path, name) if os.path.isdir(full_path): if cur_depth == max_depth: continue file_list = get_file_list(full_path, max_depth, cur_depth + 1) for result in file_list: yield result else: yield full_path
python
def get_file_list(path, max_depth=1, cur_depth=0): """ Recursively returns a list of all files up to ``max_depth`` in a directory. """ if os.path.exists(path): for name in os.listdir(path): if name.startswith('.'): continue full_path = os.path.join(path, name) if os.path.isdir(full_path): if cur_depth == max_depth: continue file_list = get_file_list(full_path, max_depth, cur_depth + 1) for result in file_list: yield result else: yield full_path
[ "def", "get_file_list", "(", "path", ",", "max_depth", "=", "1", ",", "cur_depth", "=", "0", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "for", "name", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "name", ...
Recursively returns a list of all files up to ``max_depth`` in a directory.
[ "Recursively", "returns", "a", "list", "of", "all", "files", "up", "to", "max_depth", "in", "a", "directory", "." ]
14e904a3f5b87e878cd053b554e76e85943d1c11
https://github.com/paltman-archive/nashvegas/blob/14e904a3f5b87e878cd053b554e76e85943d1c11/nashvegas/utils.py#L134-L153
train
55,427
paltman-archive/nashvegas
nashvegas/utils.py
get_applied_migrations
def get_applied_migrations(databases=None): """ Returns a dictionary containing lists of all applied migrations where the key is the database alias. """ if not databases: databases = get_capable_databases() else: # We only loop through databases that are listed as "capable" all_databases = list(get_capable_databases()) databases = list( itertools.ifilter(lambda x: x in all_databases, databases) ) results = defaultdict(list) for db in databases: for x in Migration.objects.using(db).order_by("migration_label"): results[db].append(x.migration_label) return results
python
def get_applied_migrations(databases=None): """ Returns a dictionary containing lists of all applied migrations where the key is the database alias. """ if not databases: databases = get_capable_databases() else: # We only loop through databases that are listed as "capable" all_databases = list(get_capable_databases()) databases = list( itertools.ifilter(lambda x: x in all_databases, databases) ) results = defaultdict(list) for db in databases: for x in Migration.objects.using(db).order_by("migration_label"): results[db].append(x.migration_label) return results
[ "def", "get_applied_migrations", "(", "databases", "=", "None", ")", ":", "if", "not", "databases", ":", "databases", "=", "get_capable_databases", "(", ")", "else", ":", "# We only loop through databases that are listed as \"capable\"", "all_databases", "=", "list", "(...
Returns a dictionary containing lists of all applied migrations where the key is the database alias.
[ "Returns", "a", "dictionary", "containing", "lists", "of", "all", "applied", "migrations", "where", "the", "key", "is", "the", "database", "alias", "." ]
14e904a3f5b87e878cd053b554e76e85943d1c11
https://github.com/paltman-archive/nashvegas/blob/14e904a3f5b87e878cd053b554e76e85943d1c11/nashvegas/utils.py#L156-L175
train
55,428
hollenstein/maspy
maspy/featuregrouping.py
getContGroupArrays
def getContGroupArrays(arrays, groupPositions, arrayKeys=None): """Convinience function to generate a subset of arrays from specified array positions. :param arrays: a dictionary containing ``numpy.arrays`` :param groupPositions: arrays positions that should be included in the subset of arrays :param arrayKeys: a list of "arrays" keys that should be included in the subset of arrays, if None all keys are selected :returns: a dictionary containing ``numpy.arrays`` """ if arrayKeys is None: arrayKeys = list(viewkeys(arrays)) matchingArrays = dict() for key in arrayKeys: matchingArrays[key] = arrays[key][groupPositions] return matchingArrays
python
def getContGroupArrays(arrays, groupPositions, arrayKeys=None): """Convinience function to generate a subset of arrays from specified array positions. :param arrays: a dictionary containing ``numpy.arrays`` :param groupPositions: arrays positions that should be included in the subset of arrays :param arrayKeys: a list of "arrays" keys that should be included in the subset of arrays, if None all keys are selected :returns: a dictionary containing ``numpy.arrays`` """ if arrayKeys is None: arrayKeys = list(viewkeys(arrays)) matchingArrays = dict() for key in arrayKeys: matchingArrays[key] = arrays[key][groupPositions] return matchingArrays
[ "def", "getContGroupArrays", "(", "arrays", ",", "groupPositions", ",", "arrayKeys", "=", "None", ")", ":", "if", "arrayKeys", "is", "None", ":", "arrayKeys", "=", "list", "(", "viewkeys", "(", "arrays", ")", ")", "matchingArrays", "=", "dict", "(", ")", ...
Convinience function to generate a subset of arrays from specified array positions. :param arrays: a dictionary containing ``numpy.arrays`` :param groupPositions: arrays positions that should be included in the subset of arrays :param arrayKeys: a list of "arrays" keys that should be included in the subset of arrays, if None all keys are selected :returns: a dictionary containing ``numpy.arrays``
[ "Convinience", "function", "to", "generate", "a", "subset", "of", "arrays", "from", "specified", "array", "positions", "." ]
f15fcfd24df306d8420540460d902aa3073ec133
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/featuregrouping.py#L323-L340
train
55,429
hollenstein/maspy
maspy/featuregrouping.py
calcDistMatchArr
def calcDistMatchArr(matchArr, tKey, mKey): """Calculate the euclidean distance of all array positions in "matchArr". :param matchArr: a dictionary of ``numpy.arrays`` containing at least two entries that are treated as cartesian coordinates. :param tKey: #TODO: docstring :param mKey: #TODO: docstring :returns: #TODO: docstring {'eucDist': numpy.array([eucDistance, eucDistance, ...]), 'posPairs': numpy.array([[pos1, pos2], [pos1, pos2], ...]) } """ #Calculate all sorted list of all eucledian feature distances matchArrSize = listvalues(matchArr)[0].size distInfo = {'posPairs': list(), 'eucDist': list()} _matrix = numpy.swapaxes(numpy.array([matchArr[tKey], matchArr[mKey]]), 0, 1) for pos1 in range(matchArrSize-1): for pos2 in range(pos1+1, matchArrSize): distInfo['posPairs'].append((pos1, pos2)) distInfo['posPairs'] = numpy.array(distInfo['posPairs']) distInfo['eucDist'] = scipy.spatial.distance.pdist(_matrix) distSort = numpy.argsort(distInfo['eucDist']) for key in list(viewkeys(distInfo)): distInfo[key] = distInfo[key][distSort] return distInfo
python
def calcDistMatchArr(matchArr, tKey, mKey): """Calculate the euclidean distance of all array positions in "matchArr". :param matchArr: a dictionary of ``numpy.arrays`` containing at least two entries that are treated as cartesian coordinates. :param tKey: #TODO: docstring :param mKey: #TODO: docstring :returns: #TODO: docstring {'eucDist': numpy.array([eucDistance, eucDistance, ...]), 'posPairs': numpy.array([[pos1, pos2], [pos1, pos2], ...]) } """ #Calculate all sorted list of all eucledian feature distances matchArrSize = listvalues(matchArr)[0].size distInfo = {'posPairs': list(), 'eucDist': list()} _matrix = numpy.swapaxes(numpy.array([matchArr[tKey], matchArr[mKey]]), 0, 1) for pos1 in range(matchArrSize-1): for pos2 in range(pos1+1, matchArrSize): distInfo['posPairs'].append((pos1, pos2)) distInfo['posPairs'] = numpy.array(distInfo['posPairs']) distInfo['eucDist'] = scipy.spatial.distance.pdist(_matrix) distSort = numpy.argsort(distInfo['eucDist']) for key in list(viewkeys(distInfo)): distInfo[key] = distInfo[key][distSort] return distInfo
[ "def", "calcDistMatchArr", "(", "matchArr", ",", "tKey", ",", "mKey", ")", ":", "#Calculate all sorted list of all eucledian feature distances", "matchArrSize", "=", "listvalues", "(", "matchArr", ")", "[", "0", "]", ".", "size", "distInfo", "=", "{", "'posPairs'", ...
Calculate the euclidean distance of all array positions in "matchArr". :param matchArr: a dictionary of ``numpy.arrays`` containing at least two entries that are treated as cartesian coordinates. :param tKey: #TODO: docstring :param mKey: #TODO: docstring :returns: #TODO: docstring {'eucDist': numpy.array([eucDistance, eucDistance, ...]), 'posPairs': numpy.array([[pos1, pos2], [pos1, pos2], ...]) }
[ "Calculate", "the", "euclidean", "distance", "of", "all", "array", "positions", "in", "matchArr", "." ]
f15fcfd24df306d8420540460d902aa3073ec133
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/featuregrouping.py#L356-L386
train
55,430
hollenstein/maspy
maspy/featuregrouping.py
FgiContainer.load
def load(self, path, name): """Imports the specified ``fgic`` file from the hard disk. :param path: filedirectory to which the ``fgic`` file is written. :param name: filename, without file extension """ filename = name + '.fgic' filepath = aux.joinpath(path, filename) with zipfile.ZipFile(filepath, 'r') as containerZip: #Convert the zipfile data into a str object, necessary since #containerZip.read() returns a bytes object. jsonString = io.TextIOWrapper(containerZip.open('data'), encoding='utf-8' ).read() infoString = io.TextIOWrapper(containerZip.open('info'), encoding='utf-8' ).read() self.container = json.loads(jsonString, object_hook=Fgi.jsonHook) self.info.update(json.loads(infoString)) self._matrixTemplate = self.info['_matrixTemplate'] del self.info['_matrixTemplate']
python
def load(self, path, name): """Imports the specified ``fgic`` file from the hard disk. :param path: filedirectory to which the ``fgic`` file is written. :param name: filename, without file extension """ filename = name + '.fgic' filepath = aux.joinpath(path, filename) with zipfile.ZipFile(filepath, 'r') as containerZip: #Convert the zipfile data into a str object, necessary since #containerZip.read() returns a bytes object. jsonString = io.TextIOWrapper(containerZip.open('data'), encoding='utf-8' ).read() infoString = io.TextIOWrapper(containerZip.open('info'), encoding='utf-8' ).read() self.container = json.loads(jsonString, object_hook=Fgi.jsonHook) self.info.update(json.loads(infoString)) self._matrixTemplate = self.info['_matrixTemplate'] del self.info['_matrixTemplate']
[ "def", "load", "(", "self", ",", "path", ",", "name", ")", ":", "filename", "=", "name", "+", "'.fgic'", "filepath", "=", "aux", ".", "joinpath", "(", "path", ",", "filename", ")", "with", "zipfile", ".", "ZipFile", "(", "filepath", ",", "'r'", ")", ...
Imports the specified ``fgic`` file from the hard disk. :param path: filedirectory to which the ``fgic`` file is written. :param name: filename, without file extension
[ "Imports", "the", "specified", "fgic", "file", "from", "the", "hard", "disk", "." ]
f15fcfd24df306d8420540460d902aa3073ec133
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/featuregrouping.py#L191-L212
train
55,431
ScottDuckworth/python-anyvcs
anyvcs/git.py
GitRepo.create
def create(cls, path, encoding='utf-8'): """Create a new bare repository""" cmd = [GIT, 'init', '--quiet', '--bare', path] subprocess.check_call(cmd) return cls(path, encoding)
python
def create(cls, path, encoding='utf-8'): """Create a new bare repository""" cmd = [GIT, 'init', '--quiet', '--bare', path] subprocess.check_call(cmd) return cls(path, encoding)
[ "def", "create", "(", "cls", ",", "path", ",", "encoding", "=", "'utf-8'", ")", ":", "cmd", "=", "[", "GIT", ",", "'init'", ",", "'--quiet'", ",", "'--bare'", ",", "path", "]", "subprocess", ".", "check_call", "(", "cmd", ")", "return", "cls", "(", ...
Create a new bare repository
[ "Create", "a", "new", "bare", "repository" ]
9eb09defbc6b7c99d373fad53cbf8fc81b637923
https://github.com/ScottDuckworth/python-anyvcs/blob/9eb09defbc6b7c99d373fad53cbf8fc81b637923/anyvcs/git.py#L66-L70
train
55,432
steinitzu/giveme
giveme/injector.py
Injector.cache
def cache(self, dependency: Dependency, value): """ Store an instance of dependency in the cache. Does nothing if dependency is NOT a threadlocal or a singleton. :param dependency: The ``Dependency`` to cache :param value: The value to cache for dependency :type dependency: Dependency """ if dependency.threadlocal: setattr(self._local, dependency.name, value) elif dependency.singleton: self._singleton[dependency.name] = value
python
def cache(self, dependency: Dependency, value): """ Store an instance of dependency in the cache. Does nothing if dependency is NOT a threadlocal or a singleton. :param dependency: The ``Dependency`` to cache :param value: The value to cache for dependency :type dependency: Dependency """ if dependency.threadlocal: setattr(self._local, dependency.name, value) elif dependency.singleton: self._singleton[dependency.name] = value
[ "def", "cache", "(", "self", ",", "dependency", ":", "Dependency", ",", "value", ")", ":", "if", "dependency", ".", "threadlocal", ":", "setattr", "(", "self", ".", "_local", ",", "dependency", ".", "name", ",", "value", ")", "elif", "dependency", ".", ...
Store an instance of dependency in the cache. Does nothing if dependency is NOT a threadlocal or a singleton. :param dependency: The ``Dependency`` to cache :param value: The value to cache for dependency :type dependency: Dependency
[ "Store", "an", "instance", "of", "dependency", "in", "the", "cache", ".", "Does", "nothing", "if", "dependency", "is", "NOT", "a", "threadlocal", "or", "a", "singleton", "." ]
b250995c59eb7e141d2cd8260e292c417785bbd1
https://github.com/steinitzu/giveme/blob/b250995c59eb7e141d2cd8260e292c417785bbd1/giveme/injector.py#L46-L60
train
55,433
steinitzu/giveme
giveme/injector.py
Injector.cached
def cached(self, dependency): """ Get a cached instance of dependency. :param dependency: The ``Dependency`` to retrievie value for :type dependency: ``Dependency`` :return: The cached value """ if dependency.threadlocal: return getattr(self._local, dependency.name, None) elif dependency.singleton: return self._singleton.get(dependency.name)
python
def cached(self, dependency): """ Get a cached instance of dependency. :param dependency: The ``Dependency`` to retrievie value for :type dependency: ``Dependency`` :return: The cached value """ if dependency.threadlocal: return getattr(self._local, dependency.name, None) elif dependency.singleton: return self._singleton.get(dependency.name)
[ "def", "cached", "(", "self", ",", "dependency", ")", ":", "if", "dependency", ".", "threadlocal", ":", "return", "getattr", "(", "self", ".", "_local", ",", "dependency", ".", "name", ",", "None", ")", "elif", "dependency", ".", "singleton", ":", "retur...
Get a cached instance of dependency. :param dependency: The ``Dependency`` to retrievie value for :type dependency: ``Dependency`` :return: The cached value
[ "Get", "a", "cached", "instance", "of", "dependency", "." ]
b250995c59eb7e141d2cd8260e292c417785bbd1
https://github.com/steinitzu/giveme/blob/b250995c59eb7e141d2cd8260e292c417785bbd1/giveme/injector.py#L62-L73
train
55,434
steinitzu/giveme
giveme/injector.py
Injector._set
def _set(self, name, factory, singleton=False, threadlocal=False): """ Add a dependency factory to the registry :param name: Name of dependency :param factory: function/callable that returns dependency :param singleton: When True, makes the dependency a singleton. Factory will only be called on first use, subsequent uses receive a cached value. :param threadlocal: When True, register dependency as a threadlocal singleton, Same functionality as ``singleton`` except :class:`Threading.local` is used to cache return values. """ name = name or factory.__name__ factory._giveme_registered_name = name dep = Dependency(name, factory, singleton, threadlocal) self._registry[name] = dep
python
def _set(self, name, factory, singleton=False, threadlocal=False): """ Add a dependency factory to the registry :param name: Name of dependency :param factory: function/callable that returns dependency :param singleton: When True, makes the dependency a singleton. Factory will only be called on first use, subsequent uses receive a cached value. :param threadlocal: When True, register dependency as a threadlocal singleton, Same functionality as ``singleton`` except :class:`Threading.local` is used to cache return values. """ name = name or factory.__name__ factory._giveme_registered_name = name dep = Dependency(name, factory, singleton, threadlocal) self._registry[name] = dep
[ "def", "_set", "(", "self", ",", "name", ",", "factory", ",", "singleton", "=", "False", ",", "threadlocal", "=", "False", ")", ":", "name", "=", "name", "or", "factory", ".", "__name__", "factory", ".", "_giveme_registered_name", "=", "name", "dep", "="...
Add a dependency factory to the registry :param name: Name of dependency :param factory: function/callable that returns dependency :param singleton: When True, makes the dependency a singleton. Factory will only be called on first use, subsequent uses receive a cached value. :param threadlocal: When True, register dependency as a threadlocal singleton, Same functionality as ``singleton`` except :class:`Threading.local` is used to cache return values.
[ "Add", "a", "dependency", "factory", "to", "the", "registry" ]
b250995c59eb7e141d2cd8260e292c417785bbd1
https://github.com/steinitzu/giveme/blob/b250995c59eb7e141d2cd8260e292c417785bbd1/giveme/injector.py#L75-L91
train
55,435
steinitzu/giveme
giveme/injector.py
Injector.register
def register(self, function=None, *, singleton=False, threadlocal=False, name=None): """ Add an object to the injector's registry. Can be used as a decorator like so: >>> @injector.register ... def my_dependency(): ... or a plain function call by passing in a callable injector.register(my_dependency) :param function: The function or callable to add to the registry :param name: Set the name of the dependency. Defaults to the name of `function` :param singleton: When True, register dependency as a singleton, this means that `function` is called on first use and its return value cached for subsequent uses. Defaults to False :param threadlocal: When True, register dependency as a threadlocal singleton, Same functionality as ``singleton`` except :class:`Threading.local` is used to cache return values. :type function: callable :type singleton: bool :type threadlocal: bool :type name: string """ def decorator(function=None): self._set(name, function, singleton, threadlocal) return function if function: return decorator(function) return decorator
python
def register(self, function=None, *, singleton=False, threadlocal=False, name=None): """ Add an object to the injector's registry. Can be used as a decorator like so: >>> @injector.register ... def my_dependency(): ... or a plain function call by passing in a callable injector.register(my_dependency) :param function: The function or callable to add to the registry :param name: Set the name of the dependency. Defaults to the name of `function` :param singleton: When True, register dependency as a singleton, this means that `function` is called on first use and its return value cached for subsequent uses. Defaults to False :param threadlocal: When True, register dependency as a threadlocal singleton, Same functionality as ``singleton`` except :class:`Threading.local` is used to cache return values. :type function: callable :type singleton: bool :type threadlocal: bool :type name: string """ def decorator(function=None): self._set(name, function, singleton, threadlocal) return function if function: return decorator(function) return decorator
[ "def", "register", "(", "self", ",", "function", "=", "None", ",", "*", ",", "singleton", "=", "False", ",", "threadlocal", "=", "False", ",", "name", "=", "None", ")", ":", "def", "decorator", "(", "function", "=", "None", ")", ":", "self", ".", "...
Add an object to the injector's registry. Can be used as a decorator like so: >>> @injector.register ... def my_dependency(): ... or a plain function call by passing in a callable injector.register(my_dependency) :param function: The function or callable to add to the registry :param name: Set the name of the dependency. Defaults to the name of `function` :param singleton: When True, register dependency as a singleton, this means that `function` is called on first use and its return value cached for subsequent uses. Defaults to False :param threadlocal: When True, register dependency as a threadlocal singleton, Same functionality as ``singleton`` except :class:`Threading.local` is used to cache return values. :type function: callable :type singleton: bool :type threadlocal: bool :type name: string
[ "Add", "an", "object", "to", "the", "injector", "s", "registry", "." ]
b250995c59eb7e141d2cd8260e292c417785bbd1
https://github.com/steinitzu/giveme/blob/b250995c59eb7e141d2cd8260e292c417785bbd1/giveme/injector.py#L116-L146
train
55,436
steinitzu/giveme
giveme/injector.py
Injector.inject
def inject(self, function=None, **names): """ Inject dependencies into `funtion`'s arguments when called. >>> @injector.inject ... def use_dependency(dependency_name): ... >>> use_dependency() The `Injector` will look for registered dependencies matching named arguments and automatically pass them to the given function when it's called. :param function: The function to inject into :type function: callable :param \**names: in the form of ``argument='name'`` to override the default behavior which matches dependency names with argument names. """ def decorator(function): @wraps(function) def wrapper(*args, **kwargs): sig = signature(function) params = sig.parameters bound = sig.bind_partial(*args, **kwargs) bound.apply_defaults() injected_kwargs = {} for key, value in params.items(): if key not in bound.arguments: name = names.get(key) if name: # Raise error when dep named explicitly # and missing injected_kwargs[key] = self.get(name) else: try: injected_kwargs[key] = self.get(key) except DependencyNotFoundError as e: warnings.warn( ambigious_not_found_msg.format(key), DependencyNotFoundWarning ) injected_kwargs.update(bound.kwargs) return function(*bound.args, **injected_kwargs) return wrapper if function: return decorator(function) return decorator
python
def inject(self, function=None, **names): """ Inject dependencies into `funtion`'s arguments when called. >>> @injector.inject ... def use_dependency(dependency_name): ... >>> use_dependency() The `Injector` will look for registered dependencies matching named arguments and automatically pass them to the given function when it's called. :param function: The function to inject into :type function: callable :param \**names: in the form of ``argument='name'`` to override the default behavior which matches dependency names with argument names. """ def decorator(function): @wraps(function) def wrapper(*args, **kwargs): sig = signature(function) params = sig.parameters bound = sig.bind_partial(*args, **kwargs) bound.apply_defaults() injected_kwargs = {} for key, value in params.items(): if key not in bound.arguments: name = names.get(key) if name: # Raise error when dep named explicitly # and missing injected_kwargs[key] = self.get(name) else: try: injected_kwargs[key] = self.get(key) except DependencyNotFoundError as e: warnings.warn( ambigious_not_found_msg.format(key), DependencyNotFoundWarning ) injected_kwargs.update(bound.kwargs) return function(*bound.args, **injected_kwargs) return wrapper if function: return decorator(function) return decorator
[ "def", "inject", "(", "self", ",", "function", "=", "None", ",", "*", "*", "names", ")", ":", "def", "decorator", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":"...
Inject dependencies into `funtion`'s arguments when called. >>> @injector.inject ... def use_dependency(dependency_name): ... >>> use_dependency() The `Injector` will look for registered dependencies matching named arguments and automatically pass them to the given function when it's called. :param function: The function to inject into :type function: callable :param \**names: in the form of ``argument='name'`` to override the default behavior which matches dependency names with argument names.
[ "Inject", "dependencies", "into", "funtion", "s", "arguments", "when", "called", "." ]
b250995c59eb7e141d2cd8260e292c417785bbd1
https://github.com/steinitzu/giveme/blob/b250995c59eb7e141d2cd8260e292c417785bbd1/giveme/injector.py#L148-L198
train
55,437
steinitzu/giveme
giveme/injector.py
Injector.resolve
def resolve(self, dependency): """ Resolve dependency as instance attribute of given class. >>> class Users: ... db = injector.resolve(user_db) ... ... def get_by_id(self, user_id): ... return self.db.get(user_id) When the attribute is first accessed, it will be resolved from the corresponding dependency function """ if isinstance(dependency, str): name = dependency else: name = dependency._giveme_registered_name return DeferredProperty( partial(self.get, name) )
python
def resolve(self, dependency): """ Resolve dependency as instance attribute of given class. >>> class Users: ... db = injector.resolve(user_db) ... ... def get_by_id(self, user_id): ... return self.db.get(user_id) When the attribute is first accessed, it will be resolved from the corresponding dependency function """ if isinstance(dependency, str): name = dependency else: name = dependency._giveme_registered_name return DeferredProperty( partial(self.get, name) )
[ "def", "resolve", "(", "self", ",", "dependency", ")", ":", "if", "isinstance", "(", "dependency", ",", "str", ")", ":", "name", "=", "dependency", "else", ":", "name", "=", "dependency", ".", "_giveme_registered_name", "return", "DeferredProperty", "(", "pa...
Resolve dependency as instance attribute of given class. >>> class Users: ... db = injector.resolve(user_db) ... ... def get_by_id(self, user_id): ... return self.db.get(user_id) When the attribute is first accessed, it will be resolved from the corresponding dependency function
[ "Resolve", "dependency", "as", "instance", "attribute", "of", "given", "class", "." ]
b250995c59eb7e141d2cd8260e292c417785bbd1
https://github.com/steinitzu/giveme/blob/b250995c59eb7e141d2cd8260e292c417785bbd1/giveme/injector.py#L200-L223
train
55,438
jplusplus/statscraper
statscraper/scrapers/SMHIScraper.py
SMHI._fetch_itemslist
def _fetch_itemslist(self, current_item): """ Get a all available apis """ if current_item.is_root: html = requests.get(self.base_url).text soup = BeautifulSoup(html, 'html.parser') for item_html in soup.select(".row .col-md-6"): try: label = item_html.select_one("h2").text except Exception: continue yield API(label, blob=item_html) else: # parameter = current_item.parent # data = requests.get(parameter.url) for resource in current_item.json["resource"]: label = u"{}, {}".format(resource["title"], resource["summary"]) yield SMHIDataset(label, blob=resource)
python
def _fetch_itemslist(self, current_item): """ Get a all available apis """ if current_item.is_root: html = requests.get(self.base_url).text soup = BeautifulSoup(html, 'html.parser') for item_html in soup.select(".row .col-md-6"): try: label = item_html.select_one("h2").text except Exception: continue yield API(label, blob=item_html) else: # parameter = current_item.parent # data = requests.get(parameter.url) for resource in current_item.json["resource"]: label = u"{}, {}".format(resource["title"], resource["summary"]) yield SMHIDataset(label, blob=resource)
[ "def", "_fetch_itemslist", "(", "self", ",", "current_item", ")", ":", "if", "current_item", ".", "is_root", ":", "html", "=", "requests", ".", "get", "(", "self", ".", "base_url", ")", ".", "text", "soup", "=", "BeautifulSoup", "(", "html", ",", "'html....
Get a all available apis
[ "Get", "a", "all", "available", "apis" ]
932ec048b23d15b3dbdaf829facc55fd78ec0109
https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/SMHIScraper.py#L27-L44
train
55,439
jplusplus/statscraper
statscraper/scrapers/SMHIScraper.py
SMHI._fetch_data
def _fetch_data(self, dataset, query={}, include_inactive_stations=False): """ Should yield dataset rows """ data = [] parameter = dataset station_dim = dataset.dimensions["station"] all_stations = station_dim.allowed_values # Step 1: Prepare query if "station" not in query: if include_inactive_stations: # Get all stations query["station"] = list(all_stations) else: # Get only active stations query["station"] = list(station_dim.active_stations()) else: if not isinstance(query["station"], list): query["station"] = [query["station"]] # Make sure that the queried stations actually exist query["station"] = [ all_stations.get_by_label(x) for x in query["station"]] if "period" not in query: # TODO: I'd prepare to do dataset.get("period").allowed_values here query["period"] = PERIODS elif not isinstance(query["period"], list): query["period"] = [query["period"]] for period in query["period"]: if period not in PERIODS: msg = u"{} is not an allowed period".format(period) raise Exception(msg) # Step 3: Get data n_queries = len(query["station"]) * len(query["period"]) counter = 0 print("Fetching data with {} queries.".format(n_queries)) for station in query["station"]: for period in query["period"]: url = dataset.url\ .replace(".json", "/station/{}/period/{}/data.csv"\ .format(station.key, period)) print("/GET {} ".format(url)) r = requests.get(url) if r.status_code == 200: raw_data = DataCsv().from_string(r.content).to_dictlist() # TODO: This is a very hard coded parse function # Expects fixed start row and number of cols for row in raw_data: #timepoint = datetime.strptime(timepoint_str, "%Y-%m-%d %H:%M:%S") value_col = parameter.id.split(",")[0] value = float(row[value_col]) row["parameter"] = parameter.id row["station"] = station.label row["station_key"] = station.key row["period"] = period row.pop(value_col,None) datapoint = Result(value, row) yield datapoint elif r.status_code == 404: print("Warning no data at {}".format(url)) else: raise Exception("Connection error for {}".format(url))
python
def _fetch_data(self, dataset, query={}, include_inactive_stations=False): """ Should yield dataset rows """ data = [] parameter = dataset station_dim = dataset.dimensions["station"] all_stations = station_dim.allowed_values # Step 1: Prepare query if "station" not in query: if include_inactive_stations: # Get all stations query["station"] = list(all_stations) else: # Get only active stations query["station"] = list(station_dim.active_stations()) else: if not isinstance(query["station"], list): query["station"] = [query["station"]] # Make sure that the queried stations actually exist query["station"] = [ all_stations.get_by_label(x) for x in query["station"]] if "period" not in query: # TODO: I'd prepare to do dataset.get("period").allowed_values here query["period"] = PERIODS elif not isinstance(query["period"], list): query["period"] = [query["period"]] for period in query["period"]: if period not in PERIODS: msg = u"{} is not an allowed period".format(period) raise Exception(msg) # Step 3: Get data n_queries = len(query["station"]) * len(query["period"]) counter = 0 print("Fetching data with {} queries.".format(n_queries)) for station in query["station"]: for period in query["period"]: url = dataset.url\ .replace(".json", "/station/{}/period/{}/data.csv"\ .format(station.key, period)) print("/GET {} ".format(url)) r = requests.get(url) if r.status_code == 200: raw_data = DataCsv().from_string(r.content).to_dictlist() # TODO: This is a very hard coded parse function # Expects fixed start row and number of cols for row in raw_data: #timepoint = datetime.strptime(timepoint_str, "%Y-%m-%d %H:%M:%S") value_col = parameter.id.split(",")[0] value = float(row[value_col]) row["parameter"] = parameter.id row["station"] = station.label row["station_key"] = station.key row["period"] = period row.pop(value_col,None) datapoint = Result(value, row) yield datapoint elif r.status_code == 404: print("Warning no data at {}".format(url)) else: raise Exception("Connection error for {}".format(url))
[ "def", "_fetch_data", "(", "self", ",", "dataset", ",", "query", "=", "{", "}", ",", "include_inactive_stations", "=", "False", ")", ":", "data", "=", "[", "]", "parameter", "=", "dataset", "station_dim", "=", "dataset", ".", "dimensions", "[", "\"station\...
Should yield dataset rows
[ "Should", "yield", "dataset", "rows" ]
932ec048b23d15b3dbdaf829facc55fd78ec0109
https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/SMHIScraper.py#L70-L140
train
55,440
jplusplus/statscraper
statscraper/scrapers/SMHIScraper.py
SMHIDataset._get_example_csv
def _get_example_csv(self): """For dimension parsing """ station_key = self.json["station"][0]["key"] period = "corrected-archive" url = self.url\ .replace(".json", "/station/{}/period/{}/data.csv"\ .format(station_key, period)) r = requests.get(url) if r.status_code == 200: return DataCsv().from_string(r.content) else: raise Exception("Error connecting to api")
python
def _get_example_csv(self): """For dimension parsing """ station_key = self.json["station"][0]["key"] period = "corrected-archive" url = self.url\ .replace(".json", "/station/{}/period/{}/data.csv"\ .format(station_key, period)) r = requests.get(url) if r.status_code == 200: return DataCsv().from_string(r.content) else: raise Exception("Error connecting to api")
[ "def", "_get_example_csv", "(", "self", ")", ":", "station_key", "=", "self", ".", "json", "[", "\"station\"", "]", "[", "0", "]", "[", "\"key\"", "]", "period", "=", "\"corrected-archive\"", "url", "=", "self", ".", "url", ".", "replace", "(", "\".json\...
For dimension parsing
[ "For", "dimension", "parsing" ]
932ec048b23d15b3dbdaf829facc55fd78ec0109
https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/SMHIScraper.py#L237-L250
train
55,441
what-studio/smartformat
smartformat/builtin.py
plural
def plural(formatter, value, name, option, format): """Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} There are 10 items. """ # Extract the plural words from the format string. words = format.split('|') # This extension requires at least two plural words. if not name and len(words) == 1: return # This extension only formats numbers. try: number = decimal.Decimal(value) except (ValueError, decimal.InvalidOperation): return # Get the locale. locale = Locale.parse(option) if option else formatter.locale # Select word based on the plural tag index. index = get_plural_tag_index(number, locale) return formatter.format(words[index], value)
python
def plural(formatter, value, name, option, format): """Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} There are 10 items. """ # Extract the plural words from the format string. words = format.split('|') # This extension requires at least two plural words. if not name and len(words) == 1: return # This extension only formats numbers. try: number = decimal.Decimal(value) except (ValueError, decimal.InvalidOperation): return # Get the locale. locale = Locale.parse(option) if option else formatter.locale # Select word based on the plural tag index. index = get_plural_tag_index(number, locale) return formatter.format(words[index], value)
[ "def", "plural", "(", "formatter", ",", "value", ",", "name", ",", "option", ",", "format", ")", ":", "# Extract the plural words from the format string.", "words", "=", "format", ".", "split", "(", "'|'", ")", "# This extension requires at least two plural words.", "...
Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} There are 10 items.
[ "Chooses", "different", "textension", "for", "locale", "-", "specific", "pluralization", "rules", "." ]
5731203cbf29617ab8d42542f9dac03d5e34b217
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L26-L53
train
55,442
what-studio/smartformat
smartformat/builtin.py
get_choice
def get_choice(value): """Gets a key to choose a choice from any value.""" if value is None: return 'null' for attr in ['__name__', 'name']: if hasattr(value, attr): return getattr(value, attr) return str(value)
python
def get_choice(value): """Gets a key to choose a choice from any value.""" if value is None: return 'null' for attr in ['__name__', 'name']: if hasattr(value, attr): return getattr(value, attr) return str(value)
[ "def", "get_choice", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "'null'", "for", "attr", "in", "[", "'__name__'", ",", "'name'", "]", ":", "if", "hasattr", "(", "value", ",", "attr", ")", ":", "return", "getattr", "(", "value...
Gets a key to choose a choice from any value.
[ "Gets", "a", "key", "to", "choose", "a", "choice", "from", "any", "value", "." ]
5731203cbf29617ab8d42542f9dac03d5e34b217
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L56-L63
train
55,443
what-studio/smartformat
smartformat/builtin.py
choose
def choose(formatter, value, name, option, format): """Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other' """ if not option: return words = format.split('|') num_words = len(words) if num_words < 2: return choices = option.split('|') num_choices = len(choices) # If the words has 1 more item than the choices, the last word will be # used as a default choice. if num_words not in (num_choices, num_choices + 1): n = num_choices raise ValueError('specify %d or %d choices' % (n, n + 1)) choice = get_choice(value) try: index = choices.index(choice) except ValueError: if num_words == num_choices: raise ValueError('no default choice supplied') index = -1 return formatter.format(words[index], value)
python
def choose(formatter, value, name, option, format): """Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other' """ if not option: return words = format.split('|') num_words = len(words) if num_words < 2: return choices = option.split('|') num_choices = len(choices) # If the words has 1 more item than the choices, the last word will be # used as a default choice. if num_words not in (num_choices, num_choices + 1): n = num_choices raise ValueError('specify %d or %d choices' % (n, n + 1)) choice = get_choice(value) try: index = choices.index(choice) except ValueError: if num_words == num_choices: raise ValueError('no default choice supplied') index = -1 return formatter.format(words[index], value)
[ "def", "choose", "(", "formatter", ",", "value", ",", "name", ",", "option", ",", "format", ")", ":", "if", "not", "option", ":", "return", "words", "=", "format", ".", "split", "(", "'|'", ")", "num_words", "=", "len", "(", "words", ")", "if", "nu...
Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other'
[ "Adds", "simple", "logic", "to", "format", "strings", "." ]
5731203cbf29617ab8d42542f9dac03d5e34b217
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L67-L100
train
55,444
what-studio/smartformat
smartformat/builtin.py
list_
def list_(formatter, value, name, option, format): """Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits[:2]) u'apple and banana' """ if not format: return if not hasattr(value, '__getitem__') or isinstance(value, string_types): return words = format.split(u'|', 4) num_words = len(words) if num_words < 2: # Require at least two words for item format and spacer. return num_items = len(value) item_format = words[0] # NOTE: SmartFormat.NET treats a not nested item format as the format # string to format each items. For example, `x` will be treated as `{:x}`. # But the original tells us this behavior has been deprecated so that # should be removed. So SmartFormat for Python doesn't implement the # behavior. spacer = u'' if num_words < 2 else words[1] final_spacer = spacer if num_words < 3 else words[2] two_spacer = final_spacer if num_words < 4 else words[3] buf = io.StringIO() for x, item in enumerate(value): if x == 0: pass elif x < num_items - 1: buf.write(spacer) elif x == 1: buf.write(two_spacer) else: buf.write(final_spacer) buf.write(formatter.format(item_format, item, index=x)) return buf.getvalue()
python
def list_(formatter, value, name, option, format): """Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits[:2]) u'apple and banana' """ if not format: return if not hasattr(value, '__getitem__') or isinstance(value, string_types): return words = format.split(u'|', 4) num_words = len(words) if num_words < 2: # Require at least two words for item format and spacer. return num_items = len(value) item_format = words[0] # NOTE: SmartFormat.NET treats a not nested item format as the format # string to format each items. For example, `x` will be treated as `{:x}`. # But the original tells us this behavior has been deprecated so that # should be removed. So SmartFormat for Python doesn't implement the # behavior. spacer = u'' if num_words < 2 else words[1] final_spacer = spacer if num_words < 3 else words[2] two_spacer = final_spacer if num_words < 4 else words[3] buf = io.StringIO() for x, item in enumerate(value): if x == 0: pass elif x < num_items - 1: buf.write(spacer) elif x == 1: buf.write(two_spacer) else: buf.write(final_spacer) buf.write(formatter.format(item_format, item, index=x)) return buf.getvalue()
[ "def", "list_", "(", "formatter", ",", "value", ",", "name", ",", "option", ",", "format", ")", ":", "if", "not", "format", ":", "return", "if", "not", "hasattr", "(", "value", ",", "'__getitem__'", ")", "or", "isinstance", "(", "value", ",", "string_t...
Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits[:2]) u'apple and banana'
[ "Repeats", "the", "items", "of", "an", "array", "." ]
5731203cbf29617ab8d42542f9dac03d5e34b217
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L112-L156
train
55,445
MacHu-GWU/rolex-project
rolex/math.py
add_months
def add_months(datetime_like_object, n, return_date=False): """ Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime
python
def add_months(datetime_like_object, n, return_date=False): """ Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime
[ "def", "add_months", "(", "datetime_like_object", ",", "n", ",", "return_date", "=", "False", ")", ":", "a_datetime", "=", "parser", ".", "parse_datetime", "(", "datetime_like_object", ")", "month_from_ordinary", "=", "a_datetime", ".", "year", "*", "12", "+", ...
Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。
[ "Returns", "a", "time", "that", "n", "months", "after", "a", "time", "." ]
a1111b410ed04b4b6eddd81df110fa2dacfa6537
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/math.py#L89-L132
train
55,446
rosshamish/catanlog
catanlog.py
CatanLog._log
def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush()
python
def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush()
[ "def", "_log", "(", "self", ",", "content", ")", ":", "self", ".", "_buffer", "+=", "content", "if", "self", ".", "_auto_flush", ":", "self", ".", "flush", "(", ")" ]
Write a string to the log
[ "Write", "a", "string", "to", "the", "log" ]
6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L51-L57
train
55,447
rosshamish/catanlog
catanlog.py
CatanLog.reset
def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now()
python
def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_buffer", "=", "''", "self", ".", "_chars_flushed", "=", "0", "self", ".", "_game_start_timestamp", "=", "datetime", ".", "datetime", ".", "now", "(", ")" ]
Erase the log and reset the timestamp
[ "Erase", "the", "log", "and", "reset", "the", "timestamp" ]
6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L71-L77
train
55,448
rosshamish/catanlog
catanlog.py
CatanLog.logpath
def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path
python
def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path
[ "def", "logpath", "(", "self", ")", ":", "name", "=", "'{}-{}.catan'", ".", "format", "(", "self", ".", "timestamp_str", "(", ")", ",", "'-'", ".", "join", "(", "[", "p", ".", "name", "for", "p", "in", "self", ".", "_players", "]", ")", ")", "pat...
Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively.
[ "Return", "the", "logfile", "path", "and", "filename", "as", "a", "string", "." ]
6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L91-L106
train
55,449
rosshamish/catanlog
catanlog.py
CatanLog.flush
def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close()
python
def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close()
[ "def", "flush", "(", "self", ")", ":", "latest", "=", "self", ".", "_latest", "(", ")", "self", ".", "_chars_flushed", "+=", "len", "(", "latest", ")", "if", "self", ".", "_use_stdout", ":", "file", "=", "sys", ".", "stdout", "else", ":", "file", "...
Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options.
[ "Append", "the", "latest", "updates", "to", "file", "or", "optionally", "to", "stdout", "instead", ".", "See", "the", "constructor", "for", "logging", "options", "." ]
6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L111-L126
train
55,450
rosshamish/catanlog
catanlog.py
CatanLog.log_game_start
def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!')
python
def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!')
[ "def", "log_game_start", "(", "self", ",", "players", ",", "terrain", ",", "numbers", ",", "ports", ")", ":", "self", ".", "reset", "(", ")", "self", ".", "_set_players", "(", "players", ")", "self", ".", "_logln", "(", "'{} v{}'", ".", "format", "(", ...
Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects.
[ "Begin", "a", "game", "." ]
6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L128-L149
train
55,451
rosshamish/catanlog
catanlog.py
CatanLog._log_board_ports
def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports)))
python
def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports)))
[ "def", "_log_board_ports", "(", "self", ",", "ports", ")", ":", "ports", "=", "sorted", "(", "ports", ",", "key", "=", "lambda", "port", ":", "(", "port", ".", "tile_id", ",", "port", ".", "direction", ")", ")", "self", ".", "_logln", "(", "'ports: {...
A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects
[ "A", "board", "with", "no", "ports", "is", "allowed", "." ]
6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L347-L359
train
55,452
davgeo/clear
clear/renamer.py
TVRenamer._SetGuide
def _SetGuide(self, guideName): """ Select guide corresponding to guideName Parameters ---------- guideName : string Name of guide to use. Note ---------- Supported guide names are: EPGUIDES """ if(guideName == epguides.EPGuidesLookup.GUIDE_NAME): self._guide = epguides.EPGuidesLookup() else: raise Exception("[RENAMER] Unknown guide set for TVRenamer selection: Got {}, Expected {}".format(guideName, epguides.EPGuidesLookup.GUIDE_NAME))
python
def _SetGuide(self, guideName): """ Select guide corresponding to guideName Parameters ---------- guideName : string Name of guide to use. Note ---------- Supported guide names are: EPGUIDES """ if(guideName == epguides.EPGuidesLookup.GUIDE_NAME): self._guide = epguides.EPGuidesLookup() else: raise Exception("[RENAMER] Unknown guide set for TVRenamer selection: Got {}, Expected {}".format(guideName, epguides.EPGuidesLookup.GUIDE_NAME))
[ "def", "_SetGuide", "(", "self", ",", "guideName", ")", ":", "if", "(", "guideName", "==", "epguides", ".", "EPGuidesLookup", ".", "GUIDE_NAME", ")", ":", "self", ".", "_guide", "=", "epguides", ".", "EPGuidesLookup", "(", ")", "else", ":", "raise", "Exc...
Select guide corresponding to guideName Parameters ---------- guideName : string Name of guide to use. Note ---------- Supported guide names are: EPGUIDES
[ "Select", "guide", "corresponding", "to", "guideName" ]
5ec85d27efd28afddfcd4c3f44df17f0115a77aa
https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/renamer.py#L108-L124
train
55,453
davgeo/clear
clear/renamer.py
TVRenamer._GetUniqueFileShowNames
def _GetUniqueFileShowNames(self, tvFileList): """ Return a list containing all unique show names from tvfile.TVFile object list. Parameters ---------- tvFileList : list List of tvfile.TVFile objects. Returns ---------- set The set of show names from the tvfile.TVFile list. """ showNameList = [tvFile.fileInfo.showName for tvFile in tvFileList] return(set(showNameList))
python
def _GetUniqueFileShowNames(self, tvFileList): """ Return a list containing all unique show names from tvfile.TVFile object list. Parameters ---------- tvFileList : list List of tvfile.TVFile objects. Returns ---------- set The set of show names from the tvfile.TVFile list. """ showNameList = [tvFile.fileInfo.showName for tvFile in tvFileList] return(set(showNameList))
[ "def", "_GetUniqueFileShowNames", "(", "self", ",", "tvFileList", ")", ":", "showNameList", "=", "[", "tvFile", ".", "fileInfo", ".", "showName", "for", "tvFile", "in", "tvFileList", "]", "return", "(", "set", "(", "showNameList", ")", ")" ]
Return a list containing all unique show names from tvfile.TVFile object list. Parameters ---------- tvFileList : list List of tvfile.TVFile objects. Returns ---------- set The set of show names from the tvfile.TVFile list.
[ "Return", "a", "list", "containing", "all", "unique", "show", "names", "from", "tvfile", ".", "TVFile", "object", "list", "." ]
5ec85d27efd28afddfcd4c3f44df17f0115a77aa
https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/renamer.py#L129-L145
train
55,454
davgeo/clear
clear/renamer.py
TVRenamer._GetShowInfo
def _GetShowInfo(self, stringSearch): """ Calls GetShowID and does post processing checks on result. Parameters ---------- stringSearch : string String to look up in database or guide. Returns ---------- tvfile.ShowInfo or None If GetShowID returns None or if it returns showInfo with showID = None then this will return None, otherwise it will return the showInfo object. """ goodlogging.Log.Info("RENAMER", "Looking up show info for: {0}".format(stringSearch)) goodlogging.Log.IncreaseIndent() showInfo = self._GetShowID(stringSearch) if showInfo is None: goodlogging.Log.DecreaseIndent() return None elif showInfo.showID is None: goodlogging.Log.DecreaseIndent() return None elif showInfo.showName is None: showInfo.showName = self._db.SearchTVLibrary(showID = showInfo.showID)[0][1] goodlogging.Log.Info("RENAMER", "Found show name: {0}".format(showInfo.showName)) goodlogging.Log.DecreaseIndent() return showInfo else: goodlogging.Log.DecreaseIndent() return showInfo
python
def _GetShowInfo(self, stringSearch): """ Calls GetShowID and does post processing checks on result. Parameters ---------- stringSearch : string String to look up in database or guide. Returns ---------- tvfile.ShowInfo or None If GetShowID returns None or if it returns showInfo with showID = None then this will return None, otherwise it will return the showInfo object. """ goodlogging.Log.Info("RENAMER", "Looking up show info for: {0}".format(stringSearch)) goodlogging.Log.IncreaseIndent() showInfo = self._GetShowID(stringSearch) if showInfo is None: goodlogging.Log.DecreaseIndent() return None elif showInfo.showID is None: goodlogging.Log.DecreaseIndent() return None elif showInfo.showName is None: showInfo.showName = self._db.SearchTVLibrary(showID = showInfo.showID)[0][1] goodlogging.Log.Info("RENAMER", "Found show name: {0}".format(showInfo.showName)) goodlogging.Log.DecreaseIndent() return showInfo else: goodlogging.Log.DecreaseIndent() return showInfo
[ "def", "_GetShowInfo", "(", "self", ",", "stringSearch", ")", ":", "goodlogging", ".", "Log", ".", "Info", "(", "\"RENAMER\"", ",", "\"Looking up show info for: {0}\"", ".", "format", "(", "stringSearch", ")", ")", "goodlogging", ".", "Log", ".", "IncreaseIndent...
Calls GetShowID and does post processing checks on result. Parameters ---------- stringSearch : string String to look up in database or guide. Returns ---------- tvfile.ShowInfo or None If GetShowID returns None or if it returns showInfo with showID = None then this will return None, otherwise it will return the showInfo object.
[ "Calls", "GetShowID", "and", "does", "post", "processing", "checks", "on", "result", "." ]
5ec85d27efd28afddfcd4c3f44df17f0115a77aa
https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/renamer.py#L266-L297
train
55,455
davgeo/clear
clear/renamer.py
TVRenamer._CreateNewShowDir
def _CreateNewShowDir(self, showName): """ Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of special characters, is proposed which the user can accept or they can enter a new name to use. If the skipUserInput variable is True the autogenerated value is accepted by default. Parameters ---------- showName : string Name of TV show Returns ---------- string or None Either the autogenerated directory name, the user given directory name or None if the user chooses to skip at this input stage. """ stripedDir = util.StripSpecialCharacters(showName) goodlogging.Log.Info("RENAMER", "Suggested show directory name is: '{0}'".format(stripedDir)) if self._skipUserInput is False: response = goodlogging.Log.Input('RENAMER', "Enter 'y' to accept this directory, 'x' to skip this show or enter a new directory to use: ") else: response = 'y' if response.lower() == 'x': return None elif response.lower() == 'y': return stripedDir else: return response
python
def _CreateNewShowDir(self, showName): """ Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of special characters, is proposed which the user can accept or they can enter a new name to use. If the skipUserInput variable is True the autogenerated value is accepted by default. Parameters ---------- showName : string Name of TV show Returns ---------- string or None Either the autogenerated directory name, the user given directory name or None if the user chooses to skip at this input stage. """ stripedDir = util.StripSpecialCharacters(showName) goodlogging.Log.Info("RENAMER", "Suggested show directory name is: '{0}'".format(stripedDir)) if self._skipUserInput is False: response = goodlogging.Log.Input('RENAMER', "Enter 'y' to accept this directory, 'x' to skip this show or enter a new directory to use: ") else: response = 'y' if response.lower() == 'x': return None elif response.lower() == 'y': return stripedDir else: return response
[ "def", "_CreateNewShowDir", "(", "self", ",", "showName", ")", ":", "stripedDir", "=", "util", ".", "StripSpecialCharacters", "(", "showName", ")", "goodlogging", ".", "Log", ".", "Info", "(", "\"RENAMER\"", ",", "\"Suggested show directory name is: '{0}'\"", ".", ...
Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of special characters, is proposed which the user can accept or they can enter a new name to use. If the skipUserInput variable is True the autogenerated value is accepted by default. Parameters ---------- showName : string Name of TV show Returns ---------- string or None Either the autogenerated directory name, the user given directory name or None if the user chooses to skip at this input stage.
[ "Create", "new", "directory", "name", "for", "show", ".", "An", "autogenerated", "choice", "which", "is", "the", "showName", "input", "that", "has", "been", "stripped", "of", "special", "characters", "is", "proposed", "which", "the", "user", "can", "accept", ...
5ec85d27efd28afddfcd4c3f44df17f0115a77aa
https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/renamer.py#L529-L561
train
55,456
davgeo/clear
clear/renamer.py
TVRenamer._GenerateLibraryPath
def _GenerateLibraryPath(self, tvFile, libraryDir): """ Creates a full path for TV file in TV library. This initially attempts to directly match a show directory in the database, if this fails it searches the library directory for the best match. The user can then select an existing match or can propose a new directory to use as the show root directory. The season directory is also generated and added to the show and library directories. This is then used by the tvFile GenerateNewFilePath method to create a new path for the file. Parameters ---------- tvFile : tvfile.TVFile Contains show and file info. libraryDir : string Root path of TV library directory. Returns ---------- tvfile.TVFile This is an updated version of the input object. """ goodlogging.Log.Info("RENAMER", "Looking up library directory in database for show: {0}".format(tvFile.showInfo.showName)) goodlogging.Log.IncreaseIndent() showID, showName, showDir = self._db.SearchTVLibrary(showName = tvFile.showInfo.showName)[0] if showDir is None: goodlogging.Log.Info("RENAMER", "No directory match found in database - looking for best match in library directory: {0}".format(libraryDir)) dirList = os.listdir(libraryDir) listDir = False matchName = tvFile.showInfo.showName while showDir is None: if len(dirList) == 0: goodlogging.Log.Info("RENAMER", "TV Library directory is empty") response = None else: if listDir is True: goodlogging.Log.Info("RENAMER", "TV library directory contains: {0}".format(', '.join(dirList))) else: matchDirList = util.GetBestMatch(matchName, dirList) listDir = False if self._skipUserInput is True: if len(matchDirList) == 1: response = matchDirList[0] goodlogging.Log.Info("RENAMER", "Automatic selection of show directory: {0}".format(response)) else: response = None goodlogging.Log.Info("RENAMER", "Could not make automatic selection of show directory") else: listDirPrompt = "enter 'ls' to list all items in TV library directory" response = util.UserAcceptance(matchDirList, promptComment = listDirPrompt, promptOnly = listDir, xStrOverride = "to create new show directory") if response is None: showDir = self._CreateNewShowDir(tvFile.showInfo.showName) if showDir is None: goodlogging.Log.DecreaseIndent() return tvFile elif response.lower() == 'ls': listDir = True elif response in matchDirList: showDir = response else: matchName = response self._db.UpdateShowDirInTVLibrary(showID, showDir) # Add base directory to show path showDir = os.path.join(libraryDir, showDir) goodlogging.Log.DecreaseIndent() # Lookup and add season directory to show path seasonDir = self._LookUpSeasonDirectory(showID, showDir, tvFile.showInfo.seasonNum) if seasonDir is None: return tvFile else: showDir = os.path.join(showDir, seasonDir) # Call tvFile function to generate file name tvFile.GenerateNewFilePath(showDir) return tvFile
python
def _GenerateLibraryPath(self, tvFile, libraryDir): """ Creates a full path for TV file in TV library. This initially attempts to directly match a show directory in the database, if this fails it searches the library directory for the best match. The user can then select an existing match or can propose a new directory to use as the show root directory. The season directory is also generated and added to the show and library directories. This is then used by the tvFile GenerateNewFilePath method to create a new path for the file. Parameters ---------- tvFile : tvfile.TVFile Contains show and file info. libraryDir : string Root path of TV library directory. Returns ---------- tvfile.TVFile This is an updated version of the input object. """ goodlogging.Log.Info("RENAMER", "Looking up library directory in database for show: {0}".format(tvFile.showInfo.showName)) goodlogging.Log.IncreaseIndent() showID, showName, showDir = self._db.SearchTVLibrary(showName = tvFile.showInfo.showName)[0] if showDir is None: goodlogging.Log.Info("RENAMER", "No directory match found in database - looking for best match in library directory: {0}".format(libraryDir)) dirList = os.listdir(libraryDir) listDir = False matchName = tvFile.showInfo.showName while showDir is None: if len(dirList) == 0: goodlogging.Log.Info("RENAMER", "TV Library directory is empty") response = None else: if listDir is True: goodlogging.Log.Info("RENAMER", "TV library directory contains: {0}".format(', '.join(dirList))) else: matchDirList = util.GetBestMatch(matchName, dirList) listDir = False if self._skipUserInput is True: if len(matchDirList) == 1: response = matchDirList[0] goodlogging.Log.Info("RENAMER", "Automatic selection of show directory: {0}".format(response)) else: response = None goodlogging.Log.Info("RENAMER", "Could not make automatic selection of show directory") else: listDirPrompt = "enter 'ls' to list all items in TV library directory" response = util.UserAcceptance(matchDirList, promptComment = listDirPrompt, promptOnly = listDir, xStrOverride = "to create new show directory") if response is None: showDir = self._CreateNewShowDir(tvFile.showInfo.showName) if showDir is None: goodlogging.Log.DecreaseIndent() return tvFile elif response.lower() == 'ls': listDir = True elif response in matchDirList: showDir = response else: matchName = response self._db.UpdateShowDirInTVLibrary(showID, showDir) # Add base directory to show path showDir = os.path.join(libraryDir, showDir) goodlogging.Log.DecreaseIndent() # Lookup and add season directory to show path seasonDir = self._LookUpSeasonDirectory(showID, showDir, tvFile.showInfo.seasonNum) if seasonDir is None: return tvFile else: showDir = os.path.join(showDir, seasonDir) # Call tvFile function to generate file name tvFile.GenerateNewFilePath(showDir) return tvFile
[ "def", "_GenerateLibraryPath", "(", "self", ",", "tvFile", ",", "libraryDir", ")", ":", "goodlogging", ".", "Log", ".", "Info", "(", "\"RENAMER\"", ",", "\"Looking up library directory in database for show: {0}\"", ".", "format", "(", "tvFile", ".", "showInfo", ".",...
Creates a full path for TV file in TV library. This initially attempts to directly match a show directory in the database, if this fails it searches the library directory for the best match. The user can then select an existing match or can propose a new directory to use as the show root directory. The season directory is also generated and added to the show and library directories. This is then used by the tvFile GenerateNewFilePath method to create a new path for the file. Parameters ---------- tvFile : tvfile.TVFile Contains show and file info. libraryDir : string Root path of TV library directory. Returns ---------- tvfile.TVFile This is an updated version of the input object.
[ "Creates", "a", "full", "path", "for", "TV", "file", "in", "TV", "library", "." ]
5ec85d27efd28afddfcd4c3f44df17f0115a77aa
https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/renamer.py#L566-L654
train
55,457
e7dal/bubble3
bubble3/util/catcher.py
catch
def catch(ignore=[], was_doing="something important", helpfull_tips="you should use a debugger", gbc=None): """ Catch, prepare and log error :param exc_cls: error class :param exc: exception :param tb: exception traceback """ exc_cls, exc, tb=sys.exc_info() if exc_cls in ignore: msg='exception in ignorelist' gbc.say('ignoring caught:'+str(exc_cls)) return 'exception in ignorelist' ex_message = traceback.format_exception_only(exc_cls, exc)[-1] ex_message = ex_message.strip() # TODO: print(ex_message) error_frame = tb while error_frame.tb_next is not None: error_frame = error_frame.tb_next file = error_frame.tb_frame.f_code.co_filename line = error_frame.tb_lineno stack = traceback.extract_tb(tb) formated_stack = [] for summary in stack: formated_stack.append({ 'file': summary[0], 'line': summary[1], 'func': summary[2], 'text': summary[3] }) event = { 'was_doing':was_doing, 'message': ex_message, 'errorLocation': { 'file': file, 'line': line, 'full': file + ' -> ' + str(line) }, 'stack': formated_stack #, #'time': time.time() } try: #logging.info('caught:'+pformat(event)) gbc.cry('caught:'+pformat(event)) print('Bubble3: written error to log') print('Bubble3: tips for fixing this:') print(helpfull_tips) except Exception as e: print('Bubble3: cant log error cause of %s' % e)
python
def catch(ignore=[], was_doing="something important", helpfull_tips="you should use a debugger", gbc=None): """ Catch, prepare and log error :param exc_cls: error class :param exc: exception :param tb: exception traceback """ exc_cls, exc, tb=sys.exc_info() if exc_cls in ignore: msg='exception in ignorelist' gbc.say('ignoring caught:'+str(exc_cls)) return 'exception in ignorelist' ex_message = traceback.format_exception_only(exc_cls, exc)[-1] ex_message = ex_message.strip() # TODO: print(ex_message) error_frame = tb while error_frame.tb_next is not None: error_frame = error_frame.tb_next file = error_frame.tb_frame.f_code.co_filename line = error_frame.tb_lineno stack = traceback.extract_tb(tb) formated_stack = [] for summary in stack: formated_stack.append({ 'file': summary[0], 'line': summary[1], 'func': summary[2], 'text': summary[3] }) event = { 'was_doing':was_doing, 'message': ex_message, 'errorLocation': { 'file': file, 'line': line, 'full': file + ' -> ' + str(line) }, 'stack': formated_stack #, #'time': time.time() } try: #logging.info('caught:'+pformat(event)) gbc.cry('caught:'+pformat(event)) print('Bubble3: written error to log') print('Bubble3: tips for fixing this:') print(helpfull_tips) except Exception as e: print('Bubble3: cant log error cause of %s' % e)
[ "def", "catch", "(", "ignore", "=", "[", "]", ",", "was_doing", "=", "\"something important\"", ",", "helpfull_tips", "=", "\"you should use a debugger\"", ",", "gbc", "=", "None", ")", ":", "exc_cls", ",", "exc", ",", "tb", "=", "sys", ".", "exc_info", "(...
Catch, prepare and log error :param exc_cls: error class :param exc: exception :param tb: exception traceback
[ "Catch", "prepare", "and", "log", "error" ]
59c735281a95b44f6263a25f4d6ce24fca520082
https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/bubble3/util/catcher.py#L7-L68
train
55,458
alphagov/performanceplatform-client.py
performanceplatform/client/data_set.py
DataSet.from_name
def from_name(api_url, name, dry_run=False): """ doesn't require a token config param as all of our data is currently public """ return DataSet( '/'.join([api_url, name]).rstrip('/'), token=None, dry_run=dry_run )
python
def from_name(api_url, name, dry_run=False): """ doesn't require a token config param as all of our data is currently public """ return DataSet( '/'.join([api_url, name]).rstrip('/'), token=None, dry_run=dry_run )
[ "def", "from_name", "(", "api_url", ",", "name", ",", "dry_run", "=", "False", ")", ":", "return", "DataSet", "(", "'/'", ".", "join", "(", "[", "api_url", ",", "name", "]", ")", ".", "rstrip", "(", "'/'", ")", ",", "token", "=", "None", ",", "dr...
doesn't require a token config param as all of our data is currently public
[ "doesn", "t", "require", "a", "token", "config", "param", "as", "all", "of", "our", "data", "is", "currently", "public" ]
5f9bd061014ef4e81b2a22666cb67213e13caa87
https://github.com/alphagov/performanceplatform-client.py/blob/5f9bd061014ef4e81b2a22666cb67213e13caa87/performanceplatform/client/data_set.py#L24-L33
train
55,459
binbrain/OpenSesame
OpenSesame/xutils.py
secured_clipboard
def secured_clipboard(item): """This clipboard only allows 1 paste """ expire_clock = time.time() def set_text(clipboard, selectiondata, info, data): # expire after 15 secs if 15.0 >= time.time() - expire_clock: selectiondata.set_text(item.get_secret()) clipboard.clear() def clear(clipboard, data): """Clearing of the buffer is deferred this only gets called if the paste is actually triggered """ pass targets = [("STRING", 0, 0) ,("TEXT", 0, 1) ,("COMPOUND_TEXT", 0, 2) ,("UTF8_STRING", 0, 3)] cp = gtk.clipboard_get() cp.set_with_data(targets, set_text, clear)
python
def secured_clipboard(item): """This clipboard only allows 1 paste """ expire_clock = time.time() def set_text(clipboard, selectiondata, info, data): # expire after 15 secs if 15.0 >= time.time() - expire_clock: selectiondata.set_text(item.get_secret()) clipboard.clear() def clear(clipboard, data): """Clearing of the buffer is deferred this only gets called if the paste is actually triggered """ pass targets = [("STRING", 0, 0) ,("TEXT", 0, 1) ,("COMPOUND_TEXT", 0, 2) ,("UTF8_STRING", 0, 3)] cp = gtk.clipboard_get() cp.set_with_data(targets, set_text, clear)
[ "def", "secured_clipboard", "(", "item", ")", ":", "expire_clock", "=", "time", ".", "time", "(", ")", "def", "set_text", "(", "clipboard", ",", "selectiondata", ",", "info", ",", "data", ")", ":", "# expire after 15 secs", "if", "15.0", ">=", "time", ".",...
This clipboard only allows 1 paste
[ "This", "clipboard", "only", "allows", "1", "paste" ]
e32c306385012646400ecb49fc65c64b14ce3a93
https://github.com/binbrain/OpenSesame/blob/e32c306385012646400ecb49fc65c64b14ce3a93/OpenSesame/xutils.py#L27-L46
train
55,460
binbrain/OpenSesame
OpenSesame/xutils.py
get_active_window
def get_active_window(): """Get the currently focused window """ active_win = None default = wnck.screen_get_default() while gtk.events_pending(): gtk.main_iteration(False) window_list = default.get_windows() if len(window_list) == 0: print "No Windows Found" for win in window_list: if win.is_active(): active_win = win.get_name() return active_win
python
def get_active_window(): """Get the currently focused window """ active_win = None default = wnck.screen_get_default() while gtk.events_pending(): gtk.main_iteration(False) window_list = default.get_windows() if len(window_list) == 0: print "No Windows Found" for win in window_list: if win.is_active(): active_win = win.get_name() return active_win
[ "def", "get_active_window", "(", ")", ":", "active_win", "=", "None", "default", "=", "wnck", ".", "screen_get_default", "(", ")", "while", "gtk", ".", "events_pending", "(", ")", ":", "gtk", ".", "main_iteration", "(", "False", ")", "window_list", "=", "d...
Get the currently focused window
[ "Get", "the", "currently", "focused", "window" ]
e32c306385012646400ecb49fc65c64b14ce3a93
https://github.com/binbrain/OpenSesame/blob/e32c306385012646400ecb49fc65c64b14ce3a93/OpenSesame/xutils.py#L48-L61
train
55,461
HPCC-Cloud-Computing/CAL
calplus/v1/network/drivers/base.py
BaseQuota.get
def get(self): """Get quota from Cloud Provider.""" # get all network quota from Cloud Provider. attrs = ("networks", "security_groups", "floating_ips", "routers", "internet_gateways") for attr in attrs: setattr(self, attr, eval("self.get_{}()". format(attr)))
python
def get(self): """Get quota from Cloud Provider.""" # get all network quota from Cloud Provider. attrs = ("networks", "security_groups", "floating_ips", "routers", "internet_gateways") for attr in attrs: setattr(self, attr, eval("self.get_{}()". format(attr)))
[ "def", "get", "(", "self", ")", ":", "# get all network quota from Cloud Provider.", "attrs", "=", "(", "\"networks\"", ",", "\"security_groups\"", ",", "\"floating_ips\"", ",", "\"routers\"", ",", "\"internet_gateways\"", ")", "for", "attr", "in", "attrs", ":", "se...
Get quota from Cloud Provider.
[ "Get", "quota", "from", "Cloud", "Provider", "." ]
7134b3dfe9ee3a383506a592765c7a12fa4ca1e9
https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/v1/network/drivers/base.py#L65-L76
train
55,462
stephrdev/django-tapeforms
tapeforms/utils.py
join_css_class
def join_css_class(css_class, *additional_css_classes): """ Returns the union of one or more CSS classes as a space-separated string. Note that the order will not be preserved. """ css_set = set(chain.from_iterable( c.split(' ') for c in [css_class, *additional_css_classes] if c)) return ' '.join(css_set)
python
def join_css_class(css_class, *additional_css_classes): """ Returns the union of one or more CSS classes as a space-separated string. Note that the order will not be preserved. """ css_set = set(chain.from_iterable( c.split(' ') for c in [css_class, *additional_css_classes] if c)) return ' '.join(css_set)
[ "def", "join_css_class", "(", "css_class", ",", "*", "additional_css_classes", ")", ":", "css_set", "=", "set", "(", "chain", ".", "from_iterable", "(", "c", ".", "split", "(", "' '", ")", "for", "c", "in", "[", "css_class", ",", "*", "additional_css_class...
Returns the union of one or more CSS classes as a space-separated string. Note that the order will not be preserved.
[ "Returns", "the", "union", "of", "one", "or", "more", "CSS", "classes", "as", "a", "space", "-", "separated", "string", ".", "Note", "that", "the", "order", "will", "not", "be", "preserved", "." ]
255602de43777141f18afaf30669d7bdd4f7c323
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/utils.py#L4-L11
train
55,463
HPCC-Cloud-Computing/CAL
calplus/wsgi.py
WSGIDriver._init_routes_and_middlewares
def _init_routes_and_middlewares(self): """Initialize hooks and URI routes to resources.""" self._init_middlewares() self._init_endpoints() self.app = falcon.API(middleware=self.middleware) self.app.add_error_handler(Exception, self._error_handler) for version_path, endpoints in self.catalog: for route, resource in endpoints: self.app.add_route(version_path + route, resource)
python
def _init_routes_and_middlewares(self): """Initialize hooks and URI routes to resources.""" self._init_middlewares() self._init_endpoints() self.app = falcon.API(middleware=self.middleware) self.app.add_error_handler(Exception, self._error_handler) for version_path, endpoints in self.catalog: for route, resource in endpoints: self.app.add_route(version_path + route, resource)
[ "def", "_init_routes_and_middlewares", "(", "self", ")", ":", "self", ".", "_init_middlewares", "(", ")", "self", ".", "_init_endpoints", "(", ")", "self", ".", "app", "=", "falcon", ".", "API", "(", "middleware", "=", "self", ".", "middleware", ")", "self...
Initialize hooks and URI routes to resources.
[ "Initialize", "hooks", "and", "URI", "routes", "to", "resources", "." ]
7134b3dfe9ee3a383506a592765c7a12fa4ca1e9
https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/wsgi.py#L57-L67
train
55,464
HPCC-Cloud-Computing/CAL
calplus/wsgi.py
WSGIDriver.listen
def listen(self): """Self-host using 'bind' and 'port' from the WSGI config group.""" msgtmpl = (u'Serving on host %(host)s:%(port)s') host = CONF.wsgi.wsgi_host port = CONF.wsgi.wsgi_port LOG.info(msgtmpl, {'host': host, 'port': port}) server_cls = self._get_server_cls(host) httpd = simple_server.make_server(host, port, self.app, server_cls) httpd.serve_forever()
python
def listen(self): """Self-host using 'bind' and 'port' from the WSGI config group.""" msgtmpl = (u'Serving on host %(host)s:%(port)s') host = CONF.wsgi.wsgi_host port = CONF.wsgi.wsgi_port LOG.info(msgtmpl, {'host': host, 'port': port}) server_cls = self._get_server_cls(host) httpd = simple_server.make_server(host, port, self.app, server_cls) httpd.serve_forever()
[ "def", "listen", "(", "self", ")", ":", "msgtmpl", "=", "(", "u'Serving on host %(host)s:%(port)s'", ")", "host", "=", "CONF", ".", "wsgi", ".", "wsgi_host", "port", "=", "CONF", ".", "wsgi", ".", "wsgi_port", "LOG", ".", "info", "(", "msgtmpl", ",", "{"...
Self-host using 'bind' and 'port' from the WSGI config group.
[ "Self", "-", "host", "using", "bind", "and", "port", "from", "the", "WSGI", "config", "group", "." ]
7134b3dfe9ee3a383506a592765c7a12fa4ca1e9
https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/wsgi.py#L88-L101
train
55,465
diamondman/proteusisc
proteusisc/primitive_defaults.py
RunInstruction.get_promise
def get_promise(self): """Return the special set of promises for run_instruction. Run Instruction has to support multiple promises (one for reading data, and one for reading back the status from IR. All other primitives have a single promise, so fitting multiple into this system causes some API consistencies. This should be reviewed to see if a more coherent alternative is available. """ if self._promise is None: promise = [] if self.read: promise.append(TDOPromise(self._chain, 0, self.bitcount)) else: promise.append(None) if self.read_status: promise.append(TDOPromise(self._chain, 0, self.dev._desc._ir_length)) else: promise.append(None) self._promise = promise return self._promise
python
def get_promise(self): """Return the special set of promises for run_instruction. Run Instruction has to support multiple promises (one for reading data, and one for reading back the status from IR. All other primitives have a single promise, so fitting multiple into this system causes some API consistencies. This should be reviewed to see if a more coherent alternative is available. """ if self._promise is None: promise = [] if self.read: promise.append(TDOPromise(self._chain, 0, self.bitcount)) else: promise.append(None) if self.read_status: promise.append(TDOPromise(self._chain, 0, self.dev._desc._ir_length)) else: promise.append(None) self._promise = promise return self._promise
[ "def", "get_promise", "(", "self", ")", ":", "if", "self", ".", "_promise", "is", "None", ":", "promise", "=", "[", "]", "if", "self", ".", "read", ":", "promise", ".", "append", "(", "TDOPromise", "(", "self", ".", "_chain", ",", "0", ",", "self",...
Return the special set of promises for run_instruction. Run Instruction has to support multiple promises (one for reading data, and one for reading back the status from IR. All other primitives have a single promise, so fitting multiple into this system causes some API consistencies. This should be reviewed to see if a more coherent alternative is available.
[ "Return", "the", "special", "set", "of", "promises", "for", "run_instruction", "." ]
7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c
https://github.com/diamondman/proteusisc/blob/7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c/proteusisc/primitive_defaults.py#L146-L170
train
55,466
synw/chartjspy
chartjspy/__init__.py
Chart._get_dataset
def _get_dataset(self, dataset, name, color): """ Encode a dataset """ global palette html = "{" html += '\t"label": "' + name + '",' if color is not None: html += '"backgroundColor": "' + color + '",\n' else: html += '"backgroundColor": ' + palette + ',\n' html += '"data": ' + self._format_list(dataset) + ',\n' html += "}" return html
python
def _get_dataset(self, dataset, name, color): """ Encode a dataset """ global palette html = "{" html += '\t"label": "' + name + '",' if color is not None: html += '"backgroundColor": "' + color + '",\n' else: html += '"backgroundColor": ' + palette + ',\n' html += '"data": ' + self._format_list(dataset) + ',\n' html += "}" return html
[ "def", "_get_dataset", "(", "self", ",", "dataset", ",", "name", ",", "color", ")", ":", "global", "palette", "html", "=", "\"{\"", "html", "+=", "'\\t\"label\": \"'", "+", "name", "+", "'\",'", "if", "color", "is", "not", "None", ":", "html", "+=", "'...
Encode a dataset
[ "Encode", "a", "dataset" ]
f215e36142d47b044fb59a07f95a4ff996d2b158
https://github.com/synw/chartjspy/blob/f215e36142d47b044fb59a07f95a4ff996d2b158/chartjspy/__init__.py#L12-L25
train
55,467
synw/chartjspy
chartjspy/__init__.py
Chart.get
def get(self, slug, xdata, ydatasets, label, opts, style, ctype): """ Returns html for a chart """ xdataset = self._format_list(xdata) width = "100%" height = "300px" if opts is not None: if "width" in opts: width = str(opts["width"]) if "height" in opts: height = str(opts["height"]) stylestr = '<style>#container_' + slug + \ ' { width:' + width + ' !important; height:' + \ height + ' !important}</style>\n' html = stylestr html += '<div id="container_' + slug + \ '"><canvas id="canvas_' + slug + '"></canvas></div>\n' html += '<script>\n' html += 'var data = {\n' html += 'labels: ' + xdataset + ',\n' html += 'datasets:[\n' colors = None if "color" in style: colors = style["color"] i = 0 for dataset in ydatasets: name = dataset["name"] data = dataset["data"] html += self._get_dataset(data, name, colors) if i < len(ydatasets) - 1: html += "," i += 1 html += ']\n' html += '}\n' html += 'window.onload = function() {' html += 'var ctx = document.getElementById("canvas_' + \ slug + '").getContext("2d");' html += 'window.myChart = new Chart(ctx, {' html += 'type: "' + ctype + '",' html += 'data: data,' html += 'options: {' html += 'spanGaps: false,' html += 'responsive: true,' html += 'maintainAspectRatio: false,' if "legend" in opts: html += 'legend: {' html += 'position: "' + opts["legend"] + '",' html += '},' else: html += 'legend: {' html += 'display: false,' html += '},' if "title" in opts: html += 'title: {' html += 'display: true,' html += 'text: "' + opts["title"] + '"' html += '}' html += '}' html += '});' html += '};' html += '</script>\n' return html
python
def get(self, slug, xdata, ydatasets, label, opts, style, ctype): """ Returns html for a chart """ xdataset = self._format_list(xdata) width = "100%" height = "300px" if opts is not None: if "width" in opts: width = str(opts["width"]) if "height" in opts: height = str(opts["height"]) stylestr = '<style>#container_' + slug + \ ' { width:' + width + ' !important; height:' + \ height + ' !important}</style>\n' html = stylestr html += '<div id="container_' + slug + \ '"><canvas id="canvas_' + slug + '"></canvas></div>\n' html += '<script>\n' html += 'var data = {\n' html += 'labels: ' + xdataset + ',\n' html += 'datasets:[\n' colors = None if "color" in style: colors = style["color"] i = 0 for dataset in ydatasets: name = dataset["name"] data = dataset["data"] html += self._get_dataset(data, name, colors) if i < len(ydatasets) - 1: html += "," i += 1 html += ']\n' html += '}\n' html += 'window.onload = function() {' html += 'var ctx = document.getElementById("canvas_' + \ slug + '").getContext("2d");' html += 'window.myChart = new Chart(ctx, {' html += 'type: "' + ctype + '",' html += 'data: data,' html += 'options: {' html += 'spanGaps: false,' html += 'responsive: true,' html += 'maintainAspectRatio: false,' if "legend" in opts: html += 'legend: {' html += 'position: "' + opts["legend"] + '",' html += '},' else: html += 'legend: {' html += 'display: false,' html += '},' if "title" in opts: html += 'title: {' html += 'display: true,' html += 'text: "' + opts["title"] + '"' html += '}' html += '}' html += '});' html += '};' html += '</script>\n' return html
[ "def", "get", "(", "self", ",", "slug", ",", "xdata", ",", "ydatasets", ",", "label", ",", "opts", ",", "style", ",", "ctype", ")", ":", "xdataset", "=", "self", ".", "_format_list", "(", "xdata", ")", "width", "=", "\"100%\"", "height", "=", "\"300p...
Returns html for a chart
[ "Returns", "html", "for", "a", "chart" ]
f215e36142d47b044fb59a07f95a4ff996d2b158
https://github.com/synw/chartjspy/blob/f215e36142d47b044fb59a07f95a4ff996d2b158/chartjspy/__init__.py#L27-L90
train
55,468
synw/chartjspy
chartjspy/__init__.py
Chart._format_list
def _format_list(self, data): """ Format a list to use in javascript """ dataset = "[" i = 0 for el in data: if pd.isnull(el): dataset += "null" else: dtype = type(data[i]) if dtype == int or dtype == float: dataset += str(el) else: dataset += '"' + el + '"' if i < len(data) - 1: dataset += ', ' dataset += "]" return dataset
python
def _format_list(self, data): """ Format a list to use in javascript """ dataset = "[" i = 0 for el in data: if pd.isnull(el): dataset += "null" else: dtype = type(data[i]) if dtype == int or dtype == float: dataset += str(el) else: dataset += '"' + el + '"' if i < len(data) - 1: dataset += ', ' dataset += "]" return dataset
[ "def", "_format_list", "(", "self", ",", "data", ")", ":", "dataset", "=", "\"[\"", "i", "=", "0", "for", "el", "in", "data", ":", "if", "pd", ".", "isnull", "(", "el", ")", ":", "dataset", "+=", "\"null\"", "else", ":", "dtype", "=", "type", "("...
Format a list to use in javascript
[ "Format", "a", "list", "to", "use", "in", "javascript" ]
f215e36142d47b044fb59a07f95a4ff996d2b158
https://github.com/synw/chartjspy/blob/f215e36142d47b044fb59a07f95a4ff996d2b158/chartjspy/__init__.py#L92-L110
train
55,469
nyrkovalex/httpsrv
httpsrv/httpsrv.py
Rule.status
def status(self, status, headers=None): ''' Respond with given status and no content :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ''' self.response = _Response(status, headers) return self
python
def status(self, status, headers=None): ''' Respond with given status and no content :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ''' self.response = _Response(status, headers) return self
[ "def", "status", "(", "self", ",", "status", ",", "headers", "=", "None", ")", ":", "self", ".", "response", "=", "_Response", "(", "status", ",", "headers", ")", "return", "self" ]
Respond with given status and no content :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule
[ "Respond", "with", "given", "status", "and", "no", "content" ]
0acc3298be56856f73bda1ed10c9ab5153894b01
https://github.com/nyrkovalex/httpsrv/blob/0acc3298be56856f73bda1ed10c9ab5153894b01/httpsrv/httpsrv.py#L84-L98
train
55,470
nyrkovalex/httpsrv
httpsrv/httpsrv.py
Rule.text
def text(self, text, status=200, headers=None): ''' Respond with given status and text content :type text: str :param text: text to return :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ''' self.response = _Response(status, headers, text.encode('utf8')) return self
python
def text(self, text, status=200, headers=None): ''' Respond with given status and text content :type text: str :param text: text to return :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ''' self.response = _Response(status, headers, text.encode('utf8')) return self
[ "def", "text", "(", "self", ",", "text", ",", "status", "=", "200", ",", "headers", "=", "None", ")", ":", "self", ".", "response", "=", "_Response", "(", "status", ",", "headers", ",", "text", ".", "encode", "(", "'utf8'", ")", ")", "return", "sel...
Respond with given status and text content :type text: str :param text: text to return :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule
[ "Respond", "with", "given", "status", "and", "text", "content" ]
0acc3298be56856f73bda1ed10c9ab5153894b01
https://github.com/nyrkovalex/httpsrv/blob/0acc3298be56856f73bda1ed10c9ab5153894b01/httpsrv/httpsrv.py#L100-L117
train
55,471
nyrkovalex/httpsrv
httpsrv/httpsrv.py
Rule.matches
def matches(self, method, path, headers, bytes=None): ''' Checks if rule matches given request parameters :type method: str :param method: HTTP method, e.g. ``'GET'``, ``'POST'``, etc. Can take any custom string :type path: str :param path: request path including query parameters, e.g. ``'/users?name=John%20Doe'`` :type bytes: bytes :param bytes: request body :returns: ``True`` if this rule matches given params :rtype: bool ''' return self._expectation.matches(method, path, headers, bytes)
python
def matches(self, method, path, headers, bytes=None): ''' Checks if rule matches given request parameters :type method: str :param method: HTTP method, e.g. ``'GET'``, ``'POST'``, etc. Can take any custom string :type path: str :param path: request path including query parameters, e.g. ``'/users?name=John%20Doe'`` :type bytes: bytes :param bytes: request body :returns: ``True`` if this rule matches given params :rtype: bool ''' return self._expectation.matches(method, path, headers, bytes)
[ "def", "matches", "(", "self", ",", "method", ",", "path", ",", "headers", ",", "bytes", "=", "None", ")", ":", "return", "self", ".", "_expectation", ".", "matches", "(", "method", ",", "path", ",", "headers", ",", "bytes", ")" ]
Checks if rule matches given request parameters :type method: str :param method: HTTP method, e.g. ``'GET'``, ``'POST'``, etc. Can take any custom string :type path: str :param path: request path including query parameters, e.g. ``'/users?name=John%20Doe'`` :type bytes: bytes :param bytes: request body :returns: ``True`` if this rule matches given params :rtype: bool
[ "Checks", "if", "rule", "matches", "given", "request", "parameters" ]
0acc3298be56856f73bda1ed10c9ab5153894b01
https://github.com/nyrkovalex/httpsrv/blob/0acc3298be56856f73bda1ed10c9ab5153894b01/httpsrv/httpsrv.py#L138-L156
train
55,472
nyrkovalex/httpsrv
httpsrv/httpsrv.py
Server.on
def on(self, method, path=None, headers=None, text=None, json=None): ''' Sends response to matching parameters one time and removes it from list of expectations :type method: str :param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string :type path: str :param path: request path including query parameters :type headers: dict :param headers: dictionary of headers to expect. If omitted any headers will do :type text: str :param text: request text to expect. If ommited any text will match :type json: dict :param json: request json to expect. If ommited any json will match, if present text param will be ignored :rtype: Rule :returns: newly created expectation rule ''' rule = Rule(method, path, headers, text, json) return self._add_rule_to(rule, self._rules)
python
def on(self, method, path=None, headers=None, text=None, json=None): ''' Sends response to matching parameters one time and removes it from list of expectations :type method: str :param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string :type path: str :param path: request path including query parameters :type headers: dict :param headers: dictionary of headers to expect. If omitted any headers will do :type text: str :param text: request text to expect. If ommited any text will match :type json: dict :param json: request json to expect. If ommited any json will match, if present text param will be ignored :rtype: Rule :returns: newly created expectation rule ''' rule = Rule(method, path, headers, text, json) return self._add_rule_to(rule, self._rules)
[ "def", "on", "(", "self", ",", "method", ",", "path", "=", "None", ",", "headers", "=", "None", ",", "text", "=", "None", ",", "json", "=", "None", ")", ":", "rule", "=", "Rule", "(", "method", ",", "path", ",", "headers", ",", "text", ",", "js...
Sends response to matching parameters one time and removes it from list of expectations :type method: str :param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string :type path: str :param path: request path including query parameters :type headers: dict :param headers: dictionary of headers to expect. If omitted any headers will do :type text: str :param text: request text to expect. If ommited any text will match :type json: dict :param json: request json to expect. If ommited any json will match, if present text param will be ignored :rtype: Rule :returns: newly created expectation rule
[ "Sends", "response", "to", "matching", "parameters", "one", "time", "and", "removes", "it", "from", "list", "of", "expectations" ]
0acc3298be56856f73bda1ed10c9ab5153894b01
https://github.com/nyrkovalex/httpsrv/blob/0acc3298be56856f73bda1ed10c9ab5153894b01/httpsrv/httpsrv.py#L215-L239
train
55,473
nyrkovalex/httpsrv
httpsrv/httpsrv.py
Server.stop
def stop(self): ''' Shuts the server down and waits for server thread to join ''' self._server.shutdown() self._server.server_close() self._thread.join() self.running = False
python
def stop(self): ''' Shuts the server down and waits for server thread to join ''' self._server.shutdown() self._server.server_close() self._thread.join() self.running = False
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_server", ".", "shutdown", "(", ")", "self", ".", "_server", ".", "server_close", "(", ")", "self", ".", "_thread", ".", "join", "(", ")", "self", ".", "running", "=", "False" ]
Shuts the server down and waits for server thread to join
[ "Shuts", "the", "server", "down", "and", "waits", "for", "server", "thread", "to", "join" ]
0acc3298be56856f73bda1ed10c9ab5153894b01
https://github.com/nyrkovalex/httpsrv/blob/0acc3298be56856f73bda1ed10c9ab5153894b01/httpsrv/httpsrv.py#L263-L270
train
55,474
phensley/gstatsd
gstatsd/sink.py
GraphiteSink.send
def send(self, stats): "Format stats and send to one or more Graphite hosts" buf = cStringIO.StringIO() now = int(time.time()) num_stats = 0 # timer stats pct = stats.percent timers = stats.timers for key, vals in timers.iteritems(): if not vals: continue # compute statistics num = len(vals) vals = sorted(vals) vmin = vals[0] vmax = vals[-1] mean = vmin max_at_thresh = vmax if num > 1: idx = round((pct / 100.0) * num) tmp = vals[:int(idx)] if tmp: max_at_thresh = tmp[-1] mean = sum(tmp) / idx key = 'stats.timers.%s' % key buf.write('%s.mean %f %d\n' % (key, mean, now)) buf.write('%s.upper %f %d\n' % (key, vmax, now)) buf.write('%s.upper_%d %f %d\n' % (key, pct, max_at_thresh, now)) buf.write('%s.lower %f %d\n' % (key, vmin, now)) buf.write('%s.count %d %d\n' % (key, num, now)) num_stats += 1 # counter stats counts = stats.counts for key, val in counts.iteritems(): buf.write('stats.%s %f %d\n' % (key, val / stats.interval, now)) buf.write('stats_counts.%s %f %d\n' % (key, val, now)) num_stats += 1 # counter stats gauges = stats.gauges for key, val in gauges.iteritems(): buf.write('stats.%s %f %d\n' % (key, val, now)) buf.write('stats_counts.%s %f %d\n' % (key, val, now)) num_stats += 1 buf.write('statsd.numStats %d %d\n' % (num_stats, now)) # TODO: add support for N retries for host in self._hosts: # flush stats to graphite try: sock = socket.create_connection(host) sock.sendall(buf.getvalue()) sock.close() except Exception, ex: self.error(E_SENDFAIL % ('graphite', host, ex))
python
def send(self, stats): "Format stats and send to one or more Graphite hosts" buf = cStringIO.StringIO() now = int(time.time()) num_stats = 0 # timer stats pct = stats.percent timers = stats.timers for key, vals in timers.iteritems(): if not vals: continue # compute statistics num = len(vals) vals = sorted(vals) vmin = vals[0] vmax = vals[-1] mean = vmin max_at_thresh = vmax if num > 1: idx = round((pct / 100.0) * num) tmp = vals[:int(idx)] if tmp: max_at_thresh = tmp[-1] mean = sum(tmp) / idx key = 'stats.timers.%s' % key buf.write('%s.mean %f %d\n' % (key, mean, now)) buf.write('%s.upper %f %d\n' % (key, vmax, now)) buf.write('%s.upper_%d %f %d\n' % (key, pct, max_at_thresh, now)) buf.write('%s.lower %f %d\n' % (key, vmin, now)) buf.write('%s.count %d %d\n' % (key, num, now)) num_stats += 1 # counter stats counts = stats.counts for key, val in counts.iteritems(): buf.write('stats.%s %f %d\n' % (key, val / stats.interval, now)) buf.write('stats_counts.%s %f %d\n' % (key, val, now)) num_stats += 1 # counter stats gauges = stats.gauges for key, val in gauges.iteritems(): buf.write('stats.%s %f %d\n' % (key, val, now)) buf.write('stats_counts.%s %f %d\n' % (key, val, now)) num_stats += 1 buf.write('statsd.numStats %d %d\n' % (num_stats, now)) # TODO: add support for N retries for host in self._hosts: # flush stats to graphite try: sock = socket.create_connection(host) sock.sendall(buf.getvalue()) sock.close() except Exception, ex: self.error(E_SENDFAIL % ('graphite', host, ex))
[ "def", "send", "(", "self", ",", "stats", ")", ":", "buf", "=", "cStringIO", ".", "StringIO", "(", ")", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "num_stats", "=", "0", "# timer stats", "pct", "=", "stats", ".", "percent", "timers...
Format stats and send to one or more Graphite hosts
[ "Format", "stats", "and", "send", "to", "one", "or", "more", "Graphite", "hosts" ]
c6d3d22f162d236c1ef916064670c6dc5bce6142
https://github.com/phensley/gstatsd/blob/c6d3d22f162d236c1ef916064670c6dc5bce6142/gstatsd/sink.py#L47-L107
train
55,475
kronok/django-google-analytics-reporter
google_analytics_reporter/tracking.py
Tracker.get_payload
def get_payload(self, *args, **kwargs): """Receive all passed in args, kwargs, and combine them together with any required params""" if not kwargs: kwargs = self.default_params else: kwargs.update(self.default_params) for item in args: if isinstance(item, dict): kwargs.update(item) if hasattr(self, 'type_params'): kwargs.update(self.type_params(*args, **kwargs)) return kwargs
python
def get_payload(self, *args, **kwargs): """Receive all passed in args, kwargs, and combine them together with any required params""" if not kwargs: kwargs = self.default_params else: kwargs.update(self.default_params) for item in args: if isinstance(item, dict): kwargs.update(item) if hasattr(self, 'type_params'): kwargs.update(self.type_params(*args, **kwargs)) return kwargs
[ "def", "get_payload", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ":", "kwargs", "=", "self", ".", "default_params", "else", ":", "kwargs", ".", "update", "(", "self", ".", "default_params", ")", "for", "i...
Receive all passed in args, kwargs, and combine them together with any required params
[ "Receive", "all", "passed", "in", "args", "kwargs", "and", "combine", "them", "together", "with", "any", "required", "params" ]
cca5fb0920ec68cfe03069cedf53fb4c6440cc11
https://github.com/kronok/django-google-analytics-reporter/blob/cca5fb0920ec68cfe03069cedf53fb4c6440cc11/google_analytics_reporter/tracking.py#L53-L64
train
55,476
adamrothman/ftl
ftl/stream.py
HTTP2Stream.read_frame
async def read_frame(self) -> DataFrame: """Read a single frame from the local buffer. If no frames are available but the stream is still open, waits until more frames arrive. Otherwise, raises StreamConsumedError. When a stream is closed, a single `None` is added to the data frame Queue to wake up any waiting `read_frame` coroutines. """ if self._data_frames.qsize() == 0 and self.closed: raise StreamConsumedError(self.id) frame = await self._data_frames.get() self._data_frames.task_done() if frame is None: raise StreamConsumedError(self.id) return frame
python
async def read_frame(self) -> DataFrame: """Read a single frame from the local buffer. If no frames are available but the stream is still open, waits until more frames arrive. Otherwise, raises StreamConsumedError. When a stream is closed, a single `None` is added to the data frame Queue to wake up any waiting `read_frame` coroutines. """ if self._data_frames.qsize() == 0 and self.closed: raise StreamConsumedError(self.id) frame = await self._data_frames.get() self._data_frames.task_done() if frame is None: raise StreamConsumedError(self.id) return frame
[ "async", "def", "read_frame", "(", "self", ")", "->", "DataFrame", ":", "if", "self", ".", "_data_frames", ".", "qsize", "(", ")", "==", "0", "and", "self", ".", "closed", ":", "raise", "StreamConsumedError", "(", "self", ".", "id", ")", "frame", "=", ...
Read a single frame from the local buffer. If no frames are available but the stream is still open, waits until more frames arrive. Otherwise, raises StreamConsumedError. When a stream is closed, a single `None` is added to the data frame Queue to wake up any waiting `read_frame` coroutines.
[ "Read", "a", "single", "frame", "from", "the", "local", "buffer", "." ]
a88f3df1ecbdfba45035b65f833b8ffffc49b399
https://github.com/adamrothman/ftl/blob/a88f3df1ecbdfba45035b65f833b8ffffc49b399/ftl/stream.py#L95-L110
train
55,477
adamrothman/ftl
ftl/stream.py
HTTP2Stream.read_frame_nowait
def read_frame_nowait(self) -> Optional[DataFrame]: """Read a single frame from the local buffer immediately. If no frames are available but the stream is still open, returns None. Otherwise, raises StreamConsumedError. """ try: frame = self._data_frames.get_nowait() except asyncio.QueueEmpty: if self.closed: raise StreamConsumedError(self.id) return None self._data_frames.task_done() if frame is None: raise StreamConsumedError(self.id) return frame
python
def read_frame_nowait(self) -> Optional[DataFrame]: """Read a single frame from the local buffer immediately. If no frames are available but the stream is still open, returns None. Otherwise, raises StreamConsumedError. """ try: frame = self._data_frames.get_nowait() except asyncio.QueueEmpty: if self.closed: raise StreamConsumedError(self.id) return None self._data_frames.task_done() if frame is None: raise StreamConsumedError(self.id) return frame
[ "def", "read_frame_nowait", "(", "self", ")", "->", "Optional", "[", "DataFrame", "]", ":", "try", ":", "frame", "=", "self", ".", "_data_frames", ".", "get_nowait", "(", ")", "except", "asyncio", ".", "QueueEmpty", ":", "if", "self", ".", "closed", ":",...
Read a single frame from the local buffer immediately. If no frames are available but the stream is still open, returns None. Otherwise, raises StreamConsumedError.
[ "Read", "a", "single", "frame", "from", "the", "local", "buffer", "immediately", "." ]
a88f3df1ecbdfba45035b65f833b8ffffc49b399
https://github.com/adamrothman/ftl/blob/a88f3df1ecbdfba45035b65f833b8ffffc49b399/ftl/stream.py#L112-L127
train
55,478
randomir/plucky
plucky/__init__.py
merge
def merge(a, b, op=None, recurse_list=False, max_depth=None): """Immutable merge ``a`` structure with ``b`` using binary operator ``op`` on leaf nodes. All nodes at, or below, ``max_depth`` are considered to be leaf nodes. Merged structure is returned, input data structures are not modified. If ``recurse_list=True``, leaf lists of equal length will be merged on a list-element level. Lists are considered to be leaf nodes by default (``recurse_list=False``), and they are merged with user-provided ``op``. Note the difference:: merge([1, 2], [3, 4]) ==> [1, 2, 3, 4] merge([1, 2], [3, 4], recurse_list=True) ==> [4, 6] """ if op is None: op = operator.add if max_depth is not None: if max_depth < 1: return op(a, b) else: max_depth -= 1 if isinstance(a, dict) and isinstance(b, dict): result = {} for key in set(chain(a.keys(), b.keys())): if key in a and key in b: result[key] = merge(a[key], b[key], op=op, recurse_list=recurse_list, max_depth=max_depth) elif key in a: result[key] = deepcopy(a[key]) elif key in b: result[key] = deepcopy(b[key]) return result elif isinstance(a, list) and isinstance(b, list): if recurse_list and len(a) == len(b): # merge subelements result = [] for idx in range(len(a)): result.append(merge(a[idx], b[idx], op=op, recurse_list=recurse_list, max_depth=max_depth)) return result else: # merge lists return op(a, b) # all other merge ops should be handled by ``op``. # default ``operator.add`` will handle addition of numeric types, but fail # with TypeError for incompatible types (eg. str + None, etc.) return op(a, b)
python
def merge(a, b, op=None, recurse_list=False, max_depth=None): """Immutable merge ``a`` structure with ``b`` using binary operator ``op`` on leaf nodes. All nodes at, or below, ``max_depth`` are considered to be leaf nodes. Merged structure is returned, input data structures are not modified. If ``recurse_list=True``, leaf lists of equal length will be merged on a list-element level. Lists are considered to be leaf nodes by default (``recurse_list=False``), and they are merged with user-provided ``op``. Note the difference:: merge([1, 2], [3, 4]) ==> [1, 2, 3, 4] merge([1, 2], [3, 4], recurse_list=True) ==> [4, 6] """ if op is None: op = operator.add if max_depth is not None: if max_depth < 1: return op(a, b) else: max_depth -= 1 if isinstance(a, dict) and isinstance(b, dict): result = {} for key in set(chain(a.keys(), b.keys())): if key in a and key in b: result[key] = merge(a[key], b[key], op=op, recurse_list=recurse_list, max_depth=max_depth) elif key in a: result[key] = deepcopy(a[key]) elif key in b: result[key] = deepcopy(b[key]) return result elif isinstance(a, list) and isinstance(b, list): if recurse_list and len(a) == len(b): # merge subelements result = [] for idx in range(len(a)): result.append(merge(a[idx], b[idx], op=op, recurse_list=recurse_list, max_depth=max_depth)) return result else: # merge lists return op(a, b) # all other merge ops should be handled by ``op``. # default ``operator.add`` will handle addition of numeric types, but fail # with TypeError for incompatible types (eg. str + None, etc.) return op(a, b)
[ "def", "merge", "(", "a", ",", "b", ",", "op", "=", "None", ",", "recurse_list", "=", "False", ",", "max_depth", "=", "None", ")", ":", "if", "op", "is", "None", ":", "op", "=", "operator", ".", "add", "if", "max_depth", "is", "not", "None", ":",...
Immutable merge ``a`` structure with ``b`` using binary operator ``op`` on leaf nodes. All nodes at, or below, ``max_depth`` are considered to be leaf nodes. Merged structure is returned, input data structures are not modified. If ``recurse_list=True``, leaf lists of equal length will be merged on a list-element level. Lists are considered to be leaf nodes by default (``recurse_list=False``), and they are merged with user-provided ``op``. Note the difference:: merge([1, 2], [3, 4]) ==> [1, 2, 3, 4] merge([1, 2], [3, 4], recurse_list=True) ==> [4, 6]
[ "Immutable", "merge", "a", "structure", "with", "b", "using", "binary", "operator", "op", "on", "leaf", "nodes", ".", "All", "nodes", "at", "or", "below", "max_depth", "are", "considered", "to", "be", "leaf", "nodes", "." ]
16b7b59aa19d619d8e619dc15dc7eeffc9fe078a
https://github.com/randomir/plucky/blob/16b7b59aa19d619d8e619dc15dc7eeffc9fe078a/plucky/__init__.py#L144-L200
train
55,479
DXsmiley/edgy-json
edgy.py
_param_deprecation_warning
def _param_deprecation_warning(schema, deprecated, context): """Raises warning about using the 'old' names for some parameters. The new naming scheme just has two underscores on each end of the word for consistency """ for i in deprecated: if i in schema: msg = 'When matching {ctx}, parameter {word} is deprecated, use __{word}__ instead' msg = msg.format(ctx = context, word = i) warnings.warn(msg, Warning)
python
def _param_deprecation_warning(schema, deprecated, context): """Raises warning about using the 'old' names for some parameters. The new naming scheme just has two underscores on each end of the word for consistency """ for i in deprecated: if i in schema: msg = 'When matching {ctx}, parameter {word} is deprecated, use __{word}__ instead' msg = msg.format(ctx = context, word = i) warnings.warn(msg, Warning)
[ "def", "_param_deprecation_warning", "(", "schema", ",", "deprecated", ",", "context", ")", ":", "for", "i", "in", "deprecated", ":", "if", "i", "in", "schema", ":", "msg", "=", "'When matching {ctx}, parameter {word} is deprecated, use __{word}__ instead'", "msg", "=...
Raises warning about using the 'old' names for some parameters. The new naming scheme just has two underscores on each end of the word for consistency
[ "Raises", "warning", "about", "using", "the", "old", "names", "for", "some", "parameters", ".", "The", "new", "naming", "scheme", "just", "has", "two", "underscores", "on", "each", "end", "of", "the", "word", "for", "consistency" ]
1df05c055ce66722ed8baa71fc21e2bc54884851
https://github.com/DXsmiley/edgy-json/blob/1df05c055ce66722ed8baa71fc21e2bc54884851/edgy.py#L25-L34
train
55,480
Cadasta/django-tutelary
tutelary/backends.py
Backend.has_perm
def has_perm(self, user, perm, obj=None, *args, **kwargs): """Test user permissions for a single action and object. :param user: The user to test. :type user: ``User`` :param perm: The action to test. :type perm: ``str`` :param obj: The object path to test. :type obj: ``tutelary.engine.Object`` :returns: ``bool`` -- is the action permitted? """ try: if not self._obj_ok(obj): if hasattr(obj, 'get_permissions_object'): obj = obj.get_permissions_object(perm) else: raise InvalidPermissionObjectException return user.permset_tree.allow(Action(perm), obj) except ObjectDoesNotExist: return False
python
def has_perm(self, user, perm, obj=None, *args, **kwargs): """Test user permissions for a single action and object. :param user: The user to test. :type user: ``User`` :param perm: The action to test. :type perm: ``str`` :param obj: The object path to test. :type obj: ``tutelary.engine.Object`` :returns: ``bool`` -- is the action permitted? """ try: if not self._obj_ok(obj): if hasattr(obj, 'get_permissions_object'): obj = obj.get_permissions_object(perm) else: raise InvalidPermissionObjectException return user.permset_tree.allow(Action(perm), obj) except ObjectDoesNotExist: return False
[ "def", "has_perm", "(", "self", ",", "user", ",", "perm", ",", "obj", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "not", "self", ".", "_obj_ok", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "...
Test user permissions for a single action and object. :param user: The user to test. :type user: ``User`` :param perm: The action to test. :type perm: ``str`` :param obj: The object path to test. :type obj: ``tutelary.engine.Object`` :returns: ``bool`` -- is the action permitted?
[ "Test", "user", "permissions", "for", "a", "single", "action", "and", "object", "." ]
66bb05de7098777c0a383410c287bf48433cde87
https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/backends.py#L15-L34
train
55,481
Cadasta/django-tutelary
tutelary/backends.py
Backend.permitted_actions
def permitted_actions(self, user, obj=None): """Determine list of permitted actions for an object or object pattern. :param user: The user to test. :type user: ``User`` :param obj: A function mapping from action names to object paths to test. :type obj: callable :returns: ``list(tutelary.engine.Action)`` -- permitted actions. """ try: if not self._obj_ok(obj): raise InvalidPermissionObjectException return user.permset_tree.permitted_actions(obj) except ObjectDoesNotExist: return []
python
def permitted_actions(self, user, obj=None): """Determine list of permitted actions for an object or object pattern. :param user: The user to test. :type user: ``User`` :param obj: A function mapping from action names to object paths to test. :type obj: callable :returns: ``list(tutelary.engine.Action)`` -- permitted actions. """ try: if not self._obj_ok(obj): raise InvalidPermissionObjectException return user.permset_tree.permitted_actions(obj) except ObjectDoesNotExist: return []
[ "def", "permitted_actions", "(", "self", ",", "user", ",", "obj", "=", "None", ")", ":", "try", ":", "if", "not", "self", ".", "_obj_ok", "(", "obj", ")", ":", "raise", "InvalidPermissionObjectException", "return", "user", ".", "permset_tree", ".", "permit...
Determine list of permitted actions for an object or object pattern. :param user: The user to test. :type user: ``User`` :param obj: A function mapping from action names to object paths to test. :type obj: callable :returns: ``list(tutelary.engine.Action)`` -- permitted actions.
[ "Determine", "list", "of", "permitted", "actions", "for", "an", "object", "or", "object", "pattern", "." ]
66bb05de7098777c0a383410c287bf48433cde87
https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/backends.py#L36-L53
train
55,482
rogerhil/thegamesdb
thegamesdb/resources.py
GameResource.list
def list(self, name, platform='', genre=''): """ The name argument is required for this method as per the API server specification. This method also provides the platform and genre optional arguments as filters. """ data_list = self.db.get_data(self.list_path, name=name, platform=platform, genre=genre) data_list = data_list.get('Data') or {} games = data_list.get('Game') or [] return [self._build_item(**i) for i in games]
python
def list(self, name, platform='', genre=''): """ The name argument is required for this method as per the API server specification. This method also provides the platform and genre optional arguments as filters. """ data_list = self.db.get_data(self.list_path, name=name, platform=platform, genre=genre) data_list = data_list.get('Data') or {} games = data_list.get('Game') or [] return [self._build_item(**i) for i in games]
[ "def", "list", "(", "self", ",", "name", ",", "platform", "=", "''", ",", "genre", "=", "''", ")", ":", "data_list", "=", "self", ".", "db", ".", "get_data", "(", "self", ".", "list_path", ",", "name", "=", "name", ",", "platform", "=", "platform",...
The name argument is required for this method as per the API server specification. This method also provides the platform and genre optional arguments as filters.
[ "The", "name", "argument", "is", "required", "for", "this", "method", "as", "per", "the", "API", "server", "specification", ".", "This", "method", "also", "provides", "the", "platform", "and", "genre", "optional", "arguments", "as", "filters", "." ]
795314215f9ee73697c7520dea4ddecfb23ca8e6
https://github.com/rogerhil/thegamesdb/blob/795314215f9ee73697c7520dea4ddecfb23ca8e6/thegamesdb/resources.py#L38-L47
train
55,483
rogerhil/thegamesdb
thegamesdb/resources.py
PlatformResource.list
def list(self): """ No argument is required for this method as per the API server specification. """ data_list = self.db.get_data(self.list_path) data_list = data_list.get('Data') or {} platforms = (data_list.get('Platforms') or {}).get('Platform') or [] return [self._build_item(**i) for i in platforms]
python
def list(self): """ No argument is required for this method as per the API server specification. """ data_list = self.db.get_data(self.list_path) data_list = data_list.get('Data') or {} platforms = (data_list.get('Platforms') or {}).get('Platform') or [] return [self._build_item(**i) for i in platforms]
[ "def", "list", "(", "self", ")", ":", "data_list", "=", "self", ".", "db", ".", "get_data", "(", "self", ".", "list_path", ")", "data_list", "=", "data_list", ".", "get", "(", "'Data'", ")", "or", "{", "}", "platforms", "=", "(", "data_list", ".", ...
No argument is required for this method as per the API server specification.
[ "No", "argument", "is", "required", "for", "this", "method", "as", "per", "the", "API", "server", "specification", "." ]
795314215f9ee73697c7520dea4ddecfb23ca8e6
https://github.com/rogerhil/thegamesdb/blob/795314215f9ee73697c7520dea4ddecfb23ca8e6/thegamesdb/resources.py#L72-L79
train
55,484
cloud-hero/hero-cli
lib/utils.py
remove_none_dict_values
def remove_none_dict_values(obj): """ Remove None values from dict. """ if isinstance(obj, (list, tuple, set)): return type(obj)(remove_none_dict_values(x) for x in obj) elif isinstance(obj, dict): return type(obj)((k, remove_none_dict_values(v)) for k, v in obj.items() if v is not None) else: return obj
python
def remove_none_dict_values(obj): """ Remove None values from dict. """ if isinstance(obj, (list, tuple, set)): return type(obj)(remove_none_dict_values(x) for x in obj) elif isinstance(obj, dict): return type(obj)((k, remove_none_dict_values(v)) for k, v in obj.items() if v is not None) else: return obj
[ "def", "remove_none_dict_values", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "return", "type", "(", "obj", ")", "(", "remove_none_dict_values", "(", "x", ")", "for", "x", "in", "ob...
Remove None values from dict.
[ "Remove", "None", "values", "from", "dict", "." ]
c467b6e932d169901819ac9c456b9226dfd35bd5
https://github.com/cloud-hero/hero-cli/blob/c467b6e932d169901819ac9c456b9226dfd35bd5/lib/utils.py#L88-L99
train
55,485
HPCC-Cloud-Computing/CAL
calplus/client.py
Client
def Client(version=__version__, resource=None, provider=None, **kwargs): """Initialize client object based on given version. :params version: version of CAL, define at setup.cfg :params resource: resource type (network, compute, object_storage, block_storage) :params provider: provider object :params cloud_config: cloud auth config :params **kwargs: specific args for resource :return: class Client HOW-TO: The simplest way to create a client instance is initialization:: >> from calplus import client >> calplus = client.Client(version='1.0.0', resource='compute', provider=provider_object, some_needed_args_for_ComputeClient) """ versions = _CLIENTS.keys() if version not in versions: raise exceptions.UnsupportedVersion( 'Unknown client version or subject' ) if provider is None: raise exceptions.ProviderNotDefined( 'Not define Provider for Client' ) support_types = CONF.providers.driver_mapper.keys() if provider.type not in support_types: raise exceptions.ProviderTypeNotFound( 'Unknow provider.' ) resources = _CLIENTS[version].keys() if not resource: raise exceptions.ResourceNotDefined( 'Not define Resource, choose one: compute, network,\ object_storage, block_storage.' ) elif resource.lower() not in resources: raise exceptions.ResourceNotFound( 'Unknow resource: compute, network,\ object_storage, block_storage.' ) LOG.info('Instantiating {} client ({})' . format(resource, version)) return _CLIENTS[version][resource]( provider.type, provider.config, **kwargs)
python
def Client(version=__version__, resource=None, provider=None, **kwargs): """Initialize client object based on given version. :params version: version of CAL, define at setup.cfg :params resource: resource type (network, compute, object_storage, block_storage) :params provider: provider object :params cloud_config: cloud auth config :params **kwargs: specific args for resource :return: class Client HOW-TO: The simplest way to create a client instance is initialization:: >> from calplus import client >> calplus = client.Client(version='1.0.0', resource='compute', provider=provider_object, some_needed_args_for_ComputeClient) """ versions = _CLIENTS.keys() if version not in versions: raise exceptions.UnsupportedVersion( 'Unknown client version or subject' ) if provider is None: raise exceptions.ProviderNotDefined( 'Not define Provider for Client' ) support_types = CONF.providers.driver_mapper.keys() if provider.type not in support_types: raise exceptions.ProviderTypeNotFound( 'Unknow provider.' ) resources = _CLIENTS[version].keys() if not resource: raise exceptions.ResourceNotDefined( 'Not define Resource, choose one: compute, network,\ object_storage, block_storage.' ) elif resource.lower() not in resources: raise exceptions.ResourceNotFound( 'Unknow resource: compute, network,\ object_storage, block_storage.' ) LOG.info('Instantiating {} client ({})' . format(resource, version)) return _CLIENTS[version][resource]( provider.type, provider.config, **kwargs)
[ "def", "Client", "(", "version", "=", "__version__", ",", "resource", "=", "None", ",", "provider", "=", "None", ",", "*", "*", "kwargs", ")", ":", "versions", "=", "_CLIENTS", ".", "keys", "(", ")", "if", "version", "not", "in", "versions", ":", "ra...
Initialize client object based on given version. :params version: version of CAL, define at setup.cfg :params resource: resource type (network, compute, object_storage, block_storage) :params provider: provider object :params cloud_config: cloud auth config :params **kwargs: specific args for resource :return: class Client HOW-TO: The simplest way to create a client instance is initialization:: >> from calplus import client >> calplus = client.Client(version='1.0.0', resource='compute', provider=provider_object, some_needed_args_for_ComputeClient)
[ "Initialize", "client", "object", "based", "on", "given", "version", "." ]
7134b3dfe9ee3a383506a592765c7a12fa4ca1e9
https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/calplus/client.py#L25-L82
train
55,486
standage/tag
tag/sequence.py
Sequence.accession
def accession(self): """ Parse accession number from commonly supported formats. If the defline does not match one of the following formats, the entire description (sans leading caret) will be returned. * >gi|572257426|ref|XP_006607122.1| * >gnl|Tcas|XP_008191512.1 * >lcl|PdomMRNAr1.2-10981.1 """ accession = None if self.defline.startswith('>gi|'): match = re.match('>gi\|\d+\|[^\|]+\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) elif self.defline.startswith('>gnl|'): match = re.match('>gnl\|[^\|]+\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) elif self.defline.startswith('>lcl|'): match = re.match('>lcl\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) return accession
python
def accession(self): """ Parse accession number from commonly supported formats. If the defline does not match one of the following formats, the entire description (sans leading caret) will be returned. * >gi|572257426|ref|XP_006607122.1| * >gnl|Tcas|XP_008191512.1 * >lcl|PdomMRNAr1.2-10981.1 """ accession = None if self.defline.startswith('>gi|'): match = re.match('>gi\|\d+\|[^\|]+\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) elif self.defline.startswith('>gnl|'): match = re.match('>gnl\|[^\|]+\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) elif self.defline.startswith('>lcl|'): match = re.match('>lcl\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) return accession
[ "def", "accession", "(", "self", ")", ":", "accession", "=", "None", "if", "self", ".", "defline", ".", "startswith", "(", "'>gi|'", ")", ":", "match", "=", "re", ".", "match", "(", "'>gi\\|\\d+\\|[^\\|]+\\|([^\\|\\n ]+)'", ",", "self", ".", "defline", ")"...
Parse accession number from commonly supported formats. If the defline does not match one of the following formats, the entire description (sans leading caret) will be returned. * >gi|572257426|ref|XP_006607122.1| * >gnl|Tcas|XP_008191512.1 * >lcl|PdomMRNAr1.2-10981.1
[ "Parse", "accession", "number", "from", "commonly", "supported", "formats", "." ]
94686adf57115cea1c5235e99299e691f80ba10b
https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/sequence.py#L76-L100
train
55,487
standage/tag
tag/sequence.py
Sequence.format_seq
def format_seq(self, outstream=None, linewidth=70): """ Print a sequence in a readable format. :param outstream: if `None`, formatted sequence is returned as a string; otherwise, it is treated as a file-like object and the formatted sequence is printed to the outstream :param linewidth: width for wrapping sequences over multiple lines; set to 0 for no wrapping """ if linewidth == 0 or len(self.seq) <= linewidth: if outstream is None: return self.seq else: print(self.seq, file=outstream) return i = 0 seq = '' while i < len(self.seq): if outstream is None: seq += self.seq[i:i+linewidth] + '\n' else: print(self.seq[i:i+linewidth], file=outstream) i += linewidth if outstream is None: return seq
python
def format_seq(self, outstream=None, linewidth=70): """ Print a sequence in a readable format. :param outstream: if `None`, formatted sequence is returned as a string; otherwise, it is treated as a file-like object and the formatted sequence is printed to the outstream :param linewidth: width for wrapping sequences over multiple lines; set to 0 for no wrapping """ if linewidth == 0 or len(self.seq) <= linewidth: if outstream is None: return self.seq else: print(self.seq, file=outstream) return i = 0 seq = '' while i < len(self.seq): if outstream is None: seq += self.seq[i:i+linewidth] + '\n' else: print(self.seq[i:i+linewidth], file=outstream) i += linewidth if outstream is None: return seq
[ "def", "format_seq", "(", "self", ",", "outstream", "=", "None", ",", "linewidth", "=", "70", ")", ":", "if", "linewidth", "==", "0", "or", "len", "(", "self", ".", "seq", ")", "<=", "linewidth", ":", "if", "outstream", "is", "None", ":", "return", ...
Print a sequence in a readable format. :param outstream: if `None`, formatted sequence is returned as a string; otherwise, it is treated as a file-like object and the formatted sequence is printed to the outstream :param linewidth: width for wrapping sequences over multiple lines; set to 0 for no wrapping
[ "Print", "a", "sequence", "in", "a", "readable", "format", "." ]
94686adf57115cea1c5235e99299e691f80ba10b
https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/sequence.py#L102-L129
train
55,488
botstory/botstory
botstory/matchers.py
get_validator
def get_validator(filter_data): """ ask every matcher whether it can serve such filter data :param filter_data: :return: """ for matcher_type, m in matchers.items(): if hasattr(m, 'can_handle') and m.can_handle(filter_data): filter_data = m.handle(filter_data) return filter_data
python
def get_validator(filter_data): """ ask every matcher whether it can serve such filter data :param filter_data: :return: """ for matcher_type, m in matchers.items(): if hasattr(m, 'can_handle') and m.can_handle(filter_data): filter_data = m.handle(filter_data) return filter_data
[ "def", "get_validator", "(", "filter_data", ")", ":", "for", "matcher_type", ",", "m", "in", "matchers", ".", "items", "(", ")", ":", "if", "hasattr", "(", "m", ",", "'can_handle'", ")", "and", "m", ".", "can_handle", "(", "filter_data", ")", ":", "fil...
ask every matcher whether it can serve such filter data :param filter_data: :return:
[ "ask", "every", "matcher", "whether", "it", "can", "serve", "such", "filter", "data" ]
9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3
https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/matchers.py#L24-L35
train
55,489
HPCC-Cloud-Computing/CAL
example.py
run
def run(): """Run the examples""" # NOTE(kiennt): Until now, this example isn't finished yet, # because we don't have any completed driver # Get a network client with openstack driver. network_client = client.Client(version=_VERSION, resource=_RESOURCES[0], provider=_PROVIDER) # net = network_client.create('daikk', '10.0.0.0/24') # list_subnet = network_client.list() # network_client.show(list_subnet[0].get("id")) network_client.delete("4b983028-0f8c-4b63-b10c-6e8420bb7903")
python
def run(): """Run the examples""" # NOTE(kiennt): Until now, this example isn't finished yet, # because we don't have any completed driver # Get a network client with openstack driver. network_client = client.Client(version=_VERSION, resource=_RESOURCES[0], provider=_PROVIDER) # net = network_client.create('daikk', '10.0.0.0/24') # list_subnet = network_client.list() # network_client.show(list_subnet[0].get("id")) network_client.delete("4b983028-0f8c-4b63-b10c-6e8420bb7903")
[ "def", "run", "(", ")", ":", "# NOTE(kiennt): Until now, this example isn't finished yet,", "# because we don't have any completed driver", "# Get a network client with openstack driver.", "network_client", "=", "client", ".", "Client", "(", "version", "=", "_VERSION", ...
Run the examples
[ "Run", "the", "examples" ]
7134b3dfe9ee3a383506a592765c7a12fa4ca1e9
https://github.com/HPCC-Cloud-Computing/CAL/blob/7134b3dfe9ee3a383506a592765c7a12fa4ca1e9/example.py#L16-L29
train
55,490
sharibarboza/py_zap
py_zap/py_zap.py
Ratings.sort
def sort(self, attr): """Sort the ratings based on an attribute""" self.entries = Sorter(self.entries, self.category, attr).sort_entries() return self
python
def sort(self, attr): """Sort the ratings based on an attribute""" self.entries = Sorter(self.entries, self.category, attr).sort_entries() return self
[ "def", "sort", "(", "self", ",", "attr", ")", ":", "self", ".", "entries", "=", "Sorter", "(", "self", ".", "entries", ",", "self", ".", "category", ",", "attr", ")", ".", "sort_entries", "(", ")", "return", "self" ]
Sort the ratings based on an attribute
[ "Sort", "the", "ratings", "based", "on", "an", "attribute" ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L121-L124
train
55,491
sharibarboza/py_zap
py_zap/py_zap.py
Ratings.get_title
def get_title(self): """Title is either the chart header for a cable ratings page or above the opening description for a broadcast ratings page. """ if self.category == 'cable': strings = get_strings(self.soup, 'strong') else: strings = get_strings(self.soup, 'b') if len(strings) == 0: strings = get_strings(self.soup, 'strong') if len(strings) >= 1 and self.category == 'cable': return strings[0] elif len(strings) > 0 and 'Fast' in strings[-1]: return strings[0] return ''.join(strings)
python
def get_title(self): """Title is either the chart header for a cable ratings page or above the opening description for a broadcast ratings page. """ if self.category == 'cable': strings = get_strings(self.soup, 'strong') else: strings = get_strings(self.soup, 'b') if len(strings) == 0: strings = get_strings(self.soup, 'strong') if len(strings) >= 1 and self.category == 'cable': return strings[0] elif len(strings) > 0 and 'Fast' in strings[-1]: return strings[0] return ''.join(strings)
[ "def", "get_title", "(", "self", ")", ":", "if", "self", ".", "category", "==", "'cable'", ":", "strings", "=", "get_strings", "(", "self", ".", "soup", ",", "'strong'", ")", "else", ":", "strings", "=", "get_strings", "(", "self", ".", "soup", ",", ...
Title is either the chart header for a cable ratings page or above the opening description for a broadcast ratings page.
[ "Title", "is", "either", "the", "chart", "header", "for", "a", "cable", "ratings", "page", "or", "above", "the", "opening", "description", "for", "a", "broadcast", "ratings", "page", "." ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L146-L163
train
55,492
sharibarboza/py_zap
py_zap/py_zap.py
Ratings.get_json
def get_json(self): """Serialize ratings object as JSON-formatted string""" ratings_dict = { 'category': self.category, 'date': self.date, 'day': self.weekday, 'next week': self.next_week, 'last week': self.last_week, 'entries': self.entries, 'url': self.url } return to_json(ratings_dict)
python
def get_json(self): """Serialize ratings object as JSON-formatted string""" ratings_dict = { 'category': self.category, 'date': self.date, 'day': self.weekday, 'next week': self.next_week, 'last week': self.last_week, 'entries': self.entries, 'url': self.url } return to_json(ratings_dict)
[ "def", "get_json", "(", "self", ")", ":", "ratings_dict", "=", "{", "'category'", ":", "self", ".", "category", ",", "'date'", ":", "self", ".", "date", ",", "'day'", ":", "self", ".", "weekday", ",", "'next week'", ":", "self", ".", "next_week", ",", ...
Serialize ratings object as JSON-formatted string
[ "Serialize", "ratings", "object", "as", "JSON", "-", "formatted", "string" ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L165-L176
train
55,493
sharibarboza/py_zap
py_zap/py_zap.py
Ratings._get_url_params
def _get_url_params(self, shorten=True): """Returns a list of each parameter to be used for the url format.""" cable = True if self.category == 'cable' else False url_date = convert_month(self.date, shorten=shorten, cable=cable) return [ BASE_URL, self.weekday.lower(), self.category + '-ratings', url_date.replace(' ', '-') ]
python
def _get_url_params(self, shorten=True): """Returns a list of each parameter to be used for the url format.""" cable = True if self.category == 'cable' else False url_date = convert_month(self.date, shorten=shorten, cable=cable) return [ BASE_URL, self.weekday.lower(), self.category + '-ratings', url_date.replace(' ', '-') ]
[ "def", "_get_url_params", "(", "self", ",", "shorten", "=", "True", ")", ":", "cable", "=", "True", "if", "self", ".", "category", "==", "'cable'", "else", "False", "url_date", "=", "convert_month", "(", "self", ".", "date", ",", "shorten", "=", "shorten...
Returns a list of each parameter to be used for the url format.
[ "Returns", "a", "list", "of", "each", "parameter", "to", "be", "used", "for", "the", "url", "format", "." ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L197-L207
train
55,494
sharibarboza/py_zap
py_zap/py_zap.py
Ratings._verify_page
def _verify_page(self): """Verify the ratings page matches the correct date""" title_date = self._get_date_in_title().lower() split_date = self.date.lower().split() split_date[0] = split_date[0][:3] return all(term in title_date for term in split_date)
python
def _verify_page(self): """Verify the ratings page matches the correct date""" title_date = self._get_date_in_title().lower() split_date = self.date.lower().split() split_date[0] = split_date[0][:3] return all(term in title_date for term in split_date)
[ "def", "_verify_page", "(", "self", ")", ":", "title_date", "=", "self", ".", "_get_date_in_title", "(", ")", ".", "lower", "(", ")", "split_date", "=", "self", ".", "date", ".", "lower", "(", ")", ".", "split", "(", ")", "split_date", "[", "0", "]",...
Verify the ratings page matches the correct date
[ "Verify", "the", "ratings", "page", "matches", "the", "correct", "date" ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L226-L231
train
55,495
sharibarboza/py_zap
py_zap/py_zap.py
Ratings._get_ratings_page
def _get_ratings_page(self): """Do a limited search for the correct url.""" # Use current posted date to build url self._build_url() soup = get_soup(self.url) if soup: return soup # Try building url again with unshortened month self._build_url(shorten=False) soup = get_soup(self.url) if soup: return soup # If not page is found, use search return SearchDaily(self.category, date=self.date).fetch_result()
python
def _get_ratings_page(self): """Do a limited search for the correct url.""" # Use current posted date to build url self._build_url() soup = get_soup(self.url) if soup: return soup # Try building url again with unshortened month self._build_url(shorten=False) soup = get_soup(self.url) if soup: return soup # If not page is found, use search return SearchDaily(self.category, date=self.date).fetch_result()
[ "def", "_get_ratings_page", "(", "self", ")", ":", "# Use current posted date to build url", "self", ".", "_build_url", "(", ")", "soup", "=", "get_soup", "(", "self", ".", "url", ")", "if", "soup", ":", "return", "soup", "# Try building url again with unshortened m...
Do a limited search for the correct url.
[ "Do", "a", "limited", "search", "for", "the", "correct", "url", "." ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L238-L253
train
55,496
sharibarboza/py_zap
py_zap/py_zap.py
Cable._build_url
def _build_url(self, shorten=True): """Build the url for a cable ratings page""" self.url = URL_FORMAT.format(*self._get_url_params(shorten=shorten))
python
def _build_url(self, shorten=True): """Build the url for a cable ratings page""" self.url = URL_FORMAT.format(*self._get_url_params(shorten=shorten))
[ "def", "_build_url", "(", "self", ",", "shorten", "=", "True", ")", ":", "self", ".", "url", "=", "URL_FORMAT", ".", "format", "(", "*", "self", ".", "_get_url_params", "(", "shorten", "=", "shorten", ")", ")" ]
Build the url for a cable ratings page
[ "Build", "the", "url", "for", "a", "cable", "ratings", "page" ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L291-L293
train
55,497
sharibarboza/py_zap
py_zap/py_zap.py
Cable.fetch_entries
def fetch_entries(self): """Fetch data and parse it to build a list of cable entries.""" data = [] for row in self.get_rows(): # Stop fetching data if limit has been met if exceeded_limit(self.limit, len(data)): break entry = row.find_all('td') entry_dict = {} show = entry[0].string net = entry[1].string if not self._match_query(show, net): continue entry_dict['show'] = show entry_dict['net'] = net entry_dict['time'] = entry[2].string if ',' in entry[3].string: entry_dict['viewers'] = entry[3].string.replace(',', '.') else: entry_dict['viewers'] = '0.' + entry[3].string entry_dict['rating'] = entry[4].string # Add data to create cable entry data.append(Entry(**entry_dict)) return data
python
def fetch_entries(self): """Fetch data and parse it to build a list of cable entries.""" data = [] for row in self.get_rows(): # Stop fetching data if limit has been met if exceeded_limit(self.limit, len(data)): break entry = row.find_all('td') entry_dict = {} show = entry[0].string net = entry[1].string if not self._match_query(show, net): continue entry_dict['show'] = show entry_dict['net'] = net entry_dict['time'] = entry[2].string if ',' in entry[3].string: entry_dict['viewers'] = entry[3].string.replace(',', '.') else: entry_dict['viewers'] = '0.' + entry[3].string entry_dict['rating'] = entry[4].string # Add data to create cable entry data.append(Entry(**entry_dict)) return data
[ "def", "fetch_entries", "(", "self", ")", ":", "data", "=", "[", "]", "for", "row", "in", "self", ".", "get_rows", "(", ")", ":", "# Stop fetching data if limit has been met", "if", "exceeded_limit", "(", "self", ".", "limit", ",", "len", "(", "data", ")",...
Fetch data and parse it to build a list of cable entries.
[ "Fetch", "data", "and", "parse", "it", "to", "build", "a", "list", "of", "cable", "entries", "." ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L299-L328
train
55,498
sharibarboza/py_zap
py_zap/py_zap.py
Broadcast._build_url
def _build_url(self, shorten=True): """Build the url for a broadcast ratings page""" url_order = self._get_url_params(shorten=shorten) # For fast ratings, switch weekday and category in url if self.category != 'final': url_order[1], url_order[2] = url_order[2], url_order[1] self.url = URL_FORMAT.format(*url_order)
python
def _build_url(self, shorten=True): """Build the url for a broadcast ratings page""" url_order = self._get_url_params(shorten=shorten) # For fast ratings, switch weekday and category in url if self.category != 'final': url_order[1], url_order[2] = url_order[2], url_order[1] self.url = URL_FORMAT.format(*url_order)
[ "def", "_build_url", "(", "self", ",", "shorten", "=", "True", ")", ":", "url_order", "=", "self", ".", "_get_url_params", "(", "shorten", "=", "shorten", ")", "# For fast ratings, switch weekday and category in url", "if", "self", ".", "category", "!=", "'final'"...
Build the url for a broadcast ratings page
[ "Build", "the", "url", "for", "a", "broadcast", "ratings", "page" ]
ce90853efcad66d3e28b8f1ac910f275349d016c
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/py_zap.py#L377-L384
train
55,499