uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
2bd5a5f05ca9d2232770c8d5
train
function
@utils.synchronized('ebtables', external=True) def remove_ebtables_rules(rules, table='filter'): for rule in rules: cmd = ['ebtables', '-t', table, '-D'] + rule.split() _execute(*cmd, check_exit_code=False, run_as_root=True)
@utils.synchronized('ebtables', external=True) def remove_ebtables_rules(rules, table='filter'):
for rule in rules: cmd = ['ebtables', '-t', table, '-D'] + rule.split() _execute(*cmd, check_exit_code=False, run_as_root=True)
+ rule.split() _execute(*cmd, check_exit_code=False, run_as_root=True) cmd[3] = '-I' _execute(*cmd, run_as_root=True) @utils.synchronized('ebtables', external=True) def remove_ebtables_rules(rules, table='filter'):
64
64
65
24
40
bopopescu/nested_quota
nova/network/linux_net.py
Python
remove_ebtables_rules
remove_ebtables_rules
1,651
1,655
1,651
1,652
eda11ff6f96b0538b2ac5ec19daeac14e857347b
bigcode/the-stack
train
39e5a93b0f7ff95902afa509
train
function
@utils.synchronized('ebtables', external=True) def ensure_ebtables_rules(rules, table='filter'): for rule in rules: cmd = ['ebtables', '-t', table, '-D'] + rule.split() _execute(*cmd, check_exit_code=False, run_as_root=True) cmd[3] = '-I' _execute(*cmd, run_as_root=True)
@utils.synchronized('ebtables', external=True) def ensure_ebtables_rules(rules, table='filter'):
for rule in rules: cmd = ['ebtables', '-t', table, '-D'] + rule.split() _execute(*cmd, check_exit_code=False, run_as_root=True) cmd[3] = '-I' _execute(*cmd, run_as_root=True)
drop_action))) ipv4_filter.remove_rule('FORWARD', ('--out-interface %s -j %s' % (bridge, drop_action))) delete_net_dev(bridge) @utils.synchronized('ebtables', external=True) def ensure_e...
64
64
85
24
40
bopopescu/nested_quota
nova/network/linux_net.py
Python
ensure_ebtables_rules
ensure_ebtables_rules
1,642
1,648
1,642
1,643
72ed18f53d87073bacebb6bdffeb27830c7f4567
bigcode/the-stack
train
1167a19bf7aefe173e170875
train
function
def get_dev(network): return _get_interface_driver().get_dev(network)
def get_dev(network):
return _get_interface_driver().get_dev(network)
= importutils.import_object( CONF.linuxnet_interface_driver) return interface_driver def plug(network, mac_address, gateway=True): return _get_interface_driver().plug(network, mac_address, gateway) def unplug(network): return _get_interface_driver().unplug(network) def get_dev(network):...
64
64
16
5
59
bopopescu/nested_quota
nova/network/linux_net.py
Python
get_dev
get_dev
1,410
1,411
1,410
1,410
ebad8ad764afe45ef4941f9cbdc8478d06309a8e
bigcode/the-stack
train
8b381883a5f3968a3f0f40a8
train
function
def create_ovs_vif_port(bridge, dev, iface_id, mac, instance_id): _ovs_vsctl(['--', '--if-exists', 'del-port', dev, '--', 'add-port', bridge, dev, '--', 'set', 'Interface', dev, 'external-ids:iface-id=%s' % iface_id, 'external-ids:iface-status=active',...
def create_ovs_vif_port(bridge, dev, iface_id, mac, instance_id):
_ovs_vsctl(['--', '--if-exists', 'del-port', dev, '--', 'add-port', bridge, dev, '--', 'set', 'Interface', dev, 'external-ids:iface-id=%s' % iface_id, 'external-ids:iface-status=active', 'external-ids:attached-mac=%s' % mac, ...
except Exception as e: LOG.error(_("Unable to execute %(cmd)s. Exception: %(exception)s"), {'cmd': full_args, 'exception': e}) raise exception.AgentError(method=full_args) def create_ovs_vif_port(bridge, dev, iface_id, mac, instance_id):
64
64
126
20
44
bopopescu/nested_quota
nova/network/linux_net.py
Python
create_ovs_vif_port
create_ovs_vif_port
1,330
1,338
1,330
1,330
5643c7aaaf8cb4512ca0c418d5ed90a6575a8a10
bigcode/the-stack
train
6dd6a2a87c63ab80662223af
train
function
def _ovs_vsctl(args): full_args = ['ovs-vsctl', '--timeout=%s' % CONF.ovs_vsctl_timeout] + args try: return utils.execute(*full_args, run_as_root=True) except Exception as e: LOG.error(_("Unable to execute %(cmd)s. Exception: %(exception)s"), {'cmd': full_args, 'exception':...
def _ovs_vsctl(args):
full_args = ['ovs-vsctl', '--timeout=%s' % CONF.ovs_vsctl_timeout] + args try: return utils.execute(*full_args, run_as_root=True) except Exception as e: LOG.error(_("Unable to execute %(cmd)s. Exception: %(exception)s"), {'cmd': full_args, 'exception': e}) raise exc...
utils.execute('ip', 'link', 'set', dev, 'up', run_as_root=True) utils.execute('ip', 'link', 'set', dev, 'promisc', 'on', run_as_root=True) _set_device_mtu(dev) def _ovs_vsctl(args):
64
64
94
7
57
bopopescu/nested_quota
nova/network/linux_net.py
Python
_ovs_vsctl
_ovs_vsctl
1,320
1,327
1,320
1,320
c74cb84c36558a0c73f508c7e9273e194aba682f
bigcode/the-stack
train
ba26eb460a16b59366e6f81e
train
class
class IptablesTable(object): """An iptables table.""" def __init__(self): self.rules = [] self.remove_rules = [] self.chains = set() self.unwrapped_chains = set() self.remove_chains = set() self.dirty = True def has_chain(self, name, wrap=True): if w...
class IptablesTable(object):
"""An iptables table.""" def __init__(self): self.rules = [] self.remove_rules = [] self.chains = set() self.unwrapped_chains = set() self.remove_chains = set() self.dirty = True def has_chain(self, name, wrap=True): if wrap: return name ...
Grab the name of the binary we're running in.""" return os.path.basename(inspect.stack()[-1][1])[:16] binary_name = get_binary_name() class IptablesRule(object): """An iptables rule. You shouldn't need to use this class directly, it's only used by IptablesManager. """ def __init__(self, ch...
256
256
1,119
7
249
bopopescu/nested_quota
nova/network/linux_net.py
Python
IptablesTable
IptablesTable
182
324
182
182
8270a664ff2a4f5c436e06204760d25a4003c442
bigcode/the-stack
train
ccc91d3d9b205762605bbc5b
train
function
def update_dns(context, dev, network_ref): hostsfile = _dhcp_file(dev, 'hosts') host = None if network_ref['multi_host']: host = CONF.host fixedips = objects.FixedIPList.get_by_network(context, network_ref, ...
def update_dns(context, dev, network_ref):
hostsfile = _dhcp_file(dev, 'hosts') host = None if network_ref['multi_host']: host = CONF.host fixedips = objects.FixedIPList.get_by_network(context, network_ref, host=host) write_to_file(hos...
ips = objects.FixedIPList.get_by_network(context, network_ref, host=host) write_to_file(conffile, get_dhcp_hosts(context, network_ref, fixedips)) restart_dhcp(context, dev, network_ref, fixedips) def update_dns(c...
64
64
94
10
54
bopopescu/nested_quota
nova/network/linux_net.py
Python
update_dns
update_dns
1,015
1,024
1,015
1,015
ffb9300c5c01dfc1da6eb7c5797a6355126be923
bigcode/the-stack
train
366136f6a6759bbe96afbf2f
train
function
def update_dhcp_hostfile_with_text(dev, hosts_text): conffile = _dhcp_file(dev, 'conf') write_to_file(conffile, hosts_text)
def update_dhcp_hostfile_with_text(dev, hosts_text):
conffile = _dhcp_file(dev, 'conf') write_to_file(conffile, hosts_text)
fixedips = objects.FixedIPList.get_by_network(context, network_ref, host=host) write_to_file(hostsfile, get_dns_hosts(context, network_ref)) restart_dhcp(context, dev, network_ref, fixedips) def update_dhcp_host...
64
64
38
13
51
bopopescu/nested_quota
nova/network/linux_net.py
Python
update_dhcp_hostfile_with_text
update_dhcp_hostfile_with_text
1,027
1,029
1,027
1,027
0fc67b9fc8d8ce79784d5e9e5c081335840f1827
bigcode/the-stack
train
89f2110c416dabce3d0c56c4
train
function
def update_dhcp(context, dev, network_ref): conffile = _dhcp_file(dev, 'conf') host = None if network_ref['multi_host']: host = CONF.host fixedips = objects.FixedIPList.get_by_network(context, network_ref, ...
def update_dhcp(context, dev, network_ref):
conffile = _dhcp_file(dev, 'conf') host = None if network_ref['multi_host']: host = CONF.host fixedips = objects.FixedIPList.get_by_network(context, network_ref, host=host) write_to_file(conff...
_address): try: utils.execute('dhcp_release', dev, address, mac_address, run_as_root=True) except processutils.ProcessExecutionError: raise exception.NetworkDhcpReleaseFailed(address=address, mac_address=mac_address) def upda...
64
64
100
11
53
bopopescu/nested_quota
nova/network/linux_net.py
Python
update_dhcp
update_dhcp
1,003
1,012
1,003
1,003
cfc59216e8a6242ff6bae20b12d408d35376d82f
bigcode/the-stack
train
0715df9121b16cef6e0652cc
train
function
def _add_dnsmasq_accept_rules(dev): """Allow DHCP and DNS traffic through to dnsmasq.""" table = iptables_manager.ipv4['filter'] for port in [67, 53]: for proto in ['udp', 'tcp']: args = {'dev': dev, 'port': port, 'proto': proto} table.add_rule('INPUT', ...
def _add_dnsmasq_accept_rules(dev):
"""Allow DHCP and DNS traffic through to dnsmasq.""" table = iptables_manager.ipv4['filter'] for port in [67, 53]: for proto in ['udp', 'tcp']: args = {'dev': dev, 'port': port, 'proto': proto} table.add_rule('INPUT', '-i %(dev)s -p %(proto)s -m %(p...
's DNS hosts in hosts format.""" hosts = [] for fixedip in objects.FixedIPList.get_by_network(context, network_ref): if fixedip.allocated: hosts.append(_host_dns(fixedip)) return '\n'.join(hosts) def _add_dnsmasq_accept_rules(dev):
64
64
117
10
54
bopopescu/nested_quota
nova/network/linux_net.py
Python
_add_dnsmasq_accept_rules
_add_dnsmasq_accept_rules
929
938
929
929
d748ff007bf5cd05d32af20eaeca92cf76c058ac
bigcode/the-stack
train
a567e9f78db8dfa88088399d
train
function
def write_to_file(file, data, mode='w'): with open(file, mode) as f: f.write(data)
def write_to_file(file, data, mode='w'):
with open(file, mode) as f: f.write(data)
remove_chains.clear() for rule in remove_rules: remove_rules.remove(rule) return new_filter # NOTE(jkoelker) This is just a nice little stub point since mocking # builtins with mox is a nightmare def write_to_file(file, data, mode='w'):
64
64
27
12
51
bopopescu/nested_quota
nova/network/linux_net.py
Python
write_to_file
write_to_file
635
637
635
635
0157ac88991b78f0b41b534d789d969f61a60f01
bigcode/the-stack
train
c74df030a1f9c654a7b13b14
train
class
class LinuxNetInterfaceDriver(object): """Abstract class that defines generic network host API for all Linux interface drivers. """ def plug(self, network, mac_address): """Create Linux device, return device name.""" raise NotImplementedError() def unplug(self, network): ""...
class LinuxNetInterfaceDriver(object):
"""Abstract class that defines generic network host API for all Linux interface drivers. """ def plug(self, network, mac_address): """Create Linux device, return device name.""" raise NotImplementedError() def unplug(self, network): """Destroy Linux device, return device na...
def plug(network, mac_address, gateway=True): return _get_interface_driver().plug(network, mac_address, gateway) def unplug(network): return _get_interface_driver().unplug(network) def get_dev(network): return _get_interface_driver().get_dev(network) class LinuxNetInterfaceDriver(object):
64
64
96
7
57
bopopescu/nested_quota
nova/network/linux_net.py
Python
LinuxNetInterfaceDriver
LinuxNetInterfaceDriver
1,414
1,429
1,414
1,414
fc8ec3ad390eb9c6940eef21fdabcdc2c646031c
bigcode/the-stack
train
d4dfcb2ce37b7612c4a7d4c1
train
function
def get_binary_name(): """Grab the name of the binary we're running in.""" return os.path.basename(inspect.stack()[-1][1])[:16]
def get_binary_name():
"""Grab the name of the binary we're running in.""" return os.path.basename(inspect.stack()[-1][1])[:16]
of up to 28 characters, and we # add up to 12 characters to binary_name which is used as a prefix, # so we limit it to 16 characters. # (max_chain_name_length - len('-POSTROUTING') == 16) def get_binary_name():
64
64
34
5
59
bopopescu/nested_quota
nova/network/linux_net.py
Python
get_binary_name
get_binary_name
143
145
143
143
e2b7c2fb2a88e81f52e016300d97e63d0e6b8f4a
bigcode/the-stack
train
b119657eb1f2be7aad22b363
train
function
def floating_ebtables_rules(fixed_ip, network): """Makes sure only in-network traffic is bridged.""" return (['PREROUTING --logical-in %s -p ipv4 --ip-src %s ' '! --ip-dst %s -j redirect --redirect-target ACCEPT' % (network['bridge'], fixed_ip, network['cidr'])], 'nat')
def floating_ebtables_rules(fixed_ip, network):
"""Makes sure only in-network traffic is bridged.""" return (['PREROUTING --logical-in %s -p ipv4 --ip-src %s ' '! --ip-dst %s -j redirect --redirect-target ACCEPT' % (network['bridge'], fixed_ip, network['cidr'])], 'nat')
_ip, device): iptables_manager.ipv4['nat'].remove_rule(chain, rule) iptables_manager.apply() if device != network['bridge']: remove_ebtables_rules(*floating_ebtables_rules(fixed_ip, network)) def floating_ebtables_rules(fixed_ip, network):
64
64
82
12
52
bopopescu/nested_quota
nova/network/linux_net.py
Python
floating_ebtables_rules
floating_ebtables_rules
795
799
795
795
326fd49e8d37bc3b8763d29a254aedffa459966d
bigcode/the-stack
train
e94341d6852ad31738810cfa
train
function
def delete_net_dev(dev): """Delete a network device only if it exists.""" if device_exists(dev): try: utils.execute('ip', 'link', 'delete', dev, run_as_root=True, check_exit_code=[0, 2, 254]) LOG.debug("Net device removed: '%s'", dev) except proc...
def delete_net_dev(dev):
"""Delete a network device only if it exists.""" if device_exists(dev): try: utils.execute('ip', 'link', 'delete', dev, run_as_root=True, check_exit_code=[0, 2, 254]) LOG.debug("Net device removed: '%s'", dev) except processutils.ProcessExecution...
address', mac_address, run_as_root=True, check_exit_code=[0, 2, 254]) utils.execute('ip', 'link', 'set', dev, 'up', run_as_root=True, check_exit_code=[0, 2, 254]) def delete_net_dev(dev):
64
64
105
6
58
bopopescu/nested_quota
nova/network/linux_net.py
Python
delete_net_dev
delete_net_dev
1,374
1,383
1,374
1,374
56ed4f19b37794ca5bf8881e911d76cc0e5cb576
bigcode/the-stack
train
b12df2666051ed831ddabef5
train
function
def clean_conntrack(fixed_ip): try: _execute('conntrack', '-D', '-r', fixed_ip, run_as_root=True, check_exit_code=[0, 1]) except processutils.ProcessExecutionError: LOG.exception(_('Error deleting conntrack entries for %s'), fixed_ip)
def clean_conntrack(fixed_ip):
try: _execute('conntrack', '-D', '-r', fixed_ip, run_as_root=True, check_exit_code=[0, 1]) except processutils.ProcessExecutionError: LOG.exception(_('Error deleting conntrack entries for %s'), fixed_ip)
' % (floating_ip, fixed_ip))) rules.append(('POSTROUTING', '-s %s -m conntrack --ctstate DNAT -j SNAT ' '--to-source %s' % (fixed_ip, floating_ip))) return rules def clean_conntrack(fixed_ip):
64
64
66
8
55
bopopescu/nested_quota
nova/network/linux_net.py
Python
clean_conntrack
clean_conntrack
820
825
820
820
2853b197e862cbfcdf6b8b850a0f6756240423ac
bigcode/the-stack
train
0e6e50af61767dc2a30e16bf
train
class
class IptablesManager(object): """Wrapper for iptables. See IptablesTable for some usage docs A number of chains are set up to begin with. First, nova-filter-top. It's added at the top of FORWARD and OUTPUT. Its name is not wrapped, so it's shared between the various nova workers. It's intend...
class IptablesManager(object):
"""Wrapper for iptables. See IptablesTable for some usage docs A number of chains are set up to begin with. First, nova-filter-top. It's added at the top of FORWARD and OUTPUT. Its name is not wrapped, so it's shared between the various nova workers. It's intended for rules that need to live ...
wrap, top)) if not wrap: self.remove_rules.append(IptablesRule(chain, rule, wrap, top)) self.dirty = True except ValueError: LOG.warn(_('Tried to remove rule that was not there:' ' %(chain)r %(rule)r %(wrap)r %(top)r'), ...
256
256
2,521
7
249
bopopescu/nested_quota
nova/network/linux_net.py
Python
IptablesManager
IptablesManager
327
630
327
327
15504f7af6c3b0ccca68c4bf45288de69bb03580
bigcode/the-stack
train
3da2dc7bec94caebaf9718b8
train
function
def delete_ivs_vif_port(dev): utils.execute('ivs-ctl', 'del-port', dev, run_as_root=True) utils.execute('ip', 'link', 'delete', dev, run_as_root=True)
def delete_ivs_vif_port(dev):
utils.execute('ivs-ctl', 'del-port', dev, run_as_root=True) utils.execute('ip', 'link', 'delete', dev, run_as_root=True)
if-exists', 'del-port', bridge, dev]) delete_net_dev(dev) def create_ivs_vif_port(dev, iface_id, mac, instance_id): utils.execute('ivs-ctl', 'add-port', dev, run_as_root=True) def delete_ivs_vif_port(dev):
64
64
49
9
55
bopopescu/nested_quota
nova/network/linux_net.py
Python
delete_ivs_vif_port
delete_ivs_vif_port
1,351
1,355
1,351
1,351
63f93afa45c3b07114deea76a3e6e3295423cd6e
bigcode/the-stack
train
01f85bdc3cbcf3c65722c5a0
train
function
def remove_floating_forward(floating_ip, fixed_ip, device, network): """Remove forwarding for floating ip.""" for chain, rule in floating_forward_rules(floating_ip, fixed_ip, device): iptables_manager.ipv4['nat'].remove_rule(chain, rule) iptables_manager.apply() if device != network['bridge']: ...
def remove_floating_forward(floating_ip, fixed_ip, device, network):
"""Remove forwarding for floating ip.""" for chain, rule in floating_forward_rules(floating_ip, fixed_ip, device): iptables_manager.ipv4['nat'].remove_rule(chain, rule) iptables_manager.apply() if device != network['bridge']: remove_ebtables_rules(*floating_ebtables_rules(fixed_ip, netwo...
iptables_manager.ipv4['nat'].add_rule(chain, rule) iptables_manager.apply() if device != network['bridge']: ensure_ebtables_rules(*floating_ebtables_rules(fixed_ip, network)) def remove_floating_forward(floating_ip, fixed_ip, device, network):
64
64
90
16
48
bopopescu/nested_quota
nova/network/linux_net.py
Python
remove_floating_forward
remove_floating_forward
786
792
786
786
0d6e4a13bba4d67a3f1900ddfd8d26f6cf432720
bigcode/the-stack
train
40d2c329855e6650a961d315
train
function
def _host_dns(fixedip): return '%s\t%s.%s' % (fixedip.address, fixedip.instance.hostname, CONF.dhcp_domain)
def _host_dns(fixedip):
return '%s\t%s.%s' % (fixedip.address, fixedip.instance.hostname, CONF.dhcp_domain)
.instance.hostname, CONF.dhcp_domain, fixedip.address, net) else: return '%s,%s.%s,%s' % (fixedip.virtual_interface.address, fixedip.instance.hostname, C...
64
64
35
8
56
bopopescu/nested_quota
nova/network/linux_net.py
Python
_host_dns
_host_dns
1,204
1,207
1,204
1,204
4b89adf746884a009fb6d8395bb840e3fbefbe42
bigcode/the-stack
train
5187859aa8d4d0450191a53a
train
function
def create_ivs_vif_port(dev, iface_id, mac, instance_id): utils.execute('ivs-ctl', 'add-port', dev, run_as_root=True)
def create_ivs_vif_port(dev, iface_id, mac, instance_id):
utils.execute('ivs-ctl', 'add-port', dev, run_as_root=True)
_set_device_mtu(dev) def delete_ovs_vif_port(bridge, dev): _ovs_vsctl(['--', '--if-exists', 'del-port', bridge, dev]) delete_net_dev(dev) def create_ivs_vif_port(dev, iface_id, mac, instance_id):
64
64
37
17
47
bopopescu/nested_quota
nova/network/linux_net.py
Python
create_ivs_vif_port
create_ivs_vif_port
1,346
1,348
1,346
1,346
83c958d461986430bfe8e6077a158cd7da0c45d6
bigcode/the-stack
train
c29f71bdfd4d748264141137
train
function
def _dhcp_file(dev, kind): """Return path to a pid, leases, hosts or conf file for a bridge/device.""" fileutils.ensure_tree(CONF.networks_path) return os.path.abspath('%s/nova-%s.%s' % (CONF.networks_path, dev, kind...
def _dhcp_file(dev, kind):
"""Return path to a pid, leases, hosts or conf file for a bridge/device.""" fileutils.ensure_tree(CONF.networks_path) return os.path.abspath('%s/nova-%s.%s' % (CONF.networks_path, dev, kind))
join(map(str, cmd))) return 'fake', 0 else: return utils.execute(*cmd, **kwargs) def device_exists(device): """Check if ethernet device exists.""" return os.path.exists('/sys/class/net/%s' % device) def _dhcp_file(dev, kind):
64
64
66
9
55
bopopescu/nested_quota
nova/network/linux_net.py
Python
_dhcp_file
_dhcp_file
1,236
1,241
1,236
1,236
4ac679b2edabef5d761a5fe37f793f57154e683f
bigcode/the-stack
train
91ba93157dcde3335800497b
train
function
def _ra_pid_for(dev): """Returns the pid for prior radvd instance for a bridge/device. Returns None if no pid file exists. If machine has rebooted pid might be incorrect (caller should check). """ pid_file = _ra_file(dev, 'pid') if os.path.exists(pid_file): with open(pid_file, 'r') a...
def _ra_pid_for(dev):
"""Returns the pid for prior radvd instance for a bridge/device. Returns None if no pid file exists. If machine has rebooted pid might be incorrect (caller should check). """ pid_file = _ra_file(dev, 'pid') if os.path.exists(pid_file): with open(pid_file, 'r') as f: retur...
). """ pid_file = _dhcp_file(dev, 'pid') if os.path.exists(pid_file): try: with open(pid_file, 'r') as f: return int(f.read()) except (ValueError, IOError): return None def _ra_pid_for(dev):
64
64
86
7
56
bopopescu/nested_quota
nova/network/linux_net.py
Python
_ra_pid_for
_ra_pid_for
1,270
1,282
1,270
1,270
d6b76076ef8d948f0b66ee0765032e4208bf1358
bigcode/the-stack
train
a3f8932c26315e6b3e5f26c9
train
function
def _get_interface_driver(): global interface_driver if not interface_driver: interface_driver = importutils.import_object( CONF.linuxnet_interface_driver) return interface_driver
def _get_interface_driver():
global interface_driver if not interface_driver: interface_driver = importutils.import_object( CONF.linuxnet_interface_driver) return interface_driver
node # code uses a flexible driver model to support different ways # of creating ethernet interfaces and attaching them to the network. # In the case of a network host, these interfaces # act as gateway/dhcp/vpn/etc. endpoints not VM interfaces. interface_driver = None def _get_interface_driver():
64
64
39
6
57
bopopescu/nested_quota
nova/network/linux_net.py
Python
_get_interface_driver
_get_interface_driver
1,394
1,399
1,394
1,394
cabcbe332c22a3aff656a928aef0e6e471055100
bigcode/the-stack
train
f18dc0dd0d321a823aa937a8
train
function
def _remove_dnsmasq_accept_rules(dev): """Remove DHCP and DNS traffic allowed through to dnsmasq.""" table = iptables_manager.ipv4['filter'] for port in [67, 53]: for proto in ['udp', 'tcp']: args = {'dev': dev, 'port': port, 'proto': proto} table.remove_rule('INPUT', ...
def _remove_dnsmasq_accept_rules(dev):
"""Remove DHCP and DNS traffic allowed through to dnsmasq.""" table = iptables_manager.ipv4['filter'] for port in [67, 53]: for proto in ['udp', 'tcp']: args = {'dev': dev, 'port': port, 'proto': proto} table.remove_rule('INPUT', '-i %(dev)s -p %(pr...
'port': port, 'proto': proto} table.add_rule('INPUT', '-i %(dev)s -p %(proto)s -m %(proto)s ' '--dport %(port)s -j ACCEPT' % args) iptables_manager.apply() def _remove_dnsmasq_accept_rules(dev):
64
64
118
10
54
bopopescu/nested_quota
nova/network/linux_net.py
Python
_remove_dnsmasq_accept_rules
_remove_dnsmasq_accept_rules
941
950
941
941
aa21cc1746188ad2bdcc0d17b736b489d4e4ebe0
bigcode/the-stack
train
7cb5648f90ba1710f78abb8e
train
class
class LinuxBridgeInterfaceDriver(LinuxNetInterfaceDriver): def plug(self, network, mac_address, gateway=True): vlan = network.get('vlan') if vlan is not None: iface = CONF.vlan_interface or network['bridge_interface'] LinuxBridgeInterfaceDriver.ensure_vlan_bridge( ...
class LinuxBridgeInterfaceDriver(LinuxNetInterfaceDriver):
def plug(self, network, mac_address, gateway=True): vlan = network.get('vlan') if vlan is not None: iface = CONF.vlan_interface or network['bridge_interface'] LinuxBridgeInterfaceDriver.ensure_vlan_bridge( vlan, network['b...
different ways # of creating ethernet interfaces and attaching them to the network. # In the case of a network host, these interfaces # act as gateway/dhcp/vpn/etc. endpoints not VM interfaces. interface_driver = None def _get_interface_driver(): global interface_driver if not interface_driver: inter...
256
256
1,966
11
244
bopopescu/nested_quota
nova/network/linux_net.py
Python
LinuxBridgeInterfaceDriver
LinuxBridgeInterfaceDriver
1,433
1,639
1,433
1,434
4cc18e89c43c99a6133b90586ff6d625c3bb84f3
bigcode/the-stack
train
741e0b0c15fb623a9d57428b
train
class
class IptablesRule(object): """An iptables rule. You shouldn't need to use this class directly, it's only used by IptablesManager. """ def __init__(self, chain, rule, wrap=True, top=False): self.chain = chain self.rule = rule self.wrap = wrap self.top = top de...
class IptablesRule(object):
"""An iptables rule. You shouldn't need to use this class directly, it's only used by IptablesManager. """ def __init__(self, chain, rule, wrap=True, top=False): self.chain = chain self.rule = rule self.wrap = wrap self.top = top def __eq__(self, other): ...
max_chain_name_length - len('-POSTROUTING') == 16) def get_binary_name(): """Grab the name of the binary we're running in.""" return os.path.basename(inspect.stack()[-1][1])[:16] binary_name = get_binary_name() class IptablesRule(object):
64
64
215
7
57
bopopescu/nested_quota
nova/network/linux_net.py
Python
IptablesRule
IptablesRule
150
179
150
150
3abc182f7f3206cba65f0cc563ff7ac47409af79
bigcode/the-stack
train
c993a68f4837b09acde9eaf5
train
function
def _host_lease(fixedip): """Return a host string for an address in leasefile format.""" timestamp = timeutils.utcnow() seconds_since_epoch = calendar.timegm(timestamp.utctimetuple()) return '%d %s %s %s *' % (seconds_since_epoch + CONF.dhcp_lease_time, fixedip.virtual_inte...
def _host_lease(fixedip):
"""Return a host string for an address in leasefile format.""" timestamp = timeutils.utcnow() seconds_since_epoch = calendar.timegm(timestamp.utctimetuple()) return '%d %s %s %s *' % (seconds_since_epoch + CONF.dhcp_lease_time, fixedip.virtual_interface.address, ...
', pid) cmd = ['radvd', '-C', '%s' % _ra_file(dev, 'conf'), '-p', '%s' % _ra_file(dev, 'pid')] _execute(*cmd, run_as_root=True) def _host_lease(fixedip):
64
64
89
9
55
bopopescu/nested_quota
nova/network/linux_net.py
Python
_host_lease
_host_lease
1,174
1,181
1,174
1,174
f5774ea2e6596dc98e6d6d9642f95888e7b861a2
bigcode/the-stack
train
34a7d8aea59656831445aa55
train
function
def _host_dhcp_network(vif_id): return 'NW-%s' % vif_id
def _host_dhcp_network(vif_id):
return 'NW-%s' % vif_id
calendar.timegm(timestamp.utctimetuple()) return '%d %s %s %s *' % (seconds_since_epoch + CONF.dhcp_lease_time, fixedip.virtual_interface.address, fixedip.address, fixedip.instance.hostname or '*') def _host_dhcp_network(vif_...
64
64
21
10
54
bopopescu/nested_quota
nova/network/linux_net.py
Python
_host_dhcp_network
_host_dhcp_network
1,184
1,185
1,184
1,184
a1b15f7c613f1243cb284963e38814a0a1a3e832
bigcode/the-stack
train
7e5435571aacdccd441de3bf
train
function
def _host_dhcp(fixedip): """Return a host string for an address in dhcp-host format.""" if CONF.use_single_default_gateway: net = _host_dhcp_network(fixedip.virtual_interface_id) return '%s,%s.%s,%s,net:%s' % (fixedip.virtual_interface.address, fixedip.instance.hos...
def _host_dhcp(fixedip):
"""Return a host string for an address in dhcp-host format.""" if CONF.use_single_default_gateway: net = _host_dhcp_network(fixedip.virtual_interface_id) return '%s,%s.%s,%s,net:%s' % (fixedip.virtual_interface.address, fixedip.instance.hostname, ...
' % (seconds_since_epoch + CONF.dhcp_lease_time, fixedip.virtual_interface.address, fixedip.address, fixedip.instance.hostname or '*') def _host_dhcp_network(vif_id): return 'NW-%s' % vif_id def _host_dhcp(fixedip):
64
64
129
9
54
bopopescu/nested_quota
nova/network/linux_net.py
Python
_host_dhcp
_host_dhcp
1,188
1,201
1,188
1,188
d634dc98e9c84265230f2c90eb43f4c5aa8b1a5e
bigcode/the-stack
train
22b1055ac5487bf771c8d4ae
train
function
def floating_forward_rules(floating_ip, fixed_ip, device): rules = [] rule = '-s %s -j SNAT --to %s' % (fixed_ip, floating_ip) if device: rules.append(('float-snat', rule + ' -d %s' % fixed_ip)) rules.append(('float-snat', rule + ' -o %s' % device)) else: rules.append(('float-sna...
def floating_forward_rules(floating_ip, fixed_ip, device):
rules = [] rule = '-s %s -j SNAT --to %s' % (fixed_ip, floating_ip) if device: rules.append(('float-snat', rule + ' -d %s' % fixed_ip)) rules.append(('float-snat', rule + ' -o %s' % device)) else: rules.append(('float-snat', rule)) rules.append( ('PREROUTING', '-d...
ING --logical-in %s -p ipv4 --ip-src %s ' '! --ip-dst %s -j redirect --redirect-target ACCEPT' % (network['bridge'], fixed_ip, network['cidr'])], 'nat') def floating_forward_rules(floating_ip, fixed_ip, device):
64
64
205
13
51
bopopescu/nested_quota
nova/network/linux_net.py
Python
floating_forward_rules
floating_forward_rules
802
817
802
802
e12f4f0f7d9c710fc104246ffea74798a88c52f5
bigcode/the-stack
train
3ae731500d5b5be65b4adf14
train
function
@utils.synchronized('lock_gateway', external=True) def initialize_gateway_device(dev, network_ref): if not network_ref: return _enable_ipv4_forwarding() # NOTE(vish): The ip for dnsmasq has to be the first address on the # bridge for it to respond to requests properly try: ...
@utils.synchronized('lock_gateway', external=True) def initialize_gateway_device(dev, network_ref):
if not network_ref: return _enable_ipv4_forwarding() # NOTE(vish): The ip for dnsmasq has to be the first address on the # bridge for it to respond to requests properly try: prefix = network_ref.cidr.prefixlen except AttributeError: prefix = network_ref['cid...
floating_ip))) return rules def clean_conntrack(fixed_ip): try: _execute('conntrack', '-D', '-r', fixed_ip, run_as_root=True, check_exit_code=[0, 1]) except processutils.ProcessExecutionError: LOG.exception(_('Error deleting conntrack entries for %s'), fixed_ip) def _en...
167
167
558
20
147
bopopescu/nested_quota
nova/network/linux_net.py
Python
initialize_gateway_device
initialize_gateway_device
835
888
835
836
afd4ec267cef5d800bd3b22ec86498463c229c03
bigcode/the-stack
train
e339a4699d4952bd6e27c586
train
function
def delete_ovs_vif_port(bridge, dev): _ovs_vsctl(['--', '--if-exists', 'del-port', bridge, dev]) delete_net_dev(dev)
def delete_ovs_vif_port(bridge, dev):
_ovs_vsctl(['--', '--if-exists', 'del-port', bridge, dev]) delete_net_dev(dev)
_id, 'external-ids:iface-status=active', 'external-ids:attached-mac=%s' % mac, 'external-ids:vm-uuid=%s' % instance_id]) _set_device_mtu(dev) def delete_ovs_vif_port(bridge, dev):
64
64
39
12
52
bopopescu/nested_quota
nova/network/linux_net.py
Python
delete_ovs_vif_port
delete_ovs_vif_port
1,341
1,343
1,341
1,341
b1e823ec8d0689bfc8ed3013051fed772a4494d2
bigcode/the-stack
train
be7cd41dda07c416b3f86df2
train
function
def device_exists(device): """Check if ethernet device exists.""" return os.path.exists('/sys/class/net/%s' % device)
def device_exists(device):
"""Check if ethernet device exists.""" return os.path.exists('/sys/class/net/%s' % device)
kwargs): """Wrapper around utils._execute for fake_network.""" if CONF.fake_network: LOG.debug('FAKE NET: %s', ' '.join(map(str, cmd))) return 'fake', 0 else: return utils.execute(*cmd, **kwargs) def device_exists(device):
64
64
28
5
59
bopopescu/nested_quota
nova/network/linux_net.py
Python
device_exists
device_exists
1,231
1,233
1,231
1,231
0b983246abc822b45cbb8c8cb2c0957a9da5fc21
bigcode/the-stack
train
bda08c374ae3b87d1eed4b84
train
function
def add_snat_rule(ip_range, is_external=False): if CONF.routing_source_ip: if is_external: if CONF.force_snat_range: snat_range = CONF.force_snat_range else: snat_range = [] else: snat_range = ['0.0.0.0/0'] for dest_range in...
def add_snat_rule(ip_range, is_external=False):
if CONF.routing_source_ip: if is_external: if CONF.force_snat_range: snat_range = CONF.force_snat_range else: snat_range = [] else: snat_range = ['0.0.0.0/0'] for dest_range in snat_range: rule = ('-s %s -d %s -j...
s -j ACCEPT' % CONF.metadata_host else: rule += ' -m addrtype --dst-type LOCAL -j ACCEPT' iptables_manager.ipv4['filter'].add_rule('INPUT', rule) iptables_manager.apply() def add_snat_rule(ip_range, is_external=False):
64
64
164
12
52
bopopescu/nested_quota
nova/network/linux_net.py
Python
add_snat_rule
add_snat_rule
669
684
669
669
aded969e0b1c9242e91a3b8be0ed82d43dc370ba
bigcode/the-stack
train
fb1ae235e5816ee1ff32eb55
train
function
@utils.synchronized('dnsmasq_start') def restart_dhcp(context, dev, network_ref, fixedips): """(Re)starts a dnsmasq server for a given network. If a dnsmasq instance is already running then send a HUP signal causing it to reload, otherwise spawn a new instance. """ conffile = _dhcp_file(dev, 'conf...
@utils.synchronized('dnsmasq_start') def restart_dhcp(context, dev, network_ref, fixedips):
"""(Re)starts a dnsmasq server for a given network. If a dnsmasq instance is already running then send a HUP signal causing it to reload, otherwise spawn a new instance. """ conffile = _dhcp_file(dev, 'conf') optsfile = _dhcp_file(dev, 'opts') write_to_file(optsfile, get_dhcp_opts(context...
): conffile = _dhcp_file(dev, 'conf') write_to_file(conffile, hosts_text) def kill_dhcp(dev): pid = _dnsmasq_pid_for(dev) if pid: # Check that the process exists and looks like a dnsmasq process conffile = _dhcp_file(dev, 'conf') out, _err = _execute('cat', '/proc/%d/cmdline' %...
238
238
794
24
214
bopopescu/nested_quota
nova/network/linux_net.py
Python
restart_dhcp
restart_dhcp
1,050
1,129
1,050
1,051
bd8b75518c6292c8e766e01fbf764c595abde70d
bigcode/the-stack
train
10e0c524e5c3672726574fe6
train
function
def kill_dhcp(dev): pid = _dnsmasq_pid_for(dev) if pid: # Check that the process exists and looks like a dnsmasq process conffile = _dhcp_file(dev, 'conf') out, _err = _execute('cat', '/proc/%d/cmdline' % pid, check_exit_code=False) if conffile.split(...
def kill_dhcp(dev):
pid = _dnsmasq_pid_for(dev) if pid: # Check that the process exists and looks like a dnsmasq process conffile = _dhcp_file(dev, 'conf') out, _err = _execute('cat', '/proc/%d/cmdline' % pid, check_exit_code=False) if conffile.split('/')[-1] in out: ...
_hosts(context, network_ref)) restart_dhcp(context, dev, network_ref, fixedips) def update_dhcp_hostfile_with_text(dev, hosts_text): conffile = _dhcp_file(dev, 'conf') write_to_file(conffile, hosts_text) def kill_dhcp(dev):
64
64
149
6
58
bopopescu/nested_quota
nova/network/linux_net.py
Python
kill_dhcp
kill_dhcp
1,032
1,044
1,032
1,032
bfbf8ee58f6e32acc23777ca66a6fb5e3cc768c4
bigcode/the-stack
train
bfaa560de5ad9e977f5ac0c4
train
function
def metadata_accept(): """Create the filter accept rule for metadata.""" rule = '-s 0.0.0.0/0 -p tcp -m tcp --dport %s' % CONF.metadata_port if CONF.metadata_host != '127.0.0.1': rule += ' -d %s -j ACCEPT' % CONF.metadata_host else: rule += ' -m addrtype --dst-type LOCAL -j ACCEPT' i...
def metadata_accept():
"""Create the filter accept rule for metadata.""" rule = '-s 0.0.0.0/0 -p tcp -m tcp --dport %s' % CONF.metadata_port if CONF.metadata_host != '127.0.0.1': rule += ' -d %s -j ACCEPT' % CONF.metadata_host else: rule += ' -m addrtype --dst-type LOCAL -j ACCEPT' iptables_manager.ipv4['f...
0.0.0.0/0 -d 169.254.169.254/32 ' '-p tcp -m tcp --dport 80 ' '-j REDIRECT --to-ports %s' % CONF.metadata_port) iptables_manager.apply() def metadata_accept():
64
64
120
4
60
bopopescu/nested_quota
nova/network/linux_net.py
Python
metadata_accept
metadata_accept
658
666
658
658
78ef58f4c562e70b7207696916e02c52b2c6ce31
bigcode/the-stack
train
ee7a443a4073e85c737b43bc
train
function
def _create_veth_pair(dev1_name, dev2_name): """Create a pair of veth devices with the specified names, deleting any previous devices with those names. """ for dev in [dev1_name, dev2_name]: delete_net_dev(dev) utils.execute('ip', 'link', 'add', dev1_name, 'type', 'veth', 'peer', ...
def _create_veth_pair(dev1_name, dev2_name):
"""Create a pair of veth devices with the specified names, deleting any previous devices with those names. """ for dev in [dev1_name, dev2_name]: delete_net_dev(dev) utils.execute('ip', 'link', 'add', dev1_name, 'type', 'veth', 'peer', 'name', dev2_name, run_as_root=True) ...
= CONF.network_device_mtu if mtu: utils.execute('ip', 'link', 'set', dev, 'mtu', mtu, run_as_root=True, check_exit_code=[0, 2, 254]) def _create_veth_pair(dev1_name, dev2_name):
64
64
167
14
50
bopopescu/nested_quota
nova/network/linux_net.py
Python
_create_veth_pair
_create_veth_pair
1,304
1,317
1,304
1,304
02f80cf659f98ee2e3690b9ee3e425e32b08a613
bigcode/the-stack
train
982f97787e7e23598ff856d5
train
function
def release_dhcp(dev, address, mac_address): try: utils.execute('dhcp_release', dev, address, mac_address, run_as_root=True) except processutils.ProcessExecutionError: raise exception.NetworkDhcpReleaseFailed(address=address, ...
def release_dhcp(dev, address, mac_address):
try: utils.execute('dhcp_release', dev, address, mac_address, run_as_root=True) except processutils.ProcessExecutionError: raise exception.NetworkDhcpReleaseFailed(address=address, mac_address=mac_address)
hosts.append(_host_dhcp_opts(vif_id, gateway)) else: hosts.append(_host_dhcp_opts(vif_id)) else: hosts.append(_host_dhcp_opts(None, gateway)) return '\n'.join(hosts) def release_dhcp(dev, address, mac_address):
64
64
62
11
53
bopopescu/nested_quota
nova/network/linux_net.py
Python
release_dhcp
release_dhcp
994
1,000
994
994
56474cb385e26f567e2d3f998c51b82042160899
bigcode/the-stack
train
44e0ac49981b53158ab5ca75
train
function
def create_tap_dev(dev, mac_address=None): if not device_exists(dev): try: # First, try with 'ip' utils.execute('ip', 'tuntap', 'add', dev, 'mode', 'tap', run_as_root=True, check_exit_code=[0, 2, 254]) except processutils.ProcessExecutionError: ...
def create_tap_dev(dev, mac_address=None):
if not device_exists(dev): try: # First, try with 'ip' utils.execute('ip', 'tuntap', 'add', dev, 'mode', 'tap', run_as_root=True, check_exit_code=[0, 2, 254]) except processutils.ProcessExecutionError: # Second option: tunctl ...
_as_root=True) def delete_ivs_vif_port(dev): utils.execute('ivs-ctl', 'del-port', dev, run_as_root=True) utils.execute('ip', 'link', 'delete', dev, run_as_root=True) def create_tap_dev(dev, mac_address=None):
64
64
184
11
53
bopopescu/nested_quota
nova/network/linux_net.py
Python
create_tap_dev
create_tap_dev
1,358
1,371
1,358
1,358
526429c25d76237bca1df8e8163ef36ce626c0bf
bigcode/the-stack
train
dc3c5db9298eed4ee49531f8
train
class
class NewInstallViewModel(ViewModelBase): def __init__(self): self.team_id = None self.name = None self.city = None self.team_abbr = None self.league = None self.division = None self.division_abbr = None self.division_id = None def from_dict(self,...
class NewInstallViewModel(ViewModelBase):
def __init__(self): self.team_id = None self.name = None self.city = None self.team_abbr = None self.league = None self.division = None self.division_abbr = None self.division_id = None def from_dict(self, data_dict): self.team_id = data_d...
from mlbpool.viewmodels.viewmodelbase import ViewModelBase class NewInstallViewModel(ViewModelBase):
22
64
179
9
12
prcutler/mlbpool2
mlbpool/viewmodels/newinstallviewmodel.py
Python
NewInstallViewModel
NewInstallViewModel
4
23
4
4
6ad7a8e02d7b79fa23bea744e6d9cd07f8da0d85
bigcode/the-stack
train
56be7503a25bf3f303d40857
train
function
def pick_peaks(arr): retDictionary = {"pos": [], "peaks": []} counter = 1 storeRemoved = [] while counter < len(arr) - 1: possiblePeak = arr[counter] if possiblePeak == arr[counter + 1]: while possiblePeak == arr[counter + 1]: arr.pop(counter + 1) storeRemoved.append(counter + 1) ...
def pick_peaks(arr):
retDictionary = {"pos": [], "peaks": []} counter = 1 storeRemoved = [] while counter < len(arr) - 1: possiblePeak = arr[counter] if possiblePeak == arr[counter + 1]: while possiblePeak == arr[counter + 1]: arr.pop(counter + 1) storeRemoved.append(counter + 1) if counter >= ...
# see https://www.codewars.com/kata/5279f6fe5ab7f447890006a7/train/python def pick_peaks(arr):
34
64
187
6
27
KonstantinosAng/CodeWars
Python/[5 kyu] Pick peaks.py
Python
pick_peaks
pick_peaks
3
23
3
3
e1ce1bc91017227140f0fde5aced4569a89e768a
bigcode/the-stack
train
18f21b97c42e1a6f4a883480
train
class
class pascal_voc(object): def __init__(self, phase, rebuild=False): self.devkil_path = os.path.join(cfg.PASCAL_PATH, 'VOCdevkit') self.data_path = os.path.join(self.devkil_path, 'VOC2007') self.cache_path = cfg.CACHE_PATH self.batch_size = cfg.BATCH_SIZE self.image_size = cfg...
class pascal_voc(object):
def __init__(self, phase, rebuild=False): self.devkil_path = os.path.join(cfg.PASCAL_PATH, 'VOCdevkit') self.data_path = os.path.join(self.devkil_path, 'VOC2007') self.cache_path = cfg.CACHE_PATH self.batch_size = cfg.BATCH_SIZE self.image_size = cfg.IMAGE_SIZE self.c...
import os import xml.etree.ElementTree as ET import numpy as np import cv2 import pickle import copy import yolo.config as cfg class pascal_voc(object):
41
256
1,445
7
33
PeterChenYijie/DeepLearningZeroToALL
Computer-vision/@PeterChenYijie yolo-tensorflow/utils/pascal_voc.py
Python
pascal_voc
pascal_voc
10
140
10
10
eb265fc5324a18dc403d870d7d48852a93f7b04f
bigcode/the-stack
train
67f59244acd5512b9067eff3
train
function
def freeze_and_center_by_name(obj): cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) cmds.CenterPivot(obj) print("Freeze and Center done for {0}".format(obj))
def freeze_and_center_by_name(obj):
cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) cmds.CenterPivot(obj) print("Freeze and Center done for {0}".format(obj))
) for obj in objs: cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) cmds.CenterPivot(obj) print("Freeze and Center done for {0}".format(obj)) def freeze_and_center_by_name(obj):
64
64
57
8
56
kspace5/mcake
generic_utils/base.py
Python
freeze_and_center_by_name
freeze_and_center_by_name
28
31
28
28
1246821947fa63c6349f4308289b8331b22882b1
bigcode/the-stack
train
ebb75c739b4683a258b43435
train
function
def duplicate_and_mirror(): objs = cmds.ls(sl=True) for obj in objs: ret = cmds.duplicate(obj, returnRootsOnly=True) cmds.scale(-1, 1, 1, obj) print("duplicate_and_mirror done for {0}".format(ret))
def duplicate_and_mirror():
objs = cmds.ls(sl=True) for obj in objs: ret = cmds.duplicate(obj, returnRootsOnly=True) cmds.scale(-1, 1, 1, obj) print("duplicate_and_mirror done for {0}".format(ret))
(): objs = cmds.ls(sl=True) for obj in objs: cmds.move(0, 0, 0, obj + ".scalePivot",obj + ".rotatePivot", absolute=True) print("zero_x_pivot done for {0}".format(obj)) def duplicate_and_mirror():
64
64
63
6
58
kspace5/mcake
generic_utils/base.py
Python
duplicate_and_mirror
duplicate_and_mirror
43
48
43
43
d5dc24e5de878f6a3883e0ca133a137911ecccf7
bigcode/the-stack
train
52a6b2fb91aaa8e97f94f99d
train
function
def move_to_z_pos_of(src_obj, trg_obj): cur_loc = get_world_pos(trg_obj) loc = get_world_pos(src_obj) cmds.move(cur_loc[0],cur_loc[1], loc[2], trg_obj, absolute=True)
def move_to_z_pos_of(src_obj, trg_obj):
cur_loc = get_world_pos(trg_obj) loc = get_world_pos(src_obj) cmds.move(cur_loc[0],cur_loc[1], loc[2], trg_obj, absolute=True)
print('loc', loc[1]) cmds.move(cur_loc[0],loc[1], cur_loc[2], trg_obj, absolute=True) #cmds.move(0, 10, 0, trg_obj, absolute=False) def move_to_z_pos_of(src_obj, trg_obj):
64
64
54
12
52
kspace5/mcake
generic_utils/base.py
Python
move_to_z_pos_of
move_to_z_pos_of
77
80
77
77
68d111160f8158f47b8e052843a93a0cf5f9f1af
bigcode/the-stack
train
9712a0f289c6959aa2855391
train
function
def set_driven_key(driver_attr, driven_attr, driver_val, driven_val): cmds.setDrivenKeyframe(driven_attr, cd=driver_attr, dv=driver_val, v=driven_val)
def set_driven_key(driver_attr, driven_attr, driver_val, driven_val):
cmds.setDrivenKeyframe(driven_attr, cd=driver_attr, dv=driver_val, v=driven_val)
'], min=p['min'], max=p['max'], dv=p['default'], k=p['keyable']) # example: gu.set_driven_key(n + '.toeRaise','joint1.rotateX', 120, 120) def set_driven_key(driver_attr, driven_attr, driver_val, driven_val):
64
64
44
17
47
kspace5/mcake
generic_utils/base.py
Python
set_driven_key
set_driven_key
88
89
88
88
890437bcfaa354322744ca310907b0c1169442f7
bigcode/the-stack
train
f890545fce06a7391380766c
train
function
def duplicate_and_mirror_x(): freeze_and_center() zero_x_pivot() duplicate_and_mirror()
def duplicate_and_mirror_x():
freeze_and_center() zero_x_pivot() duplicate_and_mirror()
) for obj in objs: ret = cmds.duplicate(obj, returnRootsOnly=True) cmds.scale(-1, 1, 1, obj) print("duplicate_and_mirror done for {0}".format(ret)) # Do all above (3 methods) def duplicate_and_mirror_x():
64
64
24
7
57
kspace5/mcake
generic_utils/base.py
Python
duplicate_and_mirror_x
duplicate_and_mirror_x
51
54
51
51
70d66a588d7b2597ff72b98e5c9e2f6f8620bab5
bigcode/the-stack
train
dfd053bfdeeb9f16d520285d
train
function
def rename_selected_by_replace(old_str, new_str): objs = cmds.ls(sl=True) for obj in objs: str = obj.replace(old_str, new_str) print(str) cmds.rename(obj, str) print("Done for " + obj)
def rename_selected_by_replace(old_str, new_str):
objs = cmds.ls(sl=True) for obj in objs: str = obj.replace(old_str, new_str) print(str) cmds.rename(obj, str) print("Done for " + obj)
from __future__ import print_function import maya.cmds as cmds # Mass rename with string replace def rename_selected_by_replace(old_str, new_str):
33
64
57
11
21
kspace5/mcake
generic_utils/base.py
Python
rename_selected_by_replace
rename_selected_by_replace
5
11
5
5
d13d80d37ed3eb4da563d4d04b656d22f5192f90
bigcode/the-stack
train
a775f71de9b4cded22f1867f
train
function
def freeze_and_center(): objs = cmds.ls(sl=True) for obj in objs: cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) cmds.CenterPivot(obj) print("Freeze and Center done for {0}".format(obj))
def freeze_and_center():
objs = cmds.ls(sl=True) for obj in objs: cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) cmds.CenterPivot(obj) print("Freeze and Center done for {0}".format(obj))
.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) print("Freeze transformations done for {0}".format(obj)) # Does center pivot and freeze transforma on all rename_selected_by_replace # Super useful method def freeze_and_center():
64
64
69
5
58
kspace5/mcake
generic_utils/base.py
Python
freeze_and_center
freeze_and_center
21
26
21
21
d9fcd6845cbfdfe4216c8ef2d7d2853290a14556
bigcode/the-stack
train
1bb7830e52383e3e5497c05f
train
function
def move_to_y_pos_of(src_obj, trg_obj): cur_loc = get_world_pos(trg_obj) loc = get_world_pos(src_obj) print('loc', loc[1]) cmds.move(cur_loc[0],loc[1], cur_loc[2], trg_obj, absolute=True)
def move_to_y_pos_of(src_obj, trg_obj):
cur_loc = get_world_pos(trg_obj) loc = get_world_pos(src_obj) print('loc', loc[1]) cmds.move(cur_loc[0],loc[1], cur_loc[2], trg_obj, absolute=True)
_to_x_pos_of(src_obj, trg_obj): cur_loc = get_world_pos(trg_obj) loc = get_world_pos(src_obj) cmds.move(loc[0],cur_loc[1], cur_loc[2], trg_obj, absolute=True) def move_to_y_pos_of(src_obj, trg_obj):
64
64
63
12
52
kspace5/mcake
generic_utils/base.py
Python
move_to_y_pos_of
move_to_y_pos_of
70
74
70
70
c393fdc79952c7c891931560cbc26d16ddda6449
bigcode/the-stack
train
fdf5a29e71d28a050756fda3
train
function
def freeze_all_selected(): objs = cmds.ls(sl=True) for obj in objs: cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) print("Freeze transformations done for {0}".format(obj))
def freeze_all_selected():
objs = cmds.ls(sl=True) for obj in objs: cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) print("Freeze transformations done for {0}".format(obj))
replace def rename_selected_by_replace(old_str, new_str): objs = cmds.ls(sl=True) for obj in objs: str = obj.replace(old_str, new_str) print(str) cmds.rename(obj, str) print("Done for " + obj) def freeze_all_selected():
64
64
62
5
59
kspace5/mcake
generic_utils/base.py
Python
freeze_all_selected
freeze_all_selected
13
17
13
13
3b848f6df2f9cdc7b6f203b213a288fd22a638d7
bigcode/the-stack
train
f5200052a924f287e603f5cd
train
function
def move_to_pos_of(src_obj, trg_obj): loc = get_world_pos(src_obj) cmds.move(loc[0],loc[1], loc[2], trg_obj, absolute=True)
def move_to_pos_of(src_obj, trg_obj):
loc = get_world_pos(src_obj) cmds.move(loc[0],loc[1], loc[2], trg_obj, absolute=True)
array as in [0.0, 94.11794271192076, -5.187759884926814] def get_world_pos(obj): loc = cmds.xform(obj, q=True, ws=True, rp=True) return loc def move_to_pos_of(src_obj, trg_obj):
64
64
41
11
52
kspace5/mcake
generic_utils/base.py
Python
move_to_pos_of
move_to_pos_of
61
63
61
61
759b358e744450c0f05dae67d4d1a58c845e1bf2
bigcode/the-stack
train
a2c2f42120b6fe3e492a569f
train
function
def move_to_x_pos_of(src_obj, trg_obj): cur_loc = get_world_pos(trg_obj) loc = get_world_pos(src_obj) cmds.move(loc[0],cur_loc[1], cur_loc[2], trg_obj, absolute=True)
def move_to_x_pos_of(src_obj, trg_obj):
cur_loc = get_world_pos(trg_obj) loc = get_world_pos(src_obj) cmds.move(loc[0],cur_loc[1], cur_loc[2], trg_obj, absolute=True)
, ws=True, rp=True) return loc def move_to_pos_of(src_obj, trg_obj): loc = get_world_pos(src_obj) cmds.move(loc[0],loc[1], loc[2], trg_obj, absolute=True) def move_to_x_pos_of(src_obj, trg_obj):
64
64
54
12
52
kspace5/mcake
generic_utils/base.py
Python
move_to_x_pos_of
move_to_x_pos_of
65
68
65
65
1cdefc3c0dd845eb8d5f5885d6f27d263a1a7466
bigcode/the-stack
train
0d408043a0cce991a18fa57d
train
function
def get_world_pos(obj): loc = cmds.xform(obj, q=True, ws=True, rp=True) return loc
def get_world_pos(obj):
loc = cmds.xform(obj, q=True, ws=True, rp=True) return loc
above (3 methods) def duplicate_and_mirror_x(): freeze_and_center() zero_x_pivot() duplicate_and_mirror() # return an array as in [0.0, 94.11794271192076, -5.187759884926814] def get_world_pos(obj):
64
64
27
6
58
kspace5/mcake
generic_utils/base.py
Python
get_world_pos
get_world_pos
57
59
57
57
fc9eb61f6fef6479c8c08e8e554bb321d6e535a6
bigcode/the-stack
train
63292597d1ea0da6139beebf
train
function
def add_attribute(tgt, name, **p): cmds.addAttr(tgt, ln=name, at=p['type'], min=p['min'], max=p['max'], dv=p['default'], k=p['keyable'])
def add_attribute(tgt, name, **p):
cmds.addAttr(tgt, ln=name, at=p['type'], min=p['min'], max=p['max'], dv=p['default'], k=p['keyable'])
],cur_loc[1], loc[2], trg_obj, absolute=True) # Custom Attributes # example: gu.add_attribute(tgt, 'toeRaise', type='float', min=0, max=120, default=0, keyable=True) def add_attribute(tgt, name, **p):
64
64
47
11
53
kspace5/mcake
generic_utils/base.py
Python
add_attribute
add_attribute
84
85
84
84
bfc873b62380d7bc990e6a24e036c69001996d62
bigcode/the-stack
train
8787e2d93b6ba53afcd252a9
train
function
def freeze_transformations_by_name(obj): cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) print("Freeze Trans done for {0}".format(obj))
def freeze_transformations_by_name(obj):
cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) print("Freeze Trans done for {0}".format(obj))
freeze_and_center_by_name(obj): cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) cmds.CenterPivot(obj) print("Freeze and Center done for {0}".format(obj)) def freeze_transformations_by_name(obj):
64
64
50
8
56
kspace5/mcake
generic_utils/base.py
Python
freeze_transformations_by_name
freeze_transformations_by_name
33
35
33
33
bd5d70f74063d589f673c5f19a358641b820eaaf
bigcode/the-stack
train
4b3094e27b018bcc3392c68c
train
function
def zero_x_pivot(): objs = cmds.ls(sl=True) for obj in objs: cmds.move(0, 0, 0, obj + ".scalePivot",obj + ".rotatePivot", absolute=True) print("zero_x_pivot done for {0}".format(obj))
def zero_x_pivot():
objs = cmds.ls(sl=True) for obj in objs: cmds.move(0, 0, 0, obj + ".scalePivot",obj + ".rotatePivot", absolute=True) print("zero_x_pivot done for {0}".format(obj))
done for {0}".format(obj)) def freeze_transformations_by_name(obj): cmds.makeIdentity(obj, apply=True, t=1, r=1, s=1, n=0, pn=1) print("Freeze Trans done for {0}".format(obj)) def zero_x_pivot():
64
64
63
6
58
kspace5/mcake
generic_utils/base.py
Python
zero_x_pivot
zero_x_pivot
37
41
37
37
2dda6b4ecf1343288078c6891a4c7481413e34f8
bigcode/the-stack
train
1f92fc835819ceb3c56cdd84
train
function
def exception_handler(exc, context): """ 自定义异常处理, 捕获或有异常 :param exc: 异常 :param context: 抛出异常的上下文 :return: Response响应对象 """ if isinstance(exc, Http404): exc = exceptions.NotFound() elif isinstance(exc, PermissionDenied): exc = exceptions.PermissionDenied() if isinstan...
def exception_handler(exc, context):
""" 自定义异常处理, 捕获或有异常 :param exc: 异常 :param context: 抛出异常的上下文 :return: Response响应对象 """ if isinstance(exc, Http404): exc = exceptions.NotFound() elif isinstance(exc, PermissionDenied): exc = exceptions.PermissionDenied() if isinstance(exc, exceptions.APIException): ...
(v, list) and isinstance(v[0], ErrorDetail): message += str(k) message += ''.join([str(x) for x in v]) elif isinstance(v, list) and isinstance(v[0], dict): for value_dict in v: mes...
132
132
442
7
124
DingGuodong/drf_admin
drf_admin/utils/exceptions.py
Python
exception_handler
exception_handler
65
112
65
65
c5891da427b9a98f97dda3b16950ecbc308179c3
bigcode/the-stack
train
a456c0051ca6103b31ca5e3b
train
function
def write_error_logs(exc, context, detail): """ 记录错误日志信息 :param exc: 异常 :param context: 抛出异常的上下文 :param detail: 异常详情 :return: """ data = { 'username': context['request'].user.username if context['request'].user.username else 'AnonymousUser', 'view': context['view'].get_vi...
def write_error_logs(exc, context, detail):
""" 记录错误日志信息 :param exc: 异常 :param context: 抛出异常的上下文 :param detail: 异常详情 :return: """ data = { 'username': context['request'].user.username if context['request'].user.username else 'AnonymousUser', 'view': context['view'].get_view_name(), 'desc': exc.__str__(), ...
_exc() write_error_logs(exc, context, detail) logger.error('[%s] %s' % (view, detail)) response = Response({'detail': '服务端未知错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return response def write_error_logs(exc, context, detail):
64
64
131
10
53
DingGuodong/drf_admin
drf_admin/utils/exceptions.py
Python
write_error_logs
write_error_logs
115
130
115
115
5ff51f67d9fc0a86fe7606eca9407d19814db50f
bigcode/the-stack
train
273fd0c589c144d1d31442f4
train
function
def errors_handler(exc): """ 自定义, 错误消息格式处理 :param exc: :return: data: 错误消息 """ try: if isinstance(exc.detail, list): msg = ''.join([str(x) for x in exc.detail]) elif isinstance(exc.detail, dict): def search_error(detail: dict, message: str): ...
def errors_handler(exc):
""" 自定义, 错误消息格式处理 :param exc: :return: data: 错误消息 """ try: if isinstance(exc.detail, list): msg = ''.join([str(x) for x in exc.detail]) elif isinstance(exc.detail, dict): def search_error(detail: dict, message: str): for k, v in detail.item...
from redis.exceptions import RedisError from rest_framework import status, exceptions from rest_framework.exceptions import ErrorDetail from rest_framework.response import Response from rest_framework.views import set_rollback # 获取在配置文件中定义的logger,用来记录日志 from monitor.models import ErrorLogs from oauth.utils import get_...
81
81
270
5
76
DingGuodong/drf_admin
drf_admin/utils/exceptions.py
Python
errors_handler
errors_handler
27
62
27
27
63b9e12ff5bd31697b2c13f3328ee605f284a7ec
bigcode/the-stack
train
dd483bed172f8c4a5ac3b3ec
train
class
class Model(nn.Module): def __init__(self): super(Model, self).__init__() def forward(self, x): x = F.upsample_bilinear(x, size=(12,12)) x = F.upsample_bilinear(x, scale_factor=2) return x
class Model(nn.Module):
def __init__(self): super(Model, self).__init__() def forward(self, x): x = F.upsample_bilinear(x, size=(12,12)) x = F.upsample_bilinear(x, scale_factor=2) return x
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module):
64
64
66
5
58
fzyzcjy/ncnn
tools/pnnx/tests/test_F_upsample_bilinear.py
Python
Model
Model
19
26
19
19
0897c52142bc4222b0b01c20ecccbfc9b4015bd7
bigcode/the-stack
train
b9dbc23a8ba611972d5584f7
train
function
def test(): net = Model() net.eval() torch.manual_seed(0) x = torch.rand(1, 12, 24, 64) a = net(x) # export torchscript mod = torch.jit.trace(net, x) mod.save("test_F_upsample_bilinear.pt") # torchscript to pnnx import os os.system("../src/pnnx test_F_upsample_bilinear.pt...
def test():
net = Model() net.eval() torch.manual_seed(0) x = torch.rand(1, 12, 24, 64) a = net(x) # export torchscript mod = torch.jit.trace(net, x) mod.save("test_F_upsample_bilinear.pt") # torchscript to pnnx import os os.system("../src/pnnx test_F_upsample_bilinear.pt inputshape=...
def __init__(self): super(Model, self).__init__() def forward(self, x): x = F.upsample_bilinear(x, size=(12,12)) x = F.upsample_bilinear(x, scale_factor=2) return x def test():
64
64
162
3
60
fzyzcjy/ncnn
tools/pnnx/tests/test_F_upsample_bilinear.py
Python
test
test
28
49
28
28
e82d17d1c1ee88c704cf265588e6762683084563
bigcode/the-stack
train
27ab0ad7c880dddb299ffbc6
train
function
def penjumlahan(a, b): hasil = a + b return hasil
def penjumlahan(a, b):
hasil = a + b return hasil
def penjumlahan(a, b):
9
64
20
9
0
Ariful2607/StrukturData21221
Minggu 04 - Fungsi Rekursif/01 function penjumlahan/penjumlahan.py
Python
penjumlahan
penjumlahan
1
3
1
1
f714c7b8148a299905df12651492346014805b8c
bigcode/the-stack
train
32534dc5a158205181d5edc8
train
class
class BaseMaskGenerator: def __init__(self, name="base"): self.name = name def generate(self, *arg, **kwargs): raise NotImplementedError("Please implement subclass")
class BaseMaskGenerator:
def __init__(self, name="base"): self.name = name def generate(self, *arg, **kwargs): raise NotImplementedError("Please implement subclass")
class BaseMaskGenerator:
5
64
43
5
0
pedrofreitascampospro/locintel
locintel/graphs/masks/generate/base.py
Python
BaseMaskGenerator
BaseMaskGenerator
1
6
1
1
ac1150c4d9015058ce2032455282254d886948cb
bigcode/the-stack
train
65a55d9199cf85727c4a6e3e
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Achievements', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
class Migration(migrations.Migration):
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Achievements', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('details', models.TextField(blank=T...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-09-19 18:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
52
185
619
7
44
dheeraj-sn/my_website
resume/migrations/0001_initial.py
Python
Migration
Migration
8
86
8
9
6a301a2da42cdffdf60d0de25870c442a8fad4a0
bigcode/the-stack
train
5e497ed5053ba31b7e191def
train
class
class Python(BaseQueryRunner): @classmethod def configuration_schema(cls): return { 'type': 'object', 'properties': { 'allowedImportModules': { 'type': 'string', 'title': 'Modules to import prior to running the script' ...
class Python(BaseQueryRunner): @classmethod
def configuration_schema(cls): return { 'type': 'object', 'properties': { 'allowedImportModules': { 'type': 'string', 'title': 'Modules to import prior to running the script' } }, } @clas...
import datetime import json import logging from redash.query_runner import * from redash import models import importlib logger = logging.getLogger(__name__) from RestrictedPython import compile_restricted from RestrictedPython.Guards import safe_builtins class CustomPrint(object): """ CustomPrint redirect "pr...
187
256
1,450
10
176
steedos/redash
redash/query_runner/python.py
Python
Python
Python
38
223
38
39
26bd2a1aab36498ebbb984d9e54f691200e06e5a
bigcode/the-stack
train
00a5acb15f7bee8a25a1c02f
train
class
class CustomPrint(object): """ CustomPrint redirect "print" calls to be sent as "log" on the result object """ def __init__(self): self.enabled = True self.lines = [] def write(self, text): if self.enabled: if text and text.strip(): log_line = "[{0}] {1}"...
class CustomPrint(object):
""" CustomPrint redirect "print" calls to be sent as "log" on the result object """ def __init__(self): self.enabled = True self.lines = [] def write(self, text): if self.enabled: if text and text.strip(): log_line = "[{0}] {1}".format(datetime.datetime.u...
import datetime import json import logging from redash.query_runner import * from redash import models import importlib logger = logging.getLogger(__name__) from RestrictedPython import compile_restricted from RestrictedPython.Guards import safe_builtins class CustomPrint(object):
58
64
124
5
52
steedos/redash
redash/query_runner/python.py
Python
CustomPrint
CustomPrint
16
35
16
16
b50493f14e42805f012fd375ac4cf3d71a40f831
bigcode/the-stack
train
6a72e8208666ead7f287d2eb
train
function
def cf_plans(cli_ctx, *_): return web_client_factory(cli_ctx).app_service_plans
def cf_plans(cli_ctx, *_):
return web_client_factory(cli_ctx).app_service_plans
_): from azure.cli.core.profiles import ResourceType return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES) def cf_kube_environments(cli_ctx, *_): return web_client_factory(cli_ctx).kube_environments def cf_plans(cli_ctx, *_):
64
64
22
9
54
sanchitmehta/azure-cli-extensions
src/appservice-kube/azext_appservice_kube/_client_factory.py
Python
cf_plans
cf_plans
50
51
50
50
39c066e39783a01a94d2036e0499615238efc0d5
bigcode/the-stack
train
011a9be0309a10bf4f4d983c
train
function
def ex_handler_factory(creating_plan=False, no_throw=False): def _polish_bad_errors(ex): import json from knack.util import CLIError try: detail = json.loads(ex.response.text)['Message'] if creating_plan: if 'Requested features are not supported in reg...
def ex_handler_factory(creating_plan=False, no_throw=False):
def _polish_bad_errors(ex): import json from knack.util import CLIError try: detail = json.loads(ex.response.text)['Message'] if creating_plan: if 'Requested features are not supported in region' in detail: detail = ("Plan with linu...
import ResourceType, CustomResourceType CUSTOM_MGMT_APPSERVICE = CustomResourceType('azext_appservice_kube.vendored_sdks.azure_mgmt_web', 'WebSiteManagementClient') # pylint: disable=inconsistent-return-statements def ex_handler_factory(creating_plan=False, no_throw=False...
65
65
219
13
51
sanchitmehta/azure-cli-extensions
src/appservice-kube/azext_appservice_kube/_client_factory.py
Python
ex_handler_factory
ex_handler_factory
14
35
14
14
bc3e84a687fcb5cd181b08cb8d7ab357d54b396e
bigcode/the-stack
train
dab9333df7c2c8fff5785a2a
train
function
def resource_client_factory(cli_ctx, **_): from azure.cli.core.profiles import ResourceType return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES)
def resource_client_factory(cli_ctx, **_):
from azure.cli.core.profiles import ResourceType return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES)
-except pass if no_throw: return ex raise ex return _polish_bad_errors def web_client_factory(cli_ctx, **_): return get_mgmt_service_client(cli_ctx, CUSTOM_MGMT_APPSERVICE) def resource_client_factory(cli_ctx, **_):
64
64
39
10
54
sanchitmehta/azure-cli-extensions
src/appservice-kube/azext_appservice_kube/_client_factory.py
Python
resource_client_factory
resource_client_factory
41
43
41
41
72e213c8e98035f9c4d6ef86aa67b9f266424c7d
bigcode/the-stack
train
b6bacec0ba8f6f527987a3f3
train
function
def web_client_factory(cli_ctx, **_): return get_mgmt_service_client(cli_ctx, CUSTOM_MGMT_APPSERVICE)
def web_client_factory(cli_ctx, **_):
return get_mgmt_service_client(cli_ctx, CUSTOM_MGMT_APPSERVICE)
resource group. Original error:" + detail) ex = CLIError(detail) except Exception: # pylint: disable=broad-except pass if no_throw: return ex raise ex return _polish_bad_errors def web_client_factory(cli_ctx, **_):
64
64
27
10
53
sanchitmehta/azure-cli-extensions
src/appservice-kube/azext_appservice_kube/_client_factory.py
Python
web_client_factory
web_client_factory
38
39
38
38
06ae898508ee124ca48f24f5beea809b6c15073f
bigcode/the-stack
train
de5a7feec944df4f5f2213d1
train
function
def cf_kube_environments(cli_ctx, *_): return web_client_factory(cli_ctx).kube_environments
def cf_kube_environments(cli_ctx, *_):
return web_client_factory(cli_ctx).kube_environments
_mgmt_service_client(cli_ctx, CUSTOM_MGMT_APPSERVICE) def resource_client_factory(cli_ctx, **_): from azure.cli.core.profiles import ResourceType return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES) def cf_kube_environments(cli_ctx, *_):
64
64
24
11
53
sanchitmehta/azure-cli-extensions
src/appservice-kube/azext_appservice_kube/_client_factory.py
Python
cf_kube_environments
cf_kube_environments
46
47
46
46
516c17a156bc85e4bf5276b54766edc86877b84b
bigcode/the-stack
train
3aebd1571629002dab7ee7e9
train
function
def cf_compute_service(cli_ctx, *_): return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_COMPUTE)
def cf_compute_service(cli_ctx, *_):
return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_COMPUTE)
, ResourceType.MGMT_RESOURCE_RESOURCES) def cf_kube_environments(cli_ctx, *_): return web_client_factory(cli_ctx).kube_environments def cf_plans(cli_ctx, *_): return web_client_factory(cli_ctx).app_service_plans def cf_compute_service(cli_ctx, *_):
64
64
27
9
54
sanchitmehta/azure-cli-extensions
src/appservice-kube/azext_appservice_kube/_client_factory.py
Python
cf_compute_service
cf_compute_service
54
55
54
54
59814f548ca2ed30d0ea6cdfb98bde15b79cc433
bigcode/the-stack
train
3fc78cee47c3a390a17d09ca
train
function
def cf_resource_groups(cli_ctx, subscription_id=None): return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, subscription_id=subscription_id).resource_groups
def cf_resource_groups(cli_ctx, subscription_id=None):
return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, subscription_id=subscription_id).resource_groups
ube_environments def cf_plans(cli_ctx, *_): return web_client_factory(cli_ctx).app_service_plans def cf_compute_service(cli_ctx, *_): return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_COMPUTE) def cf_resource_groups(cli_ctx, subscription_id=None):
64
64
39
11
53
sanchitmehta/azure-cli-extensions
src/appservice-kube/azext_appservice_kube/_client_factory.py
Python
cf_resource_groups
cf_resource_groups
58
60
58
58
cff4b979f4e335761b599553d083f4dbcf400a82
bigcode/the-stack
train
b158624ad5927867d9b8e00c
train
function
def test_invalid_command_line_options(worker_cmd): with pytest.raises(Exception) as exc: w = worker_cmd("--pepe") with w: pass assert "unrecognized arguments: --pepe" in str(exc.value)
def test_invalid_command_line_options(worker_cmd):
with pytest.raises(Exception) as exc: w = worker_cmd("--pepe") with w: pass assert "unrecognized arguments: --pepe" in str(exc.value)
() assert res["config"]["num_processes"] == 1 with worker_cmd("--worker-num-processes=2") as w: res = w.http_get("/stats").json() assert res["config"]["num_processes"] == 2 def test_invalid_command_line_options(worker_cmd):
64
64
50
9
54
ecmwf/servicelib
tests/test_cmd_worker.py
Python
test_invalid_command_line_options
test_invalid_command_line_options
28
33
28
28
80100fbacaa3d0b861508f9d45a3e286054fd9b0
bigcode/the-stack
train
4b6da3ed3cc6857504423e2a
train
function
@pytest.mark.skipif(sys.platform == "darwin", reason="No process stats on macOS") def test_command_line_options(worker_cmd): with worker_cmd("--worker-num-processes=1") as w: res = w.http_get("/stats").json() assert res["config"]["num_processes"] == 1 with worker_cmd("--worker-num-processes=2")...
@pytest.mark.skipif(sys.platform == "darwin", reason="No process stats on macOS") def test_command_line_options(worker_cmd):
with worker_cmd("--worker-num-processes=1") as w: res = w.http_get("/stats").json() assert res["config"]["num_processes"] == 1 with worker_cmd("--worker-num-processes=2") as w: res = w.http_get("/stats").json() assert res["config"]["num_processes"] == 2
of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. from __future__ import absolute_import, unicode_literals import sys import pytest @pytest.mark.skipif(sys.platform == "darwin", reason="No process stats on macOS") def test_command_line_options(worker_cmd):
64
64
108
28
35
ecmwf/servicelib
tests/test_cmd_worker.py
Python
test_command_line_options
test_command_line_options
17
25
17
18
586706b265bcd5ef9821bdd90bc4f2100711b9a2
bigcode/the-stack
train
4638beafcd6f8e1495312fa0
train
function
def plot_cm(cm, labels): ax= plt.subplot() sns.heatmap(cm, annot=True, ax = ax) #annot=True to annotate cells # labels, title and ticks ax.set_xlabel('RL Attention') ax.set_ylabel('Human Attention') # ax.set_title('Confusion Matrix') ax.xaxis.set_ticklabels(labels, fontsize=8, ha='center') ...
def plot_cm(cm, labels):
ax= plt.subplot() sns.heatmap(cm, annot=True, ax = ax) #annot=True to annotate cells # labels, title and ticks ax.set_xlabel('RL Attention') ax.set_ylabel('Human Attention') # ax.set_title('Confusion Matrix') ax.xaxis.set_ticklabels(labels, fontsize=8, ha='center') #['business', 'health'] ...
import seaborn as sns import matplotlib.pyplot as plt def plot_cm(cm, labels):
19
64
118
7
11
sahiljain11/ICML2019-TREX
audio_atari/gaze/plot_attn_comparison.py
Python
plot_cm
plot_cm
4
16
4
4
36b7589150c5a2f9908d08e22f22b4008b2c5bf1
bigcode/the-stack
train
9c0ae1a7fb59e71990889314
train
function
def test_dump_general_info_use_db(tconf, node): node._info_tool.dump_general_info() file_name = node._info_tool.GENERAL_FILE_NAME_TEMPLATE.format(node_name=node.name.lower()) file_path = os.path.join(node.node_info_dir, file_name) db_name = node._info_tool.GENERAL_DB_NAME_TEMPLATE.format(node_name=node....
def test_dump_general_info_use_db(tconf, node):
node._info_tool.dump_general_info() file_name = node._info_tool.GENERAL_FILE_NAME_TEMPLATE.format(node_name=node.name.lower()) file_path = os.path.join(node.node_info_dir, file_name) db_name = node._info_tool.GENERAL_DB_NAME_TEMPLATE.format(node_name=node.name.lower()) db_path = os.path.join(node.no...
def tconf(tconf): old_val = tconf.VALIDATOR_INFO_USE_DB tconf.VALIDATOR_INFO_USE_DB = True yield tconf tconf.VALIDATOR_INFO_USE_DB = old_val def test_dump_general_info_use_db(tconf, node):
64
64
109
12
51
andkononykhin/plenum
plenum/test/validator_info/test_validator_info_dump.py
Python
test_dump_general_info_use_db
test_dump_general_info_use_db
15
22
15
15
3b940b628579e634cb1fe200232827f83d46ce56
bigcode/the-stack
train
0d572ef3347c9f929bbe711a
train
function
@pytest.fixture(scope="module") def tconf(tconf): old_val = tconf.VALIDATOR_INFO_USE_DB tconf.VALIDATOR_INFO_USE_DB = True yield tconf tconf.VALIDATOR_INFO_USE_DB = old_val
@pytest.fixture(scope="module") def tconf(tconf):
old_val = tconf.VALIDATOR_INFO_USE_DB tconf.VALIDATOR_INFO_USE_DB = True yield tconf tconf.VALIDATOR_INFO_USE_DB = old_val
import os import pytest from plenum.server.node import Node @pytest.fixture(scope="module") def tconf(tconf):
26
64
58
12
13
andkononykhin/plenum
plenum/test/validator_info/test_validator_info_dump.py
Python
tconf
tconf
7
12
7
8
e04793ad3b87ce1cfaa93d2d3d2d11361f60a816
bigcode/the-stack
train
dc7802565a1b142439356fc3
train
function
def test_dump_additional_info(node): Node.dump_additional_info(node) file_name = node._info_tool.ADDITIONAL_FILE_NAME_TEMPLATE.format(node_name=node.name.lower()) file_path = os.path.join(node.node_info_dir, file_name) assert os.path.exists(file_path)
def test_dump_additional_info(node):
Node.dump_additional_info(node) file_name = node._info_tool.ADDITIONAL_FILE_NAME_TEMPLATE.format(node_name=node.name.lower()) file_path = os.path.join(node.node_info_dir, file_name) assert os.path.exists(file_path)
, file_name) db_name = node._info_tool.GENERAL_DB_NAME_TEMPLATE.format(node_name=node.name.lower()) db_path = os.path.join(node.node_info_dir, db_name) assert os.path.exists(file_path) assert os.path.exists(db_path) def test_dump_additional_info(node):
64
64
60
8
56
andkononykhin/plenum
plenum/test/validator_info/test_validator_info_dump.py
Python
test_dump_additional_info
test_dump_additional_info
25
29
25
25
1cca5a9730a61e9d19890a81638a464fa9dad91e
bigcode/the-stack
train
b59f8ba4187789c4cead46cc
train
function
def test_file_version_info(node): file_name = node._info_tool.VERSION_FILE_NAME_TEMPLATE.format(node_name=node.name.lower()) file_path = os.path.join(node.node_info_dir, file_name) assert os.path.exists(file_path) assert os.path.getsize(file_path) > 0
def test_file_version_info(node):
file_name = node._info_tool.VERSION_FILE_NAME_TEMPLATE.format(node_name=node.name.lower()) file_path = os.path.join(node.node_info_dir, file_name) assert os.path.exists(file_path) assert os.path.getsize(file_path) > 0
_additional_info(node): Node.dump_additional_info(node) file_name = node._info_tool.ADDITIONAL_FILE_NAME_TEMPLATE.format(node_name=node.name.lower()) file_path = os.path.join(node.node_info_dir, file_name) assert os.path.exists(file_path) def test_file_version_info(node):
64
64
62
7
57
andkononykhin/plenum
plenum/test/validator_info/test_validator_info_dump.py
Python
test_file_version_info
test_file_version_info
32
36
32
32
bea0b8ef8cc90b54904b1082dfb5dc8247cc9393
bigcode/the-stack
train
9356df179b2fd77ddd39cea8
train
function
def train_profile(profile_dir: Path, profile: Profile) -> Tuple[int, List[str]]: # Compact def ppath(query, default=None, write=False): return utils_ppath(profile, profile_dir, query, default, write=write) language = profile.get("language", "") # Inputs stt_system = profile.get("speech_to...
def train_profile(profile_dir: Path, profile: Profile) -> Tuple[int, List[str]]: # Compact
def ppath(query, default=None, write=False): return utils_ppath(profile, profile_dir, query, default, write=write) language = profile.get("language", "") # Inputs stt_system = profile.get("speech_to_text.system") stt_prefix = f"speech_to_text.{stt_system}" # intent_whitelist = ppath("...
#!/usr/bin/env python3 import io import os import re import sys import json import logging import subprocess from pathlib import Path from typing import Iterable, List, Tuple from num2words import num2words import pywrapfst as fst from doit import create_after from doit.cmd_base import ModuleTaskLoader from doit.doit...
234
256
3,385
24
210
kroka/rhasspy
rhasspy/train/__init__.py
Python
train_profile
train_profile
44
466
44
46
0a1decc44db29e3920a0527bebf1349af7b24ea0
bigcode/the-stack
train
99d950501247702c5a15d0e4
train
function
def download_files(file_urls, chrome_instance): pass
def download_files(file_urls, chrome_instance):
pass
course_files = chrome_instance.find_elements_by_class_name("ef-name-col__link") for course_file in course_files: file_download_link = course_file.get_attribute("href") file_download_links.append(file_download_link) return file_download_links #TODO def download_files(file_urls, chrome_instanc...
64
64
12
9
54
Caleb-Shepard/Canvas-File-Control
file_downloader.py
Python
download_files
download_files
67
68
67
67
d281bf1adaa19b1d7321f947a7d59c3cf3b24664
bigcode/the-stack
train
1965af97020df26c605ee376
train
function
def get_file_download_urls(course_url, chrome_instance): print_debug_messages("exec get_file_download_urls()") files_url_suffix = r"/files" course_files_url = course_url + files_url_suffix file_download_links = [] chromedriver_get(course_files_url, chrome_instance) # scan for hyperlinks conta...
def get_file_download_urls(course_url, chrome_instance):
print_debug_messages("exec get_file_download_urls()") files_url_suffix = r"/files" course_files_url = course_url + files_url_suffix file_download_links = [] chromedriver_get(course_files_url, chrome_instance) # scan for hyperlinks containing files course_files = chrome_instance.find_eleme...
NameInput") username_box.send_keys(input("username: ")) password_box = chrome_instance.find_element_by_id ("passwordInput") password_box.send_keys(getpass.getpass("Password: ")) chrome_instance.find_element_by_id("submitButton").click() def get_file_download_urls(course_url, chrome_instance):
64
64
122
11
53
Caleb-Shepard/Canvas-File-Control
file_downloader.py
Python
get_file_download_urls
get_file_download_urls
48
63
48
48
f7c817ae8d06470c1a60e90f785cd1c9b935309c
bigcode/the-stack
train
61dd6a2147c73726a8d67313
train
function
def print_debug_messages(debug_message): if DEBUG_MODE is True: print(debug_message)
def print_debug_messages(debug_message):
if DEBUG_MODE is True: print(debug_message)
CANVAS_URL = "https://floridapolytechnic.instructure.com/" def chromedriver_get(url, chrome_instance): chrome_instance.get(url) sleep(WEBDRIVER_SLEEP) # print debug messages when debug mode is active; otherwise just ignore def print_debug_messages(debug_message):
64
64
19
7
56
Caleb-Shepard/Canvas-File-Control
file_downloader.py
Python
print_debug_messages
print_debug_messages
30
32
30
30
a2a7436b23bd711b2c215d510e388c71c51f0f3a
bigcode/the-stack
train
9e96c337572e89a4e15ba97f
train
function
def main(): print_debug_messages("exec main()") print_debug_messages("Dirty hack that accesses course files for comp arch") course_url = "https://floridapolytechnic.instructure.com/courses/2556" chrome_instance = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH) canvas_login(chrome_instance) ...
def main():
print_debug_messages("exec main()") print_debug_messages("Dirty hack that accesses course files for comp arch") course_url = "https://floridapolytechnic.instructure.com/courses/2556" chrome_instance = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH) canvas_login(chrome_instance) file_urls = ...
_elements_by_class_name("ef-name-col__link") for course_file in course_files: file_download_link = course_file.get_attribute("href") file_download_links.append(file_download_link) return file_download_links #TODO def download_files(file_urls, chrome_instance): pass def main():
64
64
125
3
60
Caleb-Shepard/Canvas-File-Control
file_downloader.py
Python
main
main
71
85
71
71
740e00d07040a7b2be372b813777df506cc03570
bigcode/the-stack
train
4969b323930920b990918ec6
train
function
def chromedriver_get(url, chrome_instance): chrome_instance.get(url) sleep(WEBDRIVER_SLEEP)
def chromedriver_get(url, chrome_instance):
chrome_instance.get(url) sleep(WEBDRIVER_SLEEP)
DEFINE GLOBALS CHROMEDRIVER_PATH = "/usr/local/bin/chromedriver" WEBDRIVER_SLEEP = 5 DEBUG_MODE = True CANVAS_URL = "https://floridapolytechnic.instructure.com/" def chromedriver_get(url, chrome_instance):
63
64
24
9
54
Caleb-Shepard/Canvas-File-Control
file_downloader.py
Python
chromedriver_get
chromedriver_get
24
26
24
24
e7fb089c807799d5a4e460be2d7681a18abff4df
bigcode/the-stack
train
894bca5aeca9e6cdb5030bb0
train
function
def canvas_login(chrome_instance): print_debug_messages("exec canvas_login()") chromedriver_get(CANVAS_URL, chrome_instance) # Enter username, password, and submit username_box = chrome_instance.find_element_by_id("userNameInput") username_box.send_keys(input("username: ")) password_box = chro...
def canvas_login(chrome_instance):
print_debug_messages("exec canvas_login()") chromedriver_get(CANVAS_URL, chrome_instance) # Enter username, password, and submit username_box = chrome_instance.find_element_by_id("userNameInput") username_box.send_keys(input("username: ")) password_box = chrome_instance.find_element_by_id ("pa...
def chromedriver_get(url, chrome_instance): chrome_instance.get(url) sleep(WEBDRIVER_SLEEP) # print debug messages when debug mode is active; otherwise just ignore def print_debug_messages(debug_message): if DEBUG_MODE is True: print(debug_message) def canvas_login(chrome_instance):
64
64
104
7
57
Caleb-Shepard/Canvas-File-Control
file_downloader.py
Python
canvas_login
canvas_login
35
45
35
35
fc852bc0097ac31fd843fa8f52ab0efcb6d91a81
bigcode/the-stack
train
ba549d9c55d6ff10a418f6ee
train
function
def pick_single_fn(heads, fn_name): """ Iterates over heads and returns a static method called fn_name if and only if one head has a method of that name. If no heads have such a method, None is returned. If more than one head has such a method, an Exception is thrown""" merge_fns = [] for h in heads...
def pick_single_fn(heads, fn_name):
""" Iterates over heads and returns a static method called fn_name if and only if one head has a method of that name. If no heads have such a method, None is returned. If more than one head has such a method, an Exception is thrown""" merge_fns = [] for h in heads: merge_fns.append(getattr(h...
_impossible else: cls_pred = None pred_span.classification = cls_pred pred_spans_new.append(pred_span) qa_doc_pred.preds = pred_spans_new ret.append(qa_doc_pred) return ret def pick_single_fn(heads, fn_name):
64
64
172
10
53
dertilo/FARM
farm/modeling/prediction_head.py
Python
pick_single_fn
pick_single_fn
1,522
1,536
1,522
1,522
542a6947de77dead34a0788d00537baee1a3f844
bigcode/the-stack
train
de1e7643c1d4d0d9c99a0d3d
train
class
class TextClassificationHead(PredictionHead): def __init__( self, layer_dims=None, num_labels=None, class_weights=None, loss_ignore_index=-100, loss_reduction="none", task_name="text_classification", **kwargs, ): """ :param layer_di...
class TextClassificationHead(PredictionHead):
def __init__( self, layer_dims=None, num_labels=None, class_weights=None, loss_ignore_index=-100, loss_reduction="none", task_name="text_classification", **kwargs, ): """ :param layer_dims: The size of the layers in the feed forward...
_tensor_name) return self.loss_fct(logits, label_ids.float()) def logits_to_preds(self, logits, **kwargs): preds = logits.cpu().numpy() #rescale predictions to actual label distribution preds = [x * self.label_list[1] + self.label_list[0] for x in preds] return preds de...
256
256
1,677
9
246
dertilo/FARM
farm/modeling/prediction_head.py
Python
TextClassificationHead
TextClassificationHead
243
420
243
243
4d13f7664b51e484949b909505a59cc1147553e6
bigcode/the-stack
train
4a07678ce98037ae2bb5fbcd
train
class
class TokenClassificationHead(PredictionHead): def __init__(self, layer_dims=None, num_labels=None, task_name="ner", **kwargs): """ :param layer_dims: The size of the layers in the feed forward component. The feed forward will have ...
class TokenClassificationHead(PredictionHead):
def __init__(self, layer_dims=None, num_labels=None, task_name="ner", **kwargs): """ :param layer_dims: The size of the layers in the feed forward component. The feed forward will have as many layers as there are ints in this list. ...
self.label_list[int(x)] for x in row]) return preds def prepare_labels(self, **kwargs): label_ids = kwargs.get(self.label_tensor_name) label_ids = label_ids.cpu().numpy() label_ids = [np.where(row == 1)[0] for row in label_ids] labels = [] for row in label_ids: ...
256
256
1,704
9
246
dertilo/FARM
farm/modeling/prediction_head.py
Python
TokenClassificationHead
TokenClassificationHead
532
719
532
532
e478d77d4ee5ddad5e7840843680021cc7cbbc5e
bigcode/the-stack
train
450c44c1e9ebecf8f4b8ed0d
train
class
class MultiLabelTextClassificationHead(PredictionHead): def __init__( self, layer_dims=None, num_labels=None, class_weights=None, loss_reduction="none", task_name="text_classification", pred_threshold=0.5, **kwargs, ): """ :param la...
class MultiLabelTextClassificationHead(PredictionHead):
def __init__( self, layer_dims=None, num_labels=None, class_weights=None, loss_reduction="none", task_name="text_classification", pred_threshold=0.5, **kwargs, ): """ :param layer_dims: The size of the layers in the feed forward com...
.clear_text["question_text"] + " | " + sample.clear_text["passage_text"] for sample in samples] contexts_b = [sample.clear_text["text_b"] for sample in samples if "text_b" in sample.clear_text] if len(contexts_b) != 0: contexts = ["|".join([a, b]) for a,b in zip(contexts, contexts_b)] ...
256
256
943
11
244
dertilo/FARM
farm/modeling/prediction_head.py
Python
MultiLabelTextClassificationHead
MultiLabelTextClassificationHead
423
529
423
423
3847b21773cb4237d64440136493f8033926f6c1
bigcode/the-stack
train
b3215f960f33bdf23a62f4fa
train
class
class BertLMHead(PredictionHead): def __init__(self, hidden_size, vocab_size, hidden_act="gelu", task_name="lm", **kwargs): super(BertLMHead, self).__init__() self.hidden_size = hidden_size self.hidden_act = hidden_act self.vocab_size = vocab_size self.loss_fct = CrossEntrop...
class BertLMHead(PredictionHead):
def __init__(self, hidden_size, vocab_size, hidden_act="gelu", task_name="lm", **kwargs): super(BertLMHead, self).__init__() self.hidden_size = hidden_size self.hidden_act = hidden_act self.vocab_size = vocab_size self.loss_fct = CrossEntropyLoss(reduction="none", ignore_ind...
_spans.append(span) span = {"start": offset, "end": offset + len(token)} else: # expand the span to include the subword-token span["end"] = offset + len(token.replace("##", "")) word_spans.append(span) spans.append(word_...
256
256
1,301
9
246
dertilo/FARM
farm/modeling/prediction_head.py
Python
BertLMHead
BertLMHead
722
853
722
722
dc7a64462daa27f13d29ee7eb966df4458733ef6
bigcode/the-stack
train
374133ff335e2b45208ab01a
train
class
class PredictionHead(nn.Module): """ Takes word embeddings from a language model and generates logits for a given task. Can also convert logits to loss and and logits to predictions. """ subclasses = {} def __init_subclass__(cls, **kwargs): """ This automatically keeps track of all available s...
class PredictionHead(nn.Module):
""" Takes word embeddings from a language model and generates logits for a given task. Can also convert logits to loss and and logits to predictions. """ subclasses = {} def __init_subclass__(cls, **kwargs): """ This automatically keeps track of all available subclasses. Enables generi...
import itertools import json import logging import os import numpy as np import pandas as pd from scipy.special import expit, softmax import tqdm from pathlib import Path import torch from transformers.modeling_bert import BertForPreTraining, BertLayerNorm, ACT2FN from transformers.modeling_auto import AutoModelForQues...
169
256
1,462
6
163
dertilo/FARM
farm/modeling/prediction_head.py
Python
PredictionHead
PredictionHead
25
184
25
25
cf105f49c32bd236b5f08422d856dcea0d2fb31d
bigcode/the-stack
train
a9e314282c0834728a397033
train
class
class NextSentenceHead(TextClassificationHead): """ Almost identical to a TextClassificationHead. Only difference: we can load the weights from a pretrained language model that was saved in the Transformers style (all in one model). """ @classmethod def load(cls, pretrained_model_name_or_path):...
class NextSentenceHead(TextClassificationHead):
""" Almost identical to a TextClassificationHead. Only difference: we can load the weights from a pretrained language model that was saved in the Transformers style (all in one model). """ @classmethod def load(cls, pretrained_model_name_or_path): """ Load a prediction head from...
(x)] for x in pred_ids_for_sequence if int(x) != -1] ) return preds def prepare_labels(self, **kwargs): label_ids = kwargs.get(self.label_tensor_name) label_ids = label_ids.cpu().numpy().tolist() labels = [] # we have a batch of sequences here. we need to convert...
125
125
419
8
116
dertilo/FARM
farm/modeling/prediction_head.py
Python
NextSentenceHead
NextSentenceHead
856
896
856
856
f2d03ff2f5d06bbc6ec47e8127bcd028a3d1be2b
bigcode/the-stack
train
ae414df9fadbf0c46f638abc
train
class
class RegressionHead(PredictionHead): def __init__( self, layer_dims=[768,1], task_name="regression", **kwargs, ): super(RegressionHead, self).__init__() # num_labels could in most cases also be automatically retrieved from the data processor self.layer_di...
class RegressionHead(PredictionHead):
def __init__( self, layer_dims=[768,1], task_name="regression", **kwargs, ): super(RegressionHead, self).__init__() # num_labels could in most cases also be automatically retrieved from the data processor self.layer_dims = layer_dims self.feed_forw...
classmethod def _get_model_file(cls, config_file): if "config.json" in str(config_file) and "prediction_head" in str(config_file): head_num = int("".join([char for char in os.path.basename(config_file) if char.isdigit()])) model_file = Path(os.path.dirname(config_file)) / f"predictio...
135
135
452
8
126
dertilo/FARM
farm/modeling/prediction_head.py
Python
RegressionHead
RegressionHead
187
240
187
187
a5f7863bf19b947ba9b913001c97401660685058
bigcode/the-stack
train
e8bbebf36fba1f20cc45485a
train
class
class QuestionAnsweringHead(PredictionHead): """ A question answering head predicts the start and end of the answer on token level. """ def __init__(self, layer_dims=[768,2], task_name="question_answering", no_ans_boost=0.0, context_window_size=100, ...
class QuestionAnsweringHead(PredictionHead):
""" A question answering head predicts the start and end of the answer on token level. """ def __init__(self, layer_dims=[768,2], task_name="question_answering", no_ans_boost=0.0, context_window_size=100, n_best=5, n_b...
_with_lm.config.hidden_size, 2], loss_ignore_index=-1, task_name="nextsentence") # load weights head.feed_forward.feed_forward[0].load_state_dict(bert_with_lm.cls.seq_relationship.state_dict()) del bert_with_lm return head class FeedForwardBlock(nn.Module): """ A feed ...
256
256
6,460
10
245
dertilo/FARM
farm/modeling/prediction_head.py
Python
QuestionAnsweringHead
QuestionAnsweringHead
923
1,519
923
923
99dc961956fefb011af9e6a4125a0846b6bcabab
bigcode/the-stack
train
40154d0b39369a862d114882
train
class
class FeedForwardBlock(nn.Module): """ A feed forward neural network of variable depth and width. """ def __init__(self, layer_dims, **kwargs): # Todo: Consider having just one input argument super(FeedForwardBlock, self).__init__() self.layer_dims = layer_dims # If read from co...
class FeedForwardBlock(nn.Module):
""" A feed forward neural network of variable depth and width. """ def __init__(self, layer_dims, **kwargs): # Todo: Consider having just one input argument super(FeedForwardBlock, self).__init__() self.layer_dims = layer_dims # If read from config the input will be string ...
.hidden_size, 2], loss_ignore_index=-1, task_name="nextsentence") # load weights head.feed_forward.feed_forward[0].load_state_dict(bert_with_lm.cls.seq_relationship.state_dict()) del bert_with_lm return head class FeedForwardBlock(nn.Module):
64
64
185
7
56
dertilo/FARM
farm/modeling/prediction_head.py
Python
FeedForwardBlock
FeedForwardBlock
898
920
898
898
7ed6a82f22b822ef7de2b6e290e6531d018ba04f
bigcode/the-stack
train