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
3f1b0da06bec1adacc9f957d
train
function
def overlap_of_ranges(a1_b1, a2_b2): a1, b1 = a1_b1 a2, b2 = a2_b2 s = max(a1, a2) e = min(b1, b2) o = e - s if o < 0: o = 0 return o
def overlap_of_ranges(a1_b1, a2_b2):
a1, b1 = a1_b1 a2, b2 = a2_b2 s = max(a1, a2) e = min(b1, b2) o = e - s if o < 0: o = 0 return o
tag, i1, i2, j1, j2) in m.get_opcodes(): if tag != 'equal': d[tag].append(((i1, i2), (j1, j2))) return d def overlap_of_ranges(a1_b1, a2_b2):
64
64
82
14
49
mstmhsmt/cca
cca/esecfse2018/overlap.py
Python
overlap_of_ranges
overlap_of_ranges
103
111
103
103
f0d57cf4a3aa4579db7e00667870d7e7a896f8c6
bigcode/the-stack
train
2e3694d8c725fe89c9aa33d7
train
function
def diff_to_str(d, toks1, toks2): dels = d['delete'] repls = d['replace'] inss = d['insert'] lines = [] if dels: for ((a, b), _) in dels: lines.append('[DELETE] %d-%d (%d):\n' % (a, b-1, b-a)) lines.append(' '.join(toks1[a:b])) lines.append('\n') if ...
def diff_to_str(d, toks1, toks2):
dels = d['delete'] repls = d['replace'] inss = d['insert'] lines = [] if dels: for ((a, b), _) in dels: lines.append('[DELETE] %d-%d (%d):\n' % (a, b-1, b-a)) lines.append(' '.join(toks1[a:b])) lines.append('\n') if repls: for ((a, b), (a2, b...
['delete']: sz += i2 - i1 for ((i1, i2), (j1, j2)) in d['replace']: sz += i2 - i1 + j2 - j1 for (_, (j1, j2)) in d['insert']: sz += j2 - j1 return sz def diff_to_str(d, toks1, toks2):
88
88
294
12
75
mstmhsmt/cca
cca/esecfse2018/overlap.py
Python
diff_to_str
diff_to_str
145
172
145
145
8383b64eb209b962c73148ac65c2124ad7a40892
bigcode/the-stack
train
95bf8e0ff192741d5836e7dc
train
function
def overlap_of_delete(dels1, dels2): o = 0 for (r1, r2) in dels1: for (r3, r4) in dels2: o += overlap_of_ranges(r1, r3) return o
def overlap_of_delete(dels1, dels2):
o = 0 for (r1, r2) in dels1: for (r3, r4) in dels2: o += overlap_of_ranges(r1, r3) return o
, b2 = a2_b2 s = max(a1, a2) e = min(b1, b2) o = e - s if o < 0: o = 0 return o def overlap_of_delete(dels1, dels2):
64
64
59
11
52
mstmhsmt/cca
cca/esecfse2018/overlap.py
Python
overlap_of_delete
overlap_of_delete
113
118
113
113
e952ba8453623f4e29af041347ee926903c87d5d
bigcode/the-stack
train
da2af41b447801dd854ef174
train
function
def print_diff(d, toks1, toks2): print(diff_to_str(d, toks1, toks2))
def print_diff(d, toks1, toks2):
print(diff_to_str(d, toks1, toks2))
-> %d-%d (%d):\n' % (i, a, b-1, b-a)) lines.append(' '.join(toks2[a:b])) lines.append('\n') s = ''.join(lines) return s def print_diff(d, toks1, toks2):
64
64
24
11
52
mstmhsmt/cca
cca/esecfse2018/overlap.py
Python
print_diff
print_diff
174
175
174
174
074fdf58c7ade0bf6a8c2d7986a5162db79f020c
bigcode/the-stack
train
d33fac3ae644ee885ef3dc64
train
function
def insert_of_tokens(toks1, toks2): # returns index * token list m = SequenceMatcher(isjunk=None, a=toks1, b=toks2, autojunk=False) ins_tbl = {} for (tag, i1, _, j1, j2) in m.get_opcodes(): if tag in ('insert', 'replace'): ins_tbl[i1] = toks2[j1:j2] return ins_tbl
def insert_of_tokens(toks1, toks2): # returns index * token list
m = SequenceMatcher(isjunk=None, a=toks1, b=toks2, autojunk=False) ins_tbl = {} for (tag, i1, _, j1, j2) in m.get_opcodes(): if tag in ('insert', 'replace'): ins_tbl[i1] = toks2[j1:j2] return ins_tbl
b=toks2, autojunk=False) toks = set() for nt in m.get_matching_blocks(): for i in range(nt.a, nt.a+nt.size): toks.add(i) return toks def insert_of_tokens(toks1, toks2): # returns index * token list
64
64
96
18
45
mstmhsmt/cca
cca/esecfse2018/overlap.py
Python
insert_of_tokens
insert_of_tokens
72
78
72
72
9a65950b80699a762d904c11380f27781803aeef
bigcode/the-stack
train
27820747f5cfa743708293ff
train
function
def overlap_of_replace(repls1, repls2, toks1, toks2): o = 0 for (r1, r2) in repls1: (a1, b1) = r2 x = toks1[a1:b1] for (r3, r4) in repls2: (a2, b2) = r4 y = toks2[a2:b2] if x == y: o += overlap_of_ranges(r1, r3) return o
def overlap_of_replace(repls1, repls2, toks1, toks2):
o = 0 for (r1, r2) in repls1: (a1, b1) = r2 x = toks1[a1:b1] for (r3, r4) in repls2: (a2, b2) = r4 y = toks2[a2:b2] if x == y: o += overlap_of_ranges(r1, r3) return o
= 0 for (r1, r2) in dels1: for (r3, r4) in dels2: o += overlap_of_ranges(r1, r3) return o def overlap_of_replace(repls1, repls2, toks1, toks2):
64
64
118
18
45
mstmhsmt/cca
cca/esecfse2018/overlap.py
Python
overlap_of_replace
overlap_of_replace
120
130
120
120
df50b05e60b0aa62d7d721fe7a876bc805bd03d6
bigcode/the-stack
train
0fd0af99e518afec5f34888d
train
function
def rms(x): return(np.sqrt(np.mean(x**2)))
def rms(x):
return(np.sqrt(np.mean(x**2)))
orrelation function ''' def autocorr(x): axis = np.arange(-len(x)+1,len(x)) func = np.correlate(x-x.mean(),x-x.mean(),mode='full')/len(x) return (axis,func) '''Root mean square helper function ''' def rms(x):
64
64
14
4
60
tytong99/Project-Soundfield
Project_Soundfield/AnalysisLib.py
Python
rms
rms
20
21
20
20
b8cc7b7571ef772fd082e1517d49ba657f8ce9d6
bigcode/the-stack
train
4f5cc3bfdbfdc25a004af71f
train
function
def autocorr(x): axis = np.arange(-len(x)+1,len(x)) func = np.correlate(x-x.mean(),x-x.mean(),mode='full')/len(x) return (axis,func)
def autocorr(x):
axis = np.arange(-len(x)+1,len(x)) func = np.correlate(x-x.mean(),x-x.mean(),mode='full')/len(x) return (axis,func)
# import numpy as np '''Normalised auto-correlation Input: x is the time series or 1D process Output: 'axis' is symetrical axis for the auto-correlation function 'func' is the normalised auto-correlation function ''' def autocorr(x):
64
64
48
5
59
tytong99/Project-Soundfield
Project_Soundfield/AnalysisLib.py
Python
autocorr
autocorr
13
16
13
13
5d3aae427f28414f7cfec7353c7a340d85986998
bigcode/the-stack
train
94bc77d1bb1821d922e42cc3
train
class
class IceCreamShops(FixtureTest): def test_amenity_ice_cream(self): # New York, NY (amenity=ice_cream) self.load_fixtures(['https://www.openstreetmap.org/node/2782000317']) self.assert_has_feature( 16, 19299, 24629, 'pois', {'kind': 'ice_cream'}) def test_shop_i...
class IceCreamShops(FixtureTest):
def test_amenity_ice_cream(self): # New York, NY (amenity=ice_cream) self.load_fixtures(['https://www.openstreetmap.org/node/2782000317']) self.assert_has_feature( 16, 19299, 24629, 'pois', {'kind': 'ice_cream'}) def test_shop_ice_cream(self): # Oakland,...
from . import FixtureTest class IceCreamShops(FixtureTest):
15
64
159
9
5
nextzen/vector-datasource
integration-test/447-ice-cream-shops.py
Python
IceCreamShops
IceCreamShops
4
19
4
4
ea133a11352392a68ba78c4ccb663da9b588c9d2
bigcode/the-stack
train
9a99df10ad105a689894029b
train
class
class DataSourceLoaderTestCase(BaseLoaderTestCase): source_file_name = "ds.xml" source_contents = """<?xml version="1.0"?> <tool name="YeastMine" id="yeastmine" tool_type="data_source"> <description>server</description> <command interpreter="python">data_source.py $output $__app__.config.output_size_lim...
class DataSourceLoaderTestCase(BaseLoaderTestCase):
source_file_name = "ds.xml" source_contents = """<?xml version="1.0"?> <tool name="YeastMine" id="yeastmine" tool_type="data_source"> <description>server</description> <command interpreter="python">data_source.py $output $__app__.config.output_size_limit</command> <inputs action="http://yeastmine.ye...
diff" assert attributes1["lines_diff"] == 0 test2 = tests[1] outputs = test2["outputs"] assert len(outputs) == 1 output2 = outputs[0] assert output2[0] == 'out1' assert output2[1] is None attributes1 = output2[2] assert attributes1["compare"] == "...
133
133
446
11
121
igorhollaender/sirv_dashboard
test/unit/tools/test_parsing.py
Python
DataSourceLoaderTestCase
DataSourceLoaderTestCase
376
422
376
376
4f5da4062e4b1c860e881de2a229bd82d4c28eca
bigcode/the-stack
train
f4df5e5c858cff46967b800e
train
class
class YamlLoaderTestCase(BaseLoaderTestCase): source_file_name = "bwa.yml" source_contents = TOOL_YAML_1 def test_version(self): assert self._tool_source.parse_version() == "1.0.2" def test_id(self): assert self._tool_source.parse_id() == "bowtie" def test_module_and_type(self): ...
class YamlLoaderTestCase(BaseLoaderTestCase):
source_file_name = "bwa.yml" source_contents = TOOL_YAML_1 def test_version(self): assert self._tool_source.parse_version() == "1.0.2" def test_id(self): assert self._tool_source.parse_id() == "bowtie" def test_module_and_type(self): # These just rely on defaults a...
attributes1 = output2[2] assert attributes1["compare"] == "sim_size" assert attributes1["lines_diff"] == 4 def test_exit_code(self): tool_source = self._get_tool_source(source_contents="""<tool id="bwa" name="bwa"> <command detect_errors="exit_code"> ls ...
256
256
980
11
244
igorhollaender/sirv_dashboard
test/unit/tools/test_parsing.py
Python
YamlLoaderTestCase
YamlLoaderTestCase
254
373
254
254
0c36461451d834b9d92a9fa5b3b983a614f944e8
bigcode/the-stack
train
653316a4904e70a46524842a
train
class
class XmlLoaderTestCase(BaseLoaderTestCase): source_file_name = "bwa.xml" source_contents = TOOL_XML_1 def test_version(self): assert self._tool_source.parse_version() == "1.0.1" def test_id(self): assert self._tool_source.parse_id() == "bwa" def test_module_and_type(self): ...
class XmlLoaderTestCase(BaseLoaderTestCase):
source_file_name = "bwa.xml" source_contents = TOOL_XML_1 def test_version(self): assert self._tool_source.parse_version() == "1.0.1" def test_id(self): assert self._tool_source.parse_id() == "bwa" def test_module_and_type(self): assert self._tool_source.parse_tool_module(...
- name: nestsample type: text help: | This is HELP TEXT2!!! tests: - inputs: foo: 5 outputs: out1: moo.txt - inputs: foo: value: 5 outputs: out1: lines_diff: 4 compare: sim_size """ class BaseLoaderTestCase(unittest.TestCase): ...
256
256
1,048
10
245
igorhollaender/sirv_dashboard
test/unit/tools/test_parsing.py
Python
XmlLoaderTestCase
XmlLoaderTestCase
124
251
124
124
07b4587d04f1bf4358ffe08911d6a0b33d1c6905
bigcode/the-stack
train
0dc4206399b65fb2c95e88d5
train
class
class SpecialToolLoaderTestCase(BaseLoaderTestCase): source_file_name = os.path.join(os.getcwd(), "lib/galaxy/tools/imp_exp/exp_history_to_archive.xml") source_contents = None def test_tool_type(self): tool_module = self._tool_source.parse_tool_module() # Probably we don't parse_tool_module...
class SpecialToolLoaderTestCase(BaseLoaderTestCase):
source_file_name = os.path.join(os.getcwd(), "lib/galaxy/tools/imp_exp/exp_history_to_archive.xml") source_contents = None def test_tool_type(self): tool_module = self._tool_source.parse_tool_module() # Probably we don't parse_tool_module any more? - # tool_type seems sufficient. ...
_params_elem(self): assert self._tool_source.parse_redirect_url_params_elem() is not None def test_parallelism(self): assert self._tool_source.parse_parallelism() is None def test_hidden(self): assert not self._tool_source.parse_hidden() class SpecialToolLoaderTestCase(BaseLoaderTestCa...
67
67
224
11
56
igorhollaender/sirv_dashboard
test/unit/tools/test_parsing.py
Python
SpecialToolLoaderTestCase
SpecialToolLoaderTestCase
425
447
425
425
d2f366bf883d6301359b5365d107389a28a033e4
bigcode/the-stack
train
24f6d952087a1f02c64ad259
train
class
class BaseLoaderTestCase(unittest.TestCase): def setUp(self): self.temp_directory = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.temp_directory) @property def _tool_source(self): return self._get_tool_source() def _get_tool_source(self, source_file_name=None,...
class BaseLoaderTestCase(unittest.TestCase):
def setUp(self): self.temp_directory = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.temp_directory) @property def _tool_source(self): return self._get_tool_source() def _get_tool_source(self, source_file_name=None, source_contents=None): if source_file...
: - inputs: foo: 5 outputs: out1: moo.txt - inputs: foo: value: 5 outputs: out1: lines_diff: 4 compare: sim_size """ class BaseLoaderTestCase(unittest.TestCase):
64
64
168
9
55
igorhollaender/sirv_dashboard
test/unit/tools/test_parsing.py
Python
BaseLoaderTestCase
BaseLoaderTestCase
98
121
98
99
0a070fb1864dd4574e95591b03fbc4cb3330ef4b
bigcode/the-stack
train
424f7b325e255ea68d759a2c
train
function
def normalize_screen_name(username): if username in TWITTER_SCREEN_NAME_BLACKLIST: return None if username.startswith('@'): username = username[1:] return username.lower()
def normalize_screen_name(username):
if username in TWITTER_SCREEN_NAME_BLACKLIST: return None if username.startswith('@'): username = username[1:] return username.lower()
str): Url to test. Returns: bool: Whether given url is from Youtube. """ if isinstance(url, SplitResult): return bool(re.search(TWITTER_DOMAINS_RE, url.hostname)) return bool(re.match(TWITTER_URL_RE, url)) def normalize_screen_name(username):
64
64
39
6
58
Yomguithereal/ural
ural/twitter.py
Python
normalize_screen_name
normalize_screen_name
48
55
48
48
1569903910c012573155935ddf159de28bff7ce7
bigcode/the-stack
train
9980c4ecaf35cd9b2109f992
train
function
def extract_screen_name_from_twitter_url(url): """ Function returning the screen_name from a given Twitter url. Args: url (str) : Url from which we extract the screen_name if found. Returns: str : screen_name if the url is a valid twitter url, None otherwise. """ parsed_twitt...
def extract_screen_name_from_twitter_url(url):
""" Function returning the screen_name from a given Twitter url. Args: url (str) : Url from which we extract the screen_name if found. Returns: str : screen_name if the url is a valid twitter url, None otherwise. """ parsed_twitter_url = parse_twitter_url(url) if isinsta...
.hostname)) return bool(re.match(TWITTER_URL_RE, url)) def normalize_screen_name(username): if username in TWITTER_SCREEN_NAME_BLACKLIST: return None if username.startswith('@'): username = username[1:] return username.lower() def extract_screen_name_from_twitter_url(url):
64
64
123
10
54
Yomguithereal/ural
ural/twitter.py
Python
extract_screen_name_from_twitter_url
extract_screen_name_from_twitter_url
58
78
58
58
a88a8aa7cf878175b678d6d7d643111c295b7e40
bigcode/the-stack
train
58815cab962c99d1f8e22c94
train
function
def is_twitter_url(url): """ Function returning whether the given url is a valid Twitter url. Args: url (str): Url to test. Returns: bool: Whether given url is from Youtube. """ if isinstance(url, SplitResult): return bool(re.search(TWITTER_DOMAINS_RE, url.hostname)) ...
def is_twitter_url(url):
""" Function returning whether the given url is a valid Twitter url. Args: url (str): Url to test. Returns: bool: Whether given url is from Youtube. """ if isinstance(url, SplitResult): return bool(re.search(TWITTER_DOMAINS_RE, url.hostname)) return bool(re.match(...
'hashtag', 'i', 'messages', 'notifications', 'search', 'settings' } TwitterTweet = namedtuple('TweetInfo', ['user_screen_name', 'id']) TwitterUser = namedtuple('UserInfo', ['screen_name']) def is_twitter_url(url):
63
64
86
7
56
Yomguithereal/ural
ural/twitter.py
Python
is_twitter_url
is_twitter_url
31
45
31
31
b71d75417ae70d5b8c957b1a380f2431852c2893
bigcode/the-stack
train
7d0270ae7c24c55a0e5f8a35
train
function
def parse_twitter_url(url): """ Function returning a parsed result from a given Twitter url. Args: url (str) : Url from which to extract information if found. Returns: TwitterTweet (namedtuple containing a user_screen_name and a tweet id) instance if the url is a link to a tweet ...
def parse_twitter_url(url):
""" Function returning a parsed result from a given Twitter url. Args: url (str) : Url from which to extract information if found. Returns: TwitterTweet (namedtuple containing a user_screen_name and a tweet id) instance if the url is a link to a tweet or TwitterUser (namedtuple...
, None otherwise. """ parsed_twitter_url = parse_twitter_url(url) if isinstance(parsed_twitter_url, TwitterUser): return parsed_twitter_url.screen_name if isinstance(parsed_twitter_url, TwitterTweet): return parsed_twitter_url.user_screen_name return None def parse_twitter_url(u...
70
70
236
7
62
Yomguithereal/ural
ural/twitter.py
Python
parse_twitter_url
parse_twitter_url
81
117
81
81
02689571c64904f492ff3472b45565fb683cc529
bigcode/the-stack
train
5dd2876204e9308094326b7e
train
class
class Parallel: """Distributed launcher context manager to simplify distributed configuration setup for multiple backends: - backends from native torch distributed configuration: "nccl", "gloo", "mpi" (if available) - XLA on TPUs via `pytorch/xla <https://github.com/pytorch/xla>`_ (if installed) - us...
class Parallel:
"""Distributed launcher context manager to simplify distributed configuration setup for multiple backends: - backends from native torch distributed configuration: "nccl", "gloo", "mpi" (if available) - XLA on TPUs via `pytorch/xla <https://github.com/pytorch/xla>`_ (if installed) - using `Horovod dis...
from typing import Any, Callable, Dict, Optional from ignite.distributed import utils as idist from ignite.utils import setup_logger __all__ = [ "Parallel", ] class Parallel:
41
256
2,661
3
38
uribgp/ignite
ignite/distributed/launcher.py
Python
Parallel
Parallel
11
297
11
11
9928a7d5f59fa4446065b2d2403a7315ccd1f65d
bigcode/the-stack
train
1868d4a08cbba9fe7f1f06ee
train
function
@app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close()
@app.teardown_appcontext def close_connection(exception):
db = getattr(g, '_database', None) if db is not None: db.close()
manent = True # expires at midnight of new day app.permanent_session_lifetime = \ (datetime.now() + timedelta(days=1)).replace(hour=0, minute=0, second=0) - \ datetime.now() @app...
64
64
33
11
53
shffrror/isdi
web/__init__.py
Python
close_connection
close_connection
35
39
35
36
3e36d3589853a5af67385a19fa08693cdcd2a8a7
bigcode/the-stack
train
755cde97154d3c89e7a91aab
train
function
@app.after_request def after_request(response): """ Logging after every request. """ # This avoids the duplication of registry in the log, # since that 500 is already logged via @app.errorhandler. if response.status_code != 500: ts = strftime('[%Y-%b-%d %H:%M]') logger.error('%s %s %s %s...
@app.after_request def after_request(response):
""" Logging after every request. """ # This avoids the duplication of registry in the log, # since that 500 is already logged via @app.errorhandler. if response.status_code != 500: ts = strftime('[%Y-%b-%d %H:%M]') logger.error('%s %s %s %s %s %s', ts, ...
1)).replace(hour=0, minute=0, second=0) - \ datetime.now() @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close()...
64
64
115
9
55
shffrror/isdi
web/__init__.py
Python
after_request
after_request
42
56
42
43
d60a13c6db2da7288c67f1decdd9a6ee84c7d745
bigcode/the-stack
train
e97bf9b7140bd9667b62cec2
train
function
@app.before_request def make_session_permanent(): session.permanent = True # expires at midnight of new day app.permanent_session_lifetime = \ (datetime.now() + timedelta(days=1)).replace(hour=0, minute=0, second=0) - \ ...
@app.before_request def make_session_permanent():
session.permanent = True # expires at midnight of new day app.permanent_session_lifetime = \ (datetime.now() + timedelta(days=1)).replace(hour=0, minute=0, second=0) - \ date...
necessary app.config['SECRET_KEY'] = config.FLASK_SECRET # doesn't seem to be necessary app.config['SESSION_TYPE'] = 'filesystem' sa=SQLAlchemy(app) Migrate(app, sa) logger = logging.getLogger(__name__) import web.view @app.before_request def make_session_permanent():
64
64
66
10
53
shffrror/isdi
web/__init__.py
Python
make_session_permanent
make_session_permanent
26
33
26
27
5138371e8684d01b3ee1f6c1f0977c5179fbef6b
bigcode/the-stack
train
86f8289d814a90b84c7edbed
train
class
class DeepHitDataset(tt.data.DatasetTuple): def __getitem__(self, index): input, target = super().__getitem__(index) target = target.to_numpy() rank_mat = pair_rank_mat(*target) target = tt.tuplefy(*target, rank_mat).to_tensor() return tt.tuplefy(input, target)
class DeepHitDataset(tt.data.DatasetTuple):
def __getitem__(self, index): input, target = super().__getitem__(index) target = target.to_numpy() rank_mat = pair_rank_mat(*target) target = tt.tuplefy(*target, rank_mat).to_tensor() return tt.tuplefy(input, target)
.reshape(-1) events = events.reshape(-1) n = len(idx_durations) mat = np.zeros((n, n), dtype=dtype) mat = _pair_rank_mat(mat, idx_durations, events, dtype) return mat class DeepHitDataset(tt.data.DatasetTuple):
64
64
73
9
54
nikolase90/pycox
pycox/models/data.py
Python
DeepHitDataset
DeepHitDataset
132
138
132
132
dcc772adc5a150aa5b8c61028a79cca58a7b6a42
bigcode/the-stack
train
62b6a06af891ab0d1f80d7ed
train
class
class CoxTimeDataset(CoxCCDataset): def __init__(self, input, durations, events, n_control=1): super().__init__(input, durations, events, n_control) self.durations_tensor = tt.tuplefy(self.durations.values.reshape(-1, 1)).to_tensor() def __getitem__(self, index): if not hasattr(index, '...
class CoxTimeDataset(CoxCCDataset):
def __init__(self, input, durations, events, n_control=1): super().__init__(input, durations, events, n_control) self.durations_tensor = tt.tuplefy(self.durations.values.reshape(-1, 1)).to_tensor() def __getitem__(self, index): if not hasattr(index, '__iter__'): index = [ind...
, self.n_control) x_control = tt.TupleTree(self.input.iloc[idx] for idx in control_idx.transpose()) return tt.tuplefy(x_case, x_control).to_tensor(), None def __len__(self): return len(self.durations) class CoxTimeDataset(CoxCCDataset):
64
64
147
9
55
nikolase90/pycox
pycox/models/data.py
Python
CoxTimeDataset
CoxTimeDataset
81
93
81
81
98532aec703df47617ee989a73d4644194ff92c9
bigcode/the-stack
train
6704be842352a182d5c1caf6
train
class
class DurationSortedDataset(tt.data.DatasetTuple): """We assume the dataset contrain `(input, durations, events)`, and sort the batch based on descending `durations`. See `torchtuples.data.DatasetTuple`. """ def __getitem__(self, index): batch = super().__getitem__(index) input, (d...
class DurationSortedDataset(tt.data.DatasetTuple):
"""We assume the dataset contrain `(input, durations, events)`, and sort the batch based on descending `durations`. See `torchtuples.data.DatasetTuple`. """ def __getitem__(self, index): batch = super().__getitem__(index) input, (duration, event) = batch idx_sort = duration...
allidx = durations.index.values keys = durations.drop_duplicates(keep='first') at_risk_dict = dict() for ix, t in keys.iteritems(): at_risk_dict[t] = allidx[ix:] return at_risk_dict class DurationSortedDataset(tt.data.DatasetTuple):
64
64
116
9
54
nikolase90/pycox
pycox/models/data.py
Python
DurationSortedDataset
DurationSortedDataset
43
55
43
43
de7817843ab5dcad385fb8f3827dd776ae869b9d
bigcode/the-stack
train
ce780d1a96ad442e6ba75570
train
function
def make_at_risk_dict(durations): """Create dict(duration: indices) from sorted df. A dict mapping durations to indices. For each time => index of all individual alive. Arguments: durations {np.arrary} -- durations. """ assert type(durations) is np.ndarray, 'Need durations to be a n...
def make_at_risk_dict(durations):
"""Create dict(duration: indices) from sorted df. A dict mapping durations to indices. For each time => index of all individual alive. Arguments: durations {np.arrary} -- durations. """ assert type(durations) is np.ndarray, 'Need durations to be a numpy array' durations = pd.Ser...
('int') samp = np.empty((dates.size, n_control), dtype=int) samp.fill(np.nan) for it, time in enumerate(dates): samp[it, :] = at_risk_dict[time][idx[:, it]] return samp def make_at_risk_dict(durations):
64
64
156
9
54
nikolase90/pycox
pycox/models/data.py
Python
make_at_risk_dict
make_at_risk_dict
24
40
24
24
a16ec6d4b1418bc4eaaf5cefc20a42d80e8ef3a3
bigcode/the-stack
train
669f26fbcd6878408bb244be
train
class
class CoxCCDataset(torch.utils.data.Dataset): def __init__(self, input, durations, events, n_control=1): df_train_target = pd.DataFrame(dict(duration=durations, event=events)) self.durations = df_train_target.loc[lambda x: x['event'] == 1]['duration'] self.at_risk_dict = make_at_risk_dict(du...
class CoxCCDataset(torch.utils.data.Dataset):
def __init__(self, input, durations, events, n_control=1): df_train_target = pd.DataFrame(dict(duration=durations, event=events)) self.durations = df_train_target.loc[lambda x: x['event'] == 1]['duration'] self.at_risk_dict = make_at_risk_dict(durations) self.input = tt.tuplefy(inpu...
__(self, index): batch = super().__getitem__(index) input, (duration, event) = batch idx_sort = duration.sort(descending=True)[1] event = event.float() batch = tt.tuplefy(input, event).iloc[idx_sort] return batch class CoxCCDataset(torch.utils.data.Dataset):
71
71
239
9
61
nikolase90/pycox
pycox/models/data.py
Python
CoxCCDataset
CoxCCDataset
58
78
58
58
0459e80df82a3e5537e1c07a9b3f12e7d9c01e3e
bigcode/the-stack
train
2b101ff459d4372238d116a8
train
function
@numba.njit def _pair_rank_mat(mat, idx_durations, events, dtype='float32'): n = len(idx_durations) for i in range(n): dur_i = idx_durations[i] ev_i = events[i] if ev_i == 0: continue for j in range(n): dur_j = idx_durations[j] ev_j = events[j]...
@numba.njit def _pair_rank_mat(mat, idx_durations, events, dtype='float32'):
n = len(idx_durations) for i in range(n): dur_i = idx_durations[i] ev_i = events[i] if ev_i == 0: continue for j in range(n): dur_j = idx_durations[j] ev_j = events[j] if (dur_i < dur_j) or ((dur_i == dur_j) and (ev_j == 0)): ...
= super().__getitem__(index) case = case + durations control = control.apply_nrec(lambda x: x + durations) return tt.tuplefy(case, control), None @numba.njit def _pair_rank_mat(mat, idx_durations, events, dtype='float32'):
64
64
128
24
39
nikolase90/pycox
pycox/models/data.py
Python
_pair_rank_mat
_pair_rank_mat
95
108
95
96
0b622a036cdd649291d9900e14bb728ea4471fdb
bigcode/the-stack
train
2e76ecc06db5f2f4d1ca0dd9
train
function
def sample_alive_from_dates(dates, at_risk_dict, n_control=1): '''Sample index from living at time given in dates. dates: np.array of times (or pd.Series). at_risk_dict: dict with at_risk_dict[time] = <array with index of alive in X matrix>. n_control: number of samples. ''' lengths = np.array([...
def sample_alive_from_dates(dates, at_risk_dict, n_control=1):
'''Sample index from living at time given in dates. dates: np.array of times (or pd.Series). at_risk_dict: dict with at_risk_dict[time] = <array with index of alive in X matrix>. n_control: number of samples. ''' lengths = np.array([at_risk_dict[x].shape[0] for x in dates]) # Can be moved outsi...
import numpy as np import pandas as pd import numba import torch import torchtuples as tt def sample_alive_from_dates(dates, at_risk_dict, n_control=1):
43
64
180
18
24
nikolase90/pycox
pycox/models/data.py
Python
sample_alive_from_dates
sample_alive_from_dates
9
22
9
9
22878aa2c9f4ecdb19099343a022afbc8a43c76f
bigcode/the-stack
train
dfb454a127d9d0720b5a1ade
train
function
def pair_rank_mat(idx_durations, events, dtype='float32'): """Indicator matrix R with R_ij = 1{T_i < T_j and D_i = 1}. So it takes value 1 if we observe that i has an event before j and zero otherwise. Arguments: idx_durations {np.array} -- Array with durations. events {np.array} -- Arr...
def pair_rank_mat(idx_durations, events, dtype='float32'):
"""Indicator matrix R with R_ij = 1{T_i < T_j and D_i = 1}. So it takes value 1 if we observe that i has an event before j and zero otherwise. Arguments: idx_durations {np.array} -- Array with durations. events {np.array} -- Array with event indicators. Keyword Arguments: ...
urations[j] ev_j = events[j] if (dur_i < dur_j) or ((dur_i == dur_j) and (ev_j == 0)): mat[i, j] = 1 return mat def pair_rank_mat(idx_durations, events, dtype='float32'):
64
64
199
15
48
nikolase90/pycox
pycox/models/data.py
Python
pair_rank_mat
pair_rank_mat
110
129
110
110
60aa236d29b667fe0cde4ee06e61d90eac6bc628
bigcode/the-stack
train
c0e2288514a078381ad42233
train
function
def check_and_fix_directory(dir_name): """This function is using for creating given directpry, if it is not exists.""" if not os.path.exists(dir_name): os.mkdir(dir_name)
def check_and_fix_directory(dir_name):
"""This function is using for creating given directpry, if it is not exists.""" if not os.path.exists(dir_name): os.mkdir(dir_name)
import os def check_and_fix_directory(dir_name):
11
64
42
8
2
salihtuc/storage-library-api
utils.py
Python
check_and_fix_directory
check_and_fix_directory
4
7
4
4
42de8f6dc3f3fe1868d771c0d75436fc77d9940d
bigcode/the-stack
train
1608ccc0c2d6bd7690f5047e
train
function
def main( openwebtext_path: Path = typer.Argument(..., help="Path to a OpenWebText dump."), output_filepath: Path = typer.Argument(..., help="Filepath to save the preprocessed text"), min_length: Optional[int] = typer.Option( None, help="Minimum token length of documents to retain" ), lowerc...
def main( openwebtext_path: Path = typer.Argument(..., help="Path to a OpenWebText dump."), output_filepath: Path = typer.Argument(..., help="Filepath to save the preprocessed text"), min_length: Optional[int] = typer.Option( None, help="Minimum token length of documents to retain" ), lowerc...
"""Lightly preprocesses an OpenWebText dump obtained from https://skylion007.github.io/OpenWebTextCorpus/. If `min-length is not None`, only documents with at least this many tokens are retained. If `pretrained_model_name_or_path` is not None, the tokenizer will be loaded as `AutoTokenizer.from_pretrain...
ertools import chunked # Emoji's used in typer.secho calls # See: https://github.com/carpedm20/emoji/blob/master/emoji/unicode_codes.py" WARNING = "\U000026A0" SAVING = "\U0001F4BE" MINING = "\U000026CF" def main( openwebtext_path: Path = typer.Argument(..., help="Path to a OpenWebText dump."), output_filepath...
256
256
1,065
188
68
Jaswanth-Devarinti/DeCLUTR
scripts/preprocess_openwebtext.py
Python
main
main
18
130
18
36
9a55181f1a7f90be5cc011b0a6d837834afa979f
bigcode/the-stack
train
0c2db7b945d01f83ddd8ce79
train
class
class HardwariotowerPlatform(PlatformBase): def configure_default_packages(self, variables, targets): board = variables.get("board") board_config = self.board_config(board) build_core = variables.get( "board_build.core", board_config.get("build.core", "arduino")) ...
class HardwariotowerPlatform(PlatformBase):
def configure_default_packages(self, variables, targets): board = variables.get("board") board_config = self.board_config(board) build_core = variables.get( "board_build.core", board_config.get("build.core", "arduino")) build_mcu = variables.get("board_build.mcu", bo...
# Copyright 2014-present PlatformIO <contact@platformio.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
179
256
1,163
10
168
ivankravets/hardwario-tower
platform.py
Python
HardwariotowerPlatform
HardwariotowerPlatform
24
154
24
25
6b7a67395afbc893c1af59ef11e4526135e94bdb
bigcode/the-stack
train
72212d35f3af7a9e43b26fc0
train
function
def inplace_relu_derivative(Z): """Compute the derivative of the rectified linear unit function given output value from relu Parameters ---------- Z : {array-like, sparse matrix}, shape (n_samples, n_features) The input data which is output from some relu Returns ------- Z_new ...
def inplace_relu_derivative(Z):
"""Compute the derivative of the rectified linear unit function given output value from relu Parameters ---------- Z : {array-like, sparse matrix}, shape (n_samples, n_features) The input data which is output from some relu Returns ------- Z_new : {array-like, sparse matrix}, s...
) The input data which is output from hyperbolic tan function Returns ------- Z_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ return 1 - (Z ** 2) def inplace_relu_derivative(Z):
64
64
106
7
57
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
inplace_relu_derivative
inplace_relu_derivative
142
156
142
142
e66c1d350429e46ea58af553157f325682b947a6
bigcode/the-stack
train
6d9bdbc6cc61d46070ed3abe
train
function
def squared_loss(y_true, y_pred): """Compute the squared loss for regression. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) values. y_pred : array-like or label indicator matrix Predicted values, as returned by a regression estimator. ...
def squared_loss(y_true, y_pred):
"""Compute the squared loss for regression. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) values. y_pred : array-like or label indicator matrix Predicted values, as returned by a regression estimator. Returns ------- loss : ...
) The transformed data. """ return (Z > 0).astype(Z.dtype) DERIVATIVES = {'tanh': inplace_tanh_derivative, 'logistic': inplace_logistic_derivative, 'relu': inplace_relu_derivative} def squared_loss(y_true, y_pred):
64
64
107
9
55
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
squared_loss
squared_loss
164
180
164
164
194bb20ccc47311ddf0717fbbfbc5a63ecf8c3ee
bigcode/the-stack
train
f316d2c9cc745a4d5f710df2
train
function
def logistic(X): """Compute the logistic function inplace. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ ...
def logistic(X):
"""Compute the logistic function inplace. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ return logisti...
_features) Data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Same as the input data. """ return X def logistic(X):
64
64
81
4
59
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
logistic
logistic
29
42
29
29
15c6b9bdeb3114b40cb9b62bc8c6841fbb49a0d1
bigcode/the-stack
train
b3f36e41bd4117717b660b92
train
function
def inplace_logistic_derivative(Z): """Compute the derivative of the logistic function given output value from logistic function It exploits the fact that the derivative is a simple function of the output value from logistic function Parameters ---------- Z : {array-like, sparse matrix}, s...
def inplace_logistic_derivative(Z):
"""Compute the derivative of the logistic function given output value from logistic function It exploits the fact that the derivative is a simple function of the output value from logistic function Parameters ---------- Z : {array-like, sparse matrix}, shape (n_samples, n_features) ...
=X) X /= X.sum(axis=1)[:, np.newaxis] return X ACTIVATIONS = {'identity': identity, 'tanh': tanh, 'logistic': logistic, 'relu': relu, 'softmax': softmax} def inplace_logistic_derivative(Z):
64
64
122
8
56
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
inplace_logistic_derivative
inplace_logistic_derivative
102
119
102
102
9c26683c759eb8616f2a9208d819170bca3cbb98
bigcode/the-stack
train
13a7b425b367533ccdaa3124
train
function
def binary_log_loss(y_true, y_prob): """Compute binary logistic loss for classification. This is identical to log_loss in binary classification case, but is kept for its use in multilabel case. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) l...
def binary_log_loss(y_true, y_prob):
"""Compute binary logistic loss for classification. This is identical to log_loss in binary classification case, but is kept for its use in multilabel case. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) labels. y_prob : array-like of fl...
=1) if y_true.shape[1] == 1: y_true = np.append(1 - y_true, y_true, axis=1) return -np.sum(y_true * np.log(y_prob)) / y_prob.shape[0] def binary_log_loss(y_true, y_prob):
64
64
187
10
54
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
binary_log_loss
binary_log_loss
211
234
211
211
ec84672c2f1763be1e1df7a464321072969481fd
bigcode/the-stack
train
e6d6696cb749f70e429481ad
train
function
def softmax(X): """Compute the K-way softmax function inplace. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. "...
def softmax(X):
"""Compute the K-way softmax function inplace. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ tmp = X -...
The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ np.clip(X, 0, np.finfo(X.dtype).max, out=X) return X def softmax(X):
64
64
117
5
58
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
softmax
softmax
78
95
78
78
5eec7367feed3c91159cb5207ca9dba4c2193b19
bigcode/the-stack
train
35346c6ceaa1fe79826c76c2
train
function
def relu(X): """Compute the rectified linear unit function inplace. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. ...
def relu(X):
"""Compute the rectified linear unit function inplace. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ n...
-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ return np.tanh(X, out=X) def relu(X):
64
64
98
5
59
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
relu
relu
61
75
61
61
fcdb64f34d920fa6440f05a2cf2772a90b37f2ac
bigcode/the-stack
train
25ed5260b92c6f88fa5e44c0
train
function
def tanh(X): """Compute the hyperbolic tan function inplace. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """...
def tanh(X):
"""Compute the hyperbolic tan function inplace. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ return n...
-like, sparse matrix}, shape (n_samples, n_features) The input data. Returns ------- X_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ return logistic_sigmoid(X, out=X) def tanh(X):
64
64
85
5
59
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
tanh
tanh
45
58
45
45
28983dfff01998265bb4b8d4aca8ccc7e2a79a67
bigcode/the-stack
train
151022f4da53f7670cfac73c
train
function
def log_loss(y_true, y_prob): """Compute Logistic loss for classification. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) labels. y_prob : array-like of float, shape = (n_samples, n_classes) Predicted probabilities, as returned by a class...
def log_loss(y_true, y_prob):
"""Compute Logistic loss for classification. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) labels. y_prob : array-like of float, shape = (n_samples, n_classes) Predicted probabilities, as returned by a classifier's predict_proba ...
Predicted values, as returned by a regression estimator. Returns ------- loss : float The degree to which the samples are correctly predicted. """ return ((y_true - y_pred) ** 2).mean() / 2 def log_loss(y_true, y_prob):
64
64
206
9
54
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
log_loss
log_loss
183
208
183
183
53f176d3e143884e70857d3e275995a744429a5f
bigcode/the-stack
train
bc0d640874dff80e531f9a79
train
function
def identity(X): """Simply return the input array. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X : {array-like, sparse matrix}, ...
def identity(X):
"""Simply return the input array. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X : {array-like, sparse matrix}, shape (n_samples,...
"""Utilities for the neural network modules """ # Author: Issam H. Laradji <issam.laradji@gmail.com> # Licence: BSD 3 clause import numpy as np from ..utils.fixes import expit as logistic_sigmoid def identity(X):
58
64
93
4
53
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
identity
identity
12
26
12
12
fb07ea1d986f7c68aeedeb978de110badb8af119
bigcode/the-stack
train
913d818da550007dbe9780df
train
function
def inplace_tanh_derivative(Z): """Compute the derivative of the hyperbolic tan function given output value from hyperbolic tan It exploits the fact that the derivative is a simple function of the output value from hyperbolic tan Parameters ---------- Z : {array-like, sparse matrix}, shape...
def inplace_tanh_derivative(Z):
"""Compute the derivative of the hyperbolic tan function given output value from hyperbolic tan It exploits the fact that the derivative is a simple function of the output value from hyperbolic tan Parameters ---------- Z : {array-like, sparse matrix}, shape (n_samples, n_features) ...
_samples, n_features) The input data which is output from logistic function Returns ------- Z_new : {array-like, sparse matrix}, shape (n_samples, n_features) The transformed data. """ return Z * (1 - Z) def inplace_tanh_derivative(Z):
64
64
134
8
56
RTHMaK/git-squash-master
scikit-learn-weighted_kde/sklearn/neural_network/_base.py
Python
inplace_tanh_derivative
inplace_tanh_derivative
122
139
122
122
08061b917dff26f14e3bee4e1f53a22fa195b4a5
bigcode/the-stack
train
68e373ffb79b1a5ad84f5ba5
train
class
class Imagenet2012(tfds.core.GeneratorBasedBuilder): """Imagenet 2012, aka ILSVRC 2012.""" VERSION = tfds.core.Version('5.1.0') SUPPORTED_VERSIONS = [ tfds.core.Version('5.0.0'), ] RELEASE_NOTES = { '5.1.0': 'Added test split.', '5.0.0': 'New split API (https://tensorflo...
class Imagenet2012(tfds.core.GeneratorBasedBuilder):
"""Imagenet 2012, aka ILSVRC 2012.""" VERSION = tfds.core.Version('5.1.0') SUPPORTED_VERSIONS = [ tfds.core.Version('5.0.0'), ] RELEASE_NOTES = { '5.1.0': 'Added test split.', '5.0.0': 'New split API (https://tensorflow.org/datasets/splits)', '4.0.0': '(u...
', 'n02492035_15739.JPEG', 'n02747177_10752.JPEG', 'n03018349_4028.JPEG', 'n03062245_4620.JPEG', 'n03347037_9675.JPEG', 'n03467068_12171.JPEG', 'n03529860_11437.JPEG', 'n03544143_17228.JPEG', 'n03633091_5218.JPEG', 'n03710637_5125.JPEG', 'n03961711_5286.JPEG', 'n04033995_...
256
256
1,401
13
243
vanshhhhh/datasets
tensorflow_datasets/image_classification/imagenet.py
Python
Imagenet2012
Imagenet2012
134
294
134
134
aed1bab82b03753214cb42ddb34e0cafa37bfbc1
bigcode/the-stack
train
cc888fbbd31636f2142e95e6
train
function
def _add_split_if_exists(split_list, split, split_path, dl_manager, **kwargs): """Add split to given list of splits only if the file exists.""" if not tf.io.gfile.exists(split_path): logging.warning( 'ImageNet 2012 Challenge %s split not found at %s. ' 'Proceeding with data generation anyways bu...
def _add_split_if_exists(split_list, split, split_path, dl_manager, **kwargs):
"""Add split to given list of splits only if the file exists.""" if not tf.io.gfile.exists(split_path): logging.warning( 'ImageNet 2012 Challenge %s split not found at %s. ' 'Proceeding with data generation anyways but the split will be ' 'missing from the dataset...', str(split)...
archive): for fname, fobj in archive: record = { 'file_name': fname, 'image': fobj, 'label': -1, } yield fname, record def _add_split_if_exists(split_list, split, split_path, dl_manager, **kwargs):
64
64
143
20
43
vanshhhhh/datasets
tensorflow_datasets/image_classification/imagenet.py
Python
_add_split_if_exists
_add_split_if_exists
297
315
297
297
cb145e535ded2487db7cdbf34838ade6c7bd4949
bigcode/the-stack
train
5c79be433bb2e1c2b2fe09fc
train
class
class _M_DBS_ (TFL.Meta.Object.__class__) : """Meta class for DBS classes.""" def __init__ (cls, name, bases, dct) : cls.__m_super.__init__ (name, bases, dct) if not name.startswith ("_") : MOM.DBW._Manager_.DBS_map [cls.scheme] = cls
class _M_DBS_ (TFL.Meta.Object.__class__) :
"""Meta class for DBS classes.""" def __init__ (cls, name, bases, dct) : cls.__m_super.__init__ (name, bases, dct) if not name.startswith ("_") : MOM.DBW._Manager_.DBS_map [cls.scheme] = cls
MOM import MOM from _TFL import TFL from _TFL import sos import _MOM._DBW._Manager_ import _TFL._Meta.Object import _TFL.Url class _M_DBS_ (TFL.Meta.Object.__class__) :
64
64
81
15
48
Tapyr/tapyr
_MOM/_DBW/_DBS_.py
Python
_M_DBS_
_M_DBS_
38
44
38
38
c339d38f84350dd932694bc571c81dfd29ddc916
bigcode/the-stack
train
a54cacf53d4fe776dfce591c
train
class
class _DBS_ (TFL.Meta.Object, metaclass = _M_DBS_) : """Base class for DBS classes.""" Fatal_Exceptions = () @classmethod def create_database (cls, db_url, manager) : pass # end def create_database @classmethod def delete_database (cls, db_url, manager) : try : ...
class _DBS_ (TFL.Meta.Object, metaclass = _M_DBS_) :
"""Base class for DBS classes.""" Fatal_Exceptions = () @classmethod def create_database (cls, db_url, manager) : pass # end def create_database @classmethod def delete_database (cls, db_url, manager) : try : sos.unlink (db_url.path) except OSError : ...
dct) : cls.__m_super.__init__ (name, bases, dct) if not name.startswith ("_") : MOM.DBW._Manager_.DBS_map [cls.scheme] = cls # end def __init__ # end class _M_DBS_ class _DBS_ (TFL.Meta.Object, metaclass = _M_DBS_) :
81
81
273
20
61
Tapyr/tapyr
_MOM/_DBW/_DBS_.py
Python
_DBS_
_DBS_
49
86
49
49
76325704d0d9f401aabb7bacf8abb5d7e5a4903d
bigcode/the-stack
train
856e67055d779be2ef4eb696
train
class
class CktElementF(Base): def cktelement_read_norm_amps(self) -> float: """Deliver the normal ampere rating for the active PDElement.""" return float(self.dss_obj.CktElementF(ctypes.c_int32(0), ctypes.c_double(0))) def cktelement_write_norm_amps(self, argument: float) -> float: """Allow...
class CktElementF(Base):
def cktelement_read_norm_amps(self) -> float: """Deliver the normal ampere rating for the active PDElement.""" return float(self.dss_obj.CktElementF(ctypes.c_int32(0), ctypes.c_double(0))) def cktelement_write_norm_amps(self, argument: float) -> float: """Allows to fix the normal ampere...
# -*- encoding: utf-8 -*- """ Created by eniocc at 11/10/2020 """ import ctypes from py_dss_interface.models.Base import Base class CktElementF(Base):
43
91
304
7
35
davilamds/py_dss_interface
src/py_dss_interface/models/CktElement/CktElementF.py
Python
CktElementF
CktElementF
10
31
10
11
7f0b6d66dd3ef4e7d95e11f6533273144ce5f607
bigcode/the-stack
train
e4b6ba2235ffb49ed611ef25
train
class
class ReverseTieRankingLeaderboardTest(unittest.TestCase): def setUp(self): self.leaderboard = TieRankingLeaderboard('ties', order=Leaderboard.ASC, decode_responses=True) def tearDown(self): self.leaderboard.redis_connection.flushdb() def test_delete_the_ties_ranking_internal_leaderboard_...
class ReverseTieRankingLeaderboardTest(unittest.TestCase):
def setUp(self): self.leaderboard = TieRankingLeaderboard('ties', order=Leaderboard.ASC, decode_responses=True) def tearDown(self): self.leaderboard.redis_connection.flushdb() def test_delete_the_ties_ranking_internal_leaderboard_when_you_delete_a_leaderboard_configured_for_ties(self): ...
from leaderboard.leaderboard import Leaderboard from leaderboard.tie_ranking_leaderboard import TieRankingLeaderboard import unittest import time import sure class ReverseTieRankingLeaderboardTest(unittest.TestCase):
41
256
2,296
10
30
saikiranravupalli/leaderboard-python
test/leaderboard/reverse_tie_ranking_leaderboard_test.py
Python
ReverseTieRankingLeaderboardTest
ReverseTieRankingLeaderboardTest
8
193
8
9
c21533d8d2e07b24b35153023e3f791075b8f500
bigcode/the-stack
train
3eac32de333fcf809490ecdc
train
function
def get_expiry_orders(): if frappe.db.get_value("Expiry Warning Settings", None, "hourly") == '1': hourly = frappe.db.get_value("Expiry Warning Settings", None, "expiry_warning_durati") if hourly: return frappe.db.sql("""\ SELECT count(*) FROM `tabMaintenance Order` WHERE status not in ('Completed'...
def get_expiry_orders():
if frappe.db.get_value("Expiry Warning Settings", None, "hourly") == '1': hourly = frappe.db.get_value("Expiry Warning Settings", None, "expiry_warning_durati") if hourly: return frappe.db.sql("""\ SELECT count(*) FROM `tabMaintenance Order` WHERE status not in ('Completed', 'Canceled') AND TIM...
')] for doc in frappe.get_all('DocType', fields= ["name"], filters = {"name": ("not in", doctype), 'is_submittable': 1}): notifications["for_doctype"][doc.name] = {"docstatus": 0} return notifications def get_expiry_orders():
67
67
224
6
60
Techstation-Egypt/ERP-T-assistant-MRS
maintenance_repair_services/notifications.py
Python
get_expiry_orders
get_expiry_orders
22
41
22
22
ed69949208152877a7749d298b858436487b8e76
bigcode/the-stack
train
897fb9cabc57005220cf6c44
train
function
def get_notification_config(): notifications = { "for_doctype": { "Maintenance Order": "maintenance_repair_services.notifications.get_expiry_orders" } } doctype = [d for d in notifications.get('for_doctype')] for doc in frappe.get_all('DocType', fields= ["name"], filters = {"name": ("not in", doctype),...
def get_notification_config():
notifications = { "for_doctype": { "Maintenance Order": "maintenance_repair_services.notifications.get_expiry_orders" } } doctype = [d for d in notifications.get('for_doctype')] for doc in frappe.get_all('DocType', fields= ["name"], filters = {"name": ("not in", doctype), 'is_submittable': 1}): notif...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe def get_notification_config():
50
64
116
5
44
Techstation-Egypt/ERP-T-assistant-MRS
maintenance_repair_services/notifications.py
Python
get_notification_config
get_notification_config
7
19
7
7
4894e07320b142980f9cd0424bbf8fa0b4d9e855
bigcode/the-stack
train
becb6ae17568b2291aaaa861
train
class
class JSPECTestScannerBoolean(JSPECTestScanner): """Class for testing the behaviour when using the ``scan`` method for booleans. A valid JSPEC boolean is either true or false. """ def test_scanner_boolean_good(self): """Test examples of good matches. The ``scan`` method should retu...
class JSPECTestScannerBoolean(JSPECTestScanner):
"""Class for testing the behaviour when using the ``scan`` method for booleans. A valid JSPEC boolean is either true or false. """ def test_scanner_boolean_good(self): """Test examples of good matches. The ``scan`` method should return a matching ``JSPEC`` with a ``JSPECBoo...
"""JSPEC Testing Module for scanning JSPEC documents for ``JSPECTestScannerBoolean``. """ from test.scanner import JSPECTestScanner from jspec.entity import ( JSPEC, JSPECBoolean, ) class JSPECTestScannerBoolean(JSPECTestScanner):
59
138
463
11
48
chrismalcolm/jspec
test/scanner/boolean.py
Python
JSPECTestScannerBoolean
JSPECTestScannerBoolean
11
83
11
11
068d0c786d31c2e229d19e69756a7833a1656cc6
bigcode/the-stack
train
cebf88efc9bfd929748fa925
train
function
def wrap_lines(value, indent=4) -> List[str]: prefix = " " * indent return [ textwrap.indent(line, prefix=prefix) for line in textwrap.wrap(value) ]
def wrap_lines(value, indent=4) -> List[str]:
prefix = " " * indent return [ textwrap.indent(line, prefix=prefix) for line in textwrap.wrap(value) ]
import textwrap from typing import List from sota_extractor.taskdb.v01 import Task, Dataset def wrap_lines(value, indent=4) -> List[str]:
35
64
45
13
21
zeke/sota-extractor
sota_extractor/scrapers/nlp_progress/printer.py
Python
wrap_lines
wrap_lines
7
11
7
7
f3acbf12c1bdcf52d21c905219c73c41312b816a
bigcode/the-stack
train
d3a362d3249a74b00d7c8a09
train
function
def sub_items(title, items, lines_func) -> List[str]: lines = [] if len(items) == 0: lines.append(f"{title}: -") else: lines.append(f"{title}:") for item in items: for i, line in enumerate(lines_func(item)): if i == 0: lines.append(f" ...
def sub_items(title, items, lines_func) -> List[str]:
lines = [] if len(items) == 0: lines.append(f"{title}: -") else: lines.append(f"{title}:") for item in items: for i, line in enumerate(lines_func(item)): if i == 0: lines.append(f" - {line}") else: ...
Task, Dataset def wrap_lines(value, indent=4) -> List[str]: prefix = " " * indent return [ textwrap.indent(line, prefix=prefix) for line in textwrap.wrap(value) ] def sub_items(title, items, lines_func) -> List[str]:
63
64
97
14
49
zeke/sota-extractor
sota_extractor/scrapers/nlp_progress/printer.py
Python
sub_items
sub_items
14
26
14
14
a21b22d74e739abab0343a6f314cc8b6a1dba627
bigcode/the-stack
train
dcbd7fe4e8d39b2d0ca1ff88
train
function
def task_lines(task: Task) -> List[str]: lines = [f"Name: {task.name}"] if task.description is None or task.description.strip() == "": lines.append("Description: -") else: lines.append("Description:") lines.extend(wrap_lines(task.description)) if task.parent is None: line...
def task_lines(task: Task) -> List[str]:
lines = [f"Name: {task.name}"] if task.description is None or task.description.strip() == "": lines.append("Description: -") else: lines.append("Description:") lines.extend(wrap_lines(task.description)) if task.parent is None: lines.append("Parent: -") else: l...
else: lines.append("Description:") lines.extend(wrap_lines(dataset.description)) lines.append(f"Rows: {len(dataset.sota.rows)}") lines.extend(sub_items("Subdatasets", dataset.subdatasets, dataset_lines)) return lines def task_lines(task: Task) -> List[str]:
64
64
185
11
52
zeke/sota-extractor
sota_extractor/scrapers/nlp_progress/printer.py
Python
task_lines
task_lines
42
67
42
42
38e6f792266ad28486dcf573024c3193ddf3252f
bigcode/the-stack
train
7093fa282c856c3fb5c2da1f
train
function
def dataset_lines(dataset: Dataset) -> List[str]: lines = [f"Name: {dataset.name}"] if dataset.description is None or dataset.description.strip() == "": lines.append("Description: -") else: lines.append("Description:") lines.extend(wrap_lines(dataset.description)) lines.append(f"...
def dataset_lines(dataset: Dataset) -> List[str]:
lines = [f"Name: {dataset.name}"] if dataset.description is None or dataset.description.strip() == "": lines.append("Description: -") else: lines.append("Description:") lines.extend(wrap_lines(dataset.description)) lines.append(f"Rows: {len(dataset.sota.rows)}") lines.extend...
title}:") for item in items: for i, line in enumerate(lines_func(item)): if i == 0: lines.append(f" - {line}") else: lines.append(f" {line}") return lines def dataset_lines(dataset: Dataset) -> List[str]:
64
64
98
11
52
zeke/sota-extractor
sota_extractor/scrapers/nlp_progress/printer.py
Python
dataset_lines
dataset_lines
29
39
29
29
1cd0a4e48375eba83d8f01ea40d5ffdd96989ddf
bigcode/the-stack
train
af77efadea3769cdee5022d2
train
function
def print_task(task: Task): """Print a task. Used for debugging purposes. """ lines = task_lines(task) print("\n".join(lines))
def print_task(task: Task):
"""Print a task. Used for debugging purposes. """ lines = task_lines(task) print("\n".join(lines))
.extend( sub_items( title="Datasets", items=task.datasets, lines_func=dataset_lines ) ) lines.extend( sub_items(title="Subtasks", items=task.subtasks, lines_func=task_lines) ) return lines def print_task(task: Task):
64
64
36
7
56
zeke/sota-extractor
sota_extractor/scrapers/nlp_progress/printer.py
Python
print_task
print_task
70
76
70
70
04b1aa3d986f9a1ab1c424aa9b8c5e52f302c20b
bigcode/the-stack
train
54afc115281d92de28bd3e3a
train
function
@dispatch(int,int,int) def product(first,second,third): result = first * second * third print(result);
@dispatch(int,int,int) def product(first,second,third):
result = first * second * third print(result);
from multipledispatch import dispatch #passing one parameter @dispatch(int,int) def product(first,second): result = first*second print(result); #passing two parameters @dispatch(int,int,int) def product(first,second,third):
55
64
28
14
40
shaurtoonetwork/Data-Structures-Implemented-In-Python
OOps/MethodOverLoading(Effcient).py
Python
product
product
11
14
11
12
8e7afc48f762527bf0dbcf963da5cf6d28d40529
bigcode/the-stack
train
1fe2f119d7b39aa9e64eb0ab
train
function
@dispatch(float,float,float) def product(first,second,third): result = first * second * third print(result);
@dispatch(float,float,float) def product(first,second,third):
result = first * second * third print(result);
); #passing two parameters @dispatch(int,int,int) def product(first,second,third): result = first * second * third print(result); #you can also pass data type of any value as per requirement @dispatch(float,float,float) def product(first,second,third):
64
64
28
14
49
shaurtoonetwork/Data-Structures-Implemented-In-Python
OOps/MethodOverLoading(Effcient).py
Python
product
product
17
20
17
18
75a8233e0adc29aaeb6d704a9531d058e9709a9c
bigcode/the-stack
train
450fbaf47cf2359b78ad2cd8
train
function
@dispatch(int,int) def product(first,second): result = first*second print(result);
@dispatch(int,int) def product(first,second):
result = first*second print(result);
from multipledispatch import dispatch #passing one parameter @dispatch(int,int) def product(first,second):
24
64
22
11
12
shaurtoonetwork/Data-Structures-Implemented-In-Python
OOps/MethodOverLoading(Effcient).py
Python
product
product
5
8
5
6
7a0ab355531edfaf133171f8fa570c21d08343eb
bigcode/the-stack
train
2b065952bf22b1f050d40aeb
train
class
class SchemaTests(TransactionTestCase): """ Tests that the schema-alteration code works correctly. Be aware that these tests are more liable than most to false results, as sometimes the code to check if a test has worked is almost as complex as the code it is testing. """ available_apps = ...
class SchemaTests(TransactionTestCase):
""" Tests that the schema-alteration code works correctly. Be aware that these tests are more liable than most to false results, as sometimes the code to check if a test has worked is almost as complex as the code it is testing. """ available_apps = [] models = [ Author, Autho...
import datetime import itertools import unittest from copy import copy from django.db import ( DatabaseError, IntegrityError, OperationalError, connection, ) from django.db.models import Model from django.db.models.fields import ( BigIntegerField, BinaryField, BooleanField, CharField, DateTimeField, Intege...
215
256
13,168
7
208
jacinda/django
tests/schema/tests.py
Python
SchemaTests
SchemaTests
28
1,481
28
28
2303ab396ecbe8ca53b2ff83f0338643832ae5f4
bigcode/the-stack
train
5fe2ad41437b704260d104ce
train
function
def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception: hostname = None return hostname
def ip_to_host(ip):
''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception: hostname = None return hostname
in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] if len(info) >= 4: l.append(info[3]) except socket.gaierror: pass return l and l[0] or None def ip_to_host(ip):
64
64
52
6
57
hvnsweeting/salt
salt/utils/network.py
Python
ip_to_host
ip_to_host
189
197
189
189
fe8fb65869a4be6812a2176992a1d46044fecf08
bigcode/the-stack
train
79e8b03d71a2abf9c97f5c2e
train
function
def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret
def remote_port_tcp(port):
''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret
continue ret.update(_parse_tcp_line(line)) return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port):
64
64
45
6
57
hvnsweeting/salt
salt/utils/network.py
Python
remote_port_tcp
remote_port_tcp
923
928
923
923
2f9e8db4c7fe15cf7c07928392d2074d7c474827
bigcode/the-stack
train
6bae2dd28e4009a41fe40ffd
train
function
def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfa...
def _subnets(proto='inet', interfaces_=None):
''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value ...
iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', {})[0].get('address', '') else: return error def _subnets(proto='inet', interfaces_=None):
78
78
263
12
65
hvnsweeting/salt
salt/utils/network.py
Python
_subnets
_subnets
726
758
726
726
411bf632aa6b2a9ab7a3c903b98475a4d0e582cb
bigcode/the-stack
train
65a9c7f67afed6891d6ebccf
train
function
def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip)
def is_ip(ip):
''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip)
ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception: hostname = None return hostname # pylint: enable=C0103 def is_ip(ip):
64
64
41
5
58
hvnsweeting/salt
salt/utils/network.py
Python
is_ip
is_ip
202
206
202
202
d56190d80e32f495d8f9981fc80b7cfb8a331bef
bigcode/the-stack
train
21a7a7160a2493048b4a28d9
train
function
def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0'))
def get_net_size(mask):
''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0'))
else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return str(net.network_address) def get_net_size(mask):
64
64
88
6
58
hvnsweeting/salt
salt/utils/network.py
Python
get_net_size
get_net_size
643
651
643
643
a3d851e4e495e2480b6e7a4ad4cf35735c664537
bigcode/the-stack
train
a8bc3d896bf44e81806affdd
train
function
def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRE...
def _freebsd_remotes_on(port, which_end):
''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp...
_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks...
180
180
602
12
167
hvnsweeting/salt
salt/utils/network.py
Python
_freebsd_remotes_on
_freebsd_remotes_on
1,023
1,077
1,023
1,023
bbea4b7fe1bebc5dd30527e711cc97edccd77c68
bigcode/the-stack
train
d0f8ebb7443816db853648d1
train
function
def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits))
def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103
''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits))
8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103
64
64
76
23
40
hvnsweeting/salt
salt/utils/network.py
Python
_number_of_set_bits_to_ipv4_netmask
_number_of_set_bits_to_ipv4_netmask
283
289
283
283
e2f14501cdec9f4341b646e2dad130416b60e669
bigcode/the-stack
train
9f5a5e00f0c7ec996a0e9a38
train
function
def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr']...
def _parse_tcp_line(line):
''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ...
) if salt.utils.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.is_windows(): return _windows_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line):
64
64
160
7
56
hvnsweeting/salt
salt/utils/network.py
Python
_parse_tcp_line
_parse_tcp_line
968
982
968
968
22a465ca4cc488f1939d56f7f75a7643eeddc517
bigcode/the-stack
train
5fe91f9e1bf3021a2cc103a2
train
function
def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error
def hw_addr(iface):
''' Return the hardware address (a.k.a. MAC address) for a given interface ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error
(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def hw_addr(iface):
64
64
69
6
57
hvnsweeting/salt
salt/utils/network.py
Python
hw_addr
hw_addr
690
699
690
690
280ae8e98415bd8d404ee305f68cdbd7e3ff155b
bigcode/the-stack
train
5a2fed64cd3074f1ec17a2da
train
function
def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.fopen(statf, 'rb') as fp_: for line in fp_: ...
def active_tcp():
''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.fopen(statf, 'rb') as fp_: for line in fp_: if line.strip()....
ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except: # pylint: disable=bare-except return def active_tcp():
64
64
100
4
59
hvnsweeting/salt
salt/utils/network.py
Python
active_tcp
active_tcp
900
912
900
900
019c97da7422086a582e741fde508769c5566c69
bigcode/the-stack
train
8eb15e4528fd25a0961d7077
train
function
def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', {})[0].get('address', '') else: return error
def interface_ip(iface):
''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', {})[0].get('address', '') else: return error
Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface):
64
64
77
6
57
hvnsweeting/salt
salt/utils/network.py
Python
interface_ip
interface_ip
714
723
714
714
cf6a6ca0f3b00b699ca8589d087df11f342c8e28
bigcode/the-stack
train
25ab9ddda8b9ff6e271c7e09
train
function
def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False
def is_ipv6(ip):
''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False
is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip):
64
64
53
6
57
hvnsweeting/salt
salt/utils/network.py
Python
is_ipv6
is_ipv6
219
226
219
219
ba98d023a7c2edb0ad49f8fb0245506975e0b0c0
bigcode/the-stack
train
003d41d30f15ece2c937e8d2
train
function
def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local ...
def _sunos_remotes_on(port, which_end):
''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind S...
] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) return ret def _sunos_remotes_on(port, ...
113
113
378
12
100
hvnsweeting/salt
salt/utils/network.py
Python
_sunos_remotes_on
_sunos_remotes_on
985
1,020
985
985
261edba0acdd1aae4ed82ed377a0d6d5ab9e7c05
bigcode/the-stack
train
a36890b95f862e8cc1e7d76a
train
function
def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6')
def subnets6():
''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6')
: ret.add(intf.network) return [str(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6():
64
64
33
5
59
hvnsweeting/salt
salt/utils/network.py
Python
subnets6
subnets6
768
772
768
768
005ceb084525981b2dace22cb31856cc29c5ae03
bigcode/the-stack
train
030b9c02c2ebdbc493143c7d
train
function
def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.which('ip') ifconfig_path = None if ip_path else salt.utils.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), ...
def linux_interfaces():
''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.which('ip') ifconfig_path = None if ip_path else salt.utils.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, ...
inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces():
73
73
245
4
68
hvnsweeting/salt
salt/utils/network.py
Python
linux_interfaces
linux_interfaces
497
527
497
497
2e2349d50d114bd0133e4a4bb7633db61955b7ba
bigcode/the-stack
train
1494f8de259c05d362cb7865
train
function
def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_t...
def natural_ipv4_netmask(ip, fmt='prefixlen'):
''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '...
_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def natural_ipv4_netmask(ip, fmt='prefixlen'):
64
64
103
13
50
hvnsweeting/salt
salt/utils/network.py
Python
natural_ipv4_netmask
natural_ipv4_netmask
229
245
229
229
343630636b69cf808551f9d72495ae8519270b85
bigcode/the-stack
train
c83ecf521614c50bf2276e75
train
function
def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error
def interface(iface):
''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error
the hardware address (a.k.a. MAC address) for a given interface ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface):
64
64
66
5
58
hvnsweeting/salt
salt/utils/network.py
Python
interface
interface
702
711
702
702
cca6dc0e4e4a4ac323d63e2aacfd2368a1485310
bigcode/the-stack
train
f25093ccc582b59a2c23d4a6
train
function
def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.fop...
def _remotes_on(port, which_end):
''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.fopen(statf, 'r') as fp_: ...
of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(por...
86
86
287
10
75
hvnsweeting/salt
salt/utils/network.py
Python
_remotes_on
_remotes_on
931
965
931
931
423571d02693baab1b69160c78da38d5af7fa65a
bigcode/the-stack
train
f34685b69e1541e0b4beac97
train
function
def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' return _generate_minion_id().first() or 'localhost'
def generate_minion_id():
''' Return only first element of the hostname from all possible list. :return: ''' return _generate_minion_id().first() or 'localhost'
.', '::1'] or len(hst) == 1): hosts.extend(hst) # include public and private ipaddresses return hosts.extend([addr for addr in salt.utils.network.ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id():
64
64
41
6
58
hvnsweeting/salt
salt/utils/network.py
Python
generate_minion_id
generate_minion_id
143
149
143
143
6656765b9b2a4aa52c97e1d82f93eba28906b6e0
bigcode/the-stack
train
5567cb0cb876dac753af89ec
train
function
def get_fqhostname(): ''' Returns the fully qualified hostname ''' l = [] l.append(socket.getfqdn()) # try socket.getaddrinfo try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAM...
def get_fqhostname():
''' Returns the fully qualified hostname ''' l = [] l.append(socket.getfqdn()) # try socket.getaddrinfo try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) fo...
IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname():
64
64
143
6
58
hvnsweeting/salt
salt/utils/network.py
Python
get_fqhostname
get_fqhostname
166
186
166
166
3d508ad1125ed5f57a95c0e33070e39be19c56a9
bigcode/the-stack
train
bb0a19731dcf6d6354ee6074
train
function
def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 ...
def _number_of_set_bits(x):
''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f
IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x):
64
64
143
8
55
hvnsweeting/salt
salt/utils/network.py
Python
_number_of_set_bits
_number_of_set_bits
293
303
293
293
0699fb801c60faf8c31970513894918cc1d784f2
bigcode/the-stack
train
2664a96f8827a71f6f1eec6b
train
function
def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ...
def hex2ip(hex_ip, invert=False):
''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2...
, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be r...
105
105
353
10
95
hvnsweeting/salt
salt/utils/network.py
Python
hex2ip
hex2ip
844
876
844
844
3d30a115758a2e5140e12c4a5d56ed9431825b98
bigcode/the-stack
train
f66003be4fe1d8e36cf3211f
train
function
def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE D...
def _linux_remotes_on(port, which_end):
''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 99...
10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.to_str(da...
218
218
729
11
206
hvnsweeting/salt
salt/utils/network.py
Python
_linux_remotes_on
_linux_remotes_on
1,214
1,268
1,214
1,214
2fc2e67b64a628443c272ce9d1e1cebb10d24c06
bigcode/the-stack
train
24c2eea3fb97ca3353bb75fb
train
function
def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False
def is_ipv4(ip):
''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False
hostname = None return hostname # pylint: enable=C0103 def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip):
64
64
53
6
58
hvnsweeting/salt
salt/utils/network.py
Python
is_ipv4
is_ipv4
209
216
209
209
f43b03e7d1a9c740895204201315ff9c60804dc9
bigcode/the-stack
train
052808d0d879d72bdda84fbf
train
function
def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Add...
def _windows_remotes_on(port, which_end):
r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State...
local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host)...
96
96
320
11
84
hvnsweeting/salt
salt/utils/network.py
Python
_windows_remotes_on
_windows_remotes_on
1,176
1,211
1,176
1,176
b843cebd33ad6ad09ee99185dc412b54f491f75c
bigcode/the-stack
train
79b85d4b5753078e513d2d75
train
function
def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the curre...
def _interfaces_ip(out):
''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''...
pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set...
225
225
751
6
218
hvnsweeting/salt
salt/utils/network.py
Python
_interfaces_ip
_interfaces_ip
308
398
308
308
b67787af72543983ed87dc4c635944a8f4feb5ae
bigcode/the-stack
train
b33ad5b749f825f3d40d88b3
train
function
def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret
def local_port_tcp(port):
''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret
6']: if os.path.isfile(statf): with salt.utils.fopen(statf, 'rb') as fp_: for line in fp_: if line.strip().startswith('sl'): continue ret.update(_parse_tcp_line(line)) return ret def local_port_tcp(port):
64
64
43
6
57
hvnsweeting/salt
salt/utils/network.py
Python
local_port_tcp
local_port_tcp
915
920
915
915
cab991a8f98aeb2814bdf7b46713a36593f02644
bigcode/the-stack
train
f563cd1078e2db521b551e46
train
function
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if in...
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'):
''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k...
elif isinstance(addr, six.string_types): return ipaddress.ip_address(addr) in cidr for ip_addr in addr: if ipaddress.ip_address(ip_addr) in cidr: return True return False def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'):
69
69
232
21
47
hvnsweeting/salt
salt/utils/network.py
Python
_ip_addrs
_ip_addrs
797
823
797
797
7883834d8af4170833a6bfedb908af3a70612c3b
bigcode/the-stack
train
aa817c1009584e8b45274634
train
function
def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out
def isportopen(host, port):
''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out
name__) # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. ''' return ''.join([ c for c in host[0:255] if c in (ascii_letters + digits + '.-') ]) def isportopen(host, port):
63
64
69
8
55
hvnsweeting/salt
salt/utils/network.py
Python
isportopen
isportopen
44
55
44
44
066ebf33e90acf9116a2f0cc78162e464d6705c8
bigcode/the-stack
train
7209f61bc4759bbe74dd02b8
train
function
def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return ...
def ip_addrs6(interface=None, include_loopback=False, interface_data=None):
''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6')
_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None):
64
64
88
17
47
hvnsweeting/salt
salt/utils/network.py
Python
ip_addrs6
ip_addrs6
835
841
835
835
02b9e3e24eebf9614baa61a28369c5bbd1593827
bigcode/the-stack
train
75a6894300bfccbca6f819cc
train
function
def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
def _ipv4_to_bits(ipaddr):
''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
R-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return str(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr):
64
64
59
9
55
hvnsweeting/salt
salt/utils/network.py
Python
_ipv4_to_bits
_ipv4_to_bits
666
671
666
666
7e706315d9893c9b0ef53fddb779d0a49c46fedf
bigcode/the-stack
train
c97fc58082f076fbcab09799
train
function
def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'{0}\''.format(cidr)) return False if addr is None: addr ...
def in_subnet(cidr, addr=None):
''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'{0}\''.format(cidr)) return False if addr is None: addr = ip_addrs() addr.extend...
nets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None):
64
64
143
10
54
hvnsweeting/salt
salt/utils/network.py
Python
in_subnet
in_subnet
775
794
775
775
07b1f4df55e4260de808a4c862cbc9ab6adf4c04
bigcode/the-stack
train
c531424078019a13c2cedc36
train
function
def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:...
def mac2eui64(mac, prefix=None):
''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64...
>> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None):
69
69
231
11
58
hvnsweeting/salt
salt/utils/network.py
Python
mac2eui64
mac2eui64
879
897
879
879
884e2d102d5519e2166c65b8f90272a93f406939
bigcode/the-stack
train
3374a95c74298bb2c089c479
train
function
def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.is_windows(): return win_interfaces() else: return linux_interfaces()
def interfaces():
''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.is_windows(): return win_interfaces() else: return linux_interfaces()
i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces...
64
64
42
3
60
hvnsweeting/salt
salt/utils/network.py
Python
interfaces
interfaces
625
632
625
625
944be496c046cdcf5849b6346ba1687959842a9d
bigcode/the-stack
train
51f85fb86a99509b1e0c9d00
train
function
def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4))
def rpad_ipv4_network(ip):
''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4))
mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip):
64
64
85
8
55
hvnsweeting/salt
salt/utils/network.py
Python
rpad_ipv4_network
rpad_ipv4_network
248
256
248
248
b57cb037aecae59de1625ad3da7796096f89ca82
bigcode/the-stack
train
9bc7370269631c29e578bf97
train
function
def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_ifa...
def _interfaces_ipconfig(out):
''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter...
stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.to_str(cmd1), salt.utils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), sh...
120
120
403
7
112
hvnsweeting/salt
salt/utils/network.py
Python
_interfaces_ipconfig
_interfaces_ipconfig
530
576
530
530
d0c8e71a92e92a83c741c1e30d52c0ef9e88f8b0
bigcode/the-stack
train
b132d8596d819bef78c2e9d1
train
function
def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return str(ipaddress.ip_network...
def calc_net(ipaddr, netmask=None):
''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return str(ipaddress.ip_network(ipaddr, strict=False))
192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None):
63
64
88
10
53
hvnsweeting/salt
salt/utils/network.py
Python
calc_net
calc_net
654
663
654
654
0f45a5b48668d273d7b65ffd3eac2b37942242db
bigcode/the-stack
train
a025fdd900e5329eb7336920
train
function
def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ...
def win_interfaces():
''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[i...
Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key ==...
119
119
398
4
115
hvnsweeting/salt
salt/utils/network.py
Python
win_interfaces
win_interfaces
579
622
579
579
08081cc52b3a7fe78e3d42bf358772341422a2ac
bigcode/the-stack
train