desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns an empty statement object prepopulated with the correct action and the
desired effect.'
| def _getEmptyStatement(self, effect):
| statement = {'Action': 'execute-api:Invoke', 'Effect': (effect[:1].upper() + effect[1:].lower()), 'Resource': []}
return statement
|
'This function loops over an array of objects containing a resourceArn and
conditions statement and generates the array of statements for the policy.'
| def _getStatementForEffect(self, effect, methods):
| statements = []
if (len(methods) > 0):
statement = self._getEmptyStatement(effect)
for curMethod in methods:
if ((curMethod['conditions'] is None) or (len(curMethod['conditions']) == 0)):
statement['Resource'].append(curMethod['resourceArn'])
else:
... |
'Adds a \'*\' allow to the policy to authorize access to all methods of an API'
| def allowAllMethods(self):
| self._addMethod('Allow', HttpVerb.ALL, '*', [])
|
'Adds a \'*\' allow to the policy to deny access to all methods of an API'
| def denyAllMethods(self):
| self._addMethod('Deny', HttpVerb.ALL, '*', [])
|
'Adds an API Gateway method (Http verb + Resource path) to the list of allowed
methods for the policy'
| def allowMethod(self, verb, resource):
| self._addMethod('Allow', verb, resource, [])
|
'Adds an API Gateway method (Http verb + Resource path) to the list of denied
methods for the policy'
| def denyMethod(self, verb, resource):
| self._addMethod('Deny', verb, resource, [])
|
'Adds an API Gateway method (Http verb + Resource path) to the list of allowed
methods and includes a condition for the policy statement. More on AWS policy
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'
| def allowMethodWithConditions(self, verb, resource, conditions):
| self._addMethod('Allow', verb, resource, conditions)
|
'Adds an API Gateway method (Http verb + Resource path) to the list of denied
methods and includes a condition for the policy statement. More on AWS policy
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'
| def denyMethodWithConditions(self, verb, resource, conditions):
| self._addMethod('Deny', verb, resource, conditions)
|
'Generates the policy document based on the internal lists of allowed and denied
conditions. This will generate a policy with two main statements for the effect:
one statement for Allow and one statement for Deny.
Methods that includes conditions will have their own statement in the policy.'
| def build(self):
| if (((self.allowMethods is None) or (len(self.allowMethods) == 0)) and ((self.denyMethods is None) or (len(self.denyMethods) == 0))):
raise NameError('No statements defined for the policy')
policy = {'principalId': self.principalId, 'policyDocument': {'Version': self.version, 'Statement':... |
'A hack to get around the deprecation errors in 2.6.'
| @property
def message(self):
| return self._message
|
'Returns this token as a plain string, suitable for storage.
The resulting string includes the token\'s secret, so you should never
send or store this string where a third party can read it.'
| def to_string(self):
| items = [('oauth_token', self.key), ('oauth_token_secret', self.secret)]
if (self.callback_confirmed is not None):
items.append(('oauth_callback_confirmed', self.callback_confirmed))
return urlencode(items)
|
'Deserializes a token from a string like one returned by
`to_string()`.'
| @staticmethod
def from_string(s):
| if (not len(s)):
raise ValueError('Invalid parameter string.')
params = parse_qs(u(s), keep_blank_values=False)
if (not len(params)):
raise ValueError('Invalid parameter string.')
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oau... |
'Get any non-OAuth parameters.'
| def get_nonoauth_parameters(self):
| return dict([(k, v) for (k, v) in self.items() if (not k.startswith('oauth_'))])
|
'Serialize as a header for an HTTPAuth request.'
| def to_header(self, realm=''):
| oauth_params = ((k, v) for (k, v) in self.items() if k.startswith('oauth_'))
stringy_params = ((k, escape(v)) for (k, v) in oauth_params)
header_params = (('%s="%s"' % (k, v)) for (k, v) in stringy_params)
params_header = ', '.join(header_params)
auth_header = ('OAuth realm="%s"' % realm)
... |
'Serialize as post data for a POST request.'
| def to_postdata(self):
| items = []
for (k, v) in sorted(self.items()):
items.append((k.encode('utf-8'), to_utf8_optional_iterator(v)))
return urlencode(items, True).replace('+', '%20')
|
'Serialize as a URL for a GET request.'
| def to_url(self):
| base_url = urlparse(self.url)
if PY3:
query = parse_qs(base_url.query)
for (k, v) in self.items():
query.setdefault(k, []).append(to_utf8_optional_iterator(v))
scheme = base_url.scheme
netloc = base_url.netloc
path = base_url.path
params = base_url.par... |
'Return a string that contains the parameters that must be signed.'
| def get_normalized_parameters(self):
| items = []
for (key, value) in self.items():
if (key == 'oauth_signature'):
continue
if isinstance(value, STRING_TYPES):
items.append((to_utf8_if_string(key), to_utf8(value)))
else:
try:
value = list(value)
except TypeError ... |
'Set the signature parameter to the result of sign.'
| def sign_request(self, signature_method, consumer, token):
| if (not self.is_form_encoded):
self['oauth_body_hash'] = base64.b64encode(sha1(self.body).digest())
if ('oauth_consumer_key' not in self):
self['oauth_consumer_key'] = consumer.key
if (token and ('oauth_token' not in self)):
self['oauth_token'] = token.key
self['oauth_signature_m... |
'Get seconds since epoch (UTC).'
| @classmethod
def make_timestamp(cls):
| return str(int(time.time()))
|
'Generate pseudorandom number.'
| @classmethod
def make_nonce(cls):
| return str(random.SystemRandom().randint(0, 100000000))
|
'Combines multiple parameter sources.'
| @classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None):
| if (parameters is None):
parameters = {}
if headers:
auth_header = None
for (k, v) in headers.items():
if ((k.lower() == 'authorization') or (k.upper() == 'HTTP_AUTHORIZATION')):
auth_header = v
if (auth_header and (auth_header[:6] == 'OAuth ')):
... |
'Turn Authorization: header into parameters.'
| @staticmethod
def _split_header(header):
| params = {}
parts = header.split(',')
for param in parts:
if (param.find('realm') > (-1)):
continue
param = param.strip()
param_parts = param.split('=', 1)
params[param_parts[0]] = unquote(param_parts[1].strip('"'))
return params
|
'Turn URL string into parameters.'
| @staticmethod
def _split_url_string(param_str):
| if (not PY3):
param_str = b(param_str, 'utf-8')
parameters = parse_qs(param_str, keep_blank_values=True)
for (k, v) in parameters.items():
if (len(v) == 1):
parameters[k] = unquote(v[0])
else:
parameters[k] = sorted([unquote(s) for s in v])
return paramete... |
'Verifies an api call and checks all the parameters.'
| def verify_request(self, request, consumer, token):
| self._check_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters
|
'Optional support for the authenticate header.'
| def build_authenticate_header(self, realm=''):
| return {'WWW-Authenticate': ('OAuth realm="%s"' % realm)}
|
'Verify the correct version of the request for this server.'
| def _check_version(self, request):
| version = self._get_version(request)
if (version and (version != self.version)):
raise Error(('OAuth version %s not supported.' % str(version)))
|
'Return the version of the request for this server.'
| def _get_version(self, request):
| try:
version = request.get_parameter('oauth_version')
except:
version = OAUTH_VERSION
return version
|
'Figure out the signature with some defaults.'
| def _get_signature_method(self, request):
| signature_method = request.get('oauth_signature_method')
if (signature_method is None):
signature_method = SIGNATURE_METHOD
try:
return self.signature_methods[signature_method]
except KeyError:
signature_method_names = ', '.join(self.signature_methods.keys())
raise Err... |
'Verify that timestamp is recentish.'
| def _check_timestamp(self, timestamp):
| timestamp = int(timestamp)
now = int(time.time())
lapsed = (now - timestamp)
if (lapsed > self.timestamp_threshold):
raise Error(('Expired timestamp: given %d and now %s has a greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold... |
'Calculates the string that needs to be signed.
This method returns a 2-tuple containing the starting key for the
signing and the message to be signed. The latter may be used in error
messages to help clients debug their software.'
| def signing_base(self, request, consumer, token):
| raise NotImplementedError
|
'Returns the signature for the given request, based on the consumer
and token also provided.
You should use your implementation of `signing_base()` to build the
message to sign. Otherwise it may be less useful for debugging.'
| def sign(self, request, consumer, token):
| raise NotImplementedError
|
'Returns whether the given signature is the correct signature for
the given consumer and token signing the given request.'
| def check(self, request, consumer, token, signature):
| built = self.sign(request, consumer, token)
return (built == signature)
|
'Builds the base signature string.'
| def sign(self, request, consumer, token):
| (key, raw) = self.signing_base(request, consumer, token)
hashed = hmac.new(key, raw, sha1)
return binascii.b2a_base64(hashed.digest())[:(-1)]
|
'Concatenates the consumer key and secret with the token\'s
secret.'
| def signing_base(self, request, consumer, token):
| sig = ('%s&' % escape(consumer.secret))
if token:
sig = (sig + escape(token.secret))
return (sig, sig)
|
'Make sure WSGI header HTTP_AUTHORIZATION is detected correctly.'
| def test_from_request_works_with_wsgi(self):
| url = 'http://sp.example.com/'
params = {'oauth_version': '1.0', 'oauth_nonce': '4572616e48616d6d65724c61686176', 'oauth_timestamp': '137131200', 'oauth_consumer_key': '0685bd9184jfhq22', 'oauth_signature_method': 'HMAC-SHA1', 'oauth_token': 'ad180jjd733klru7', 'oauth_signature': 'wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%... |
'Checks for the Authorization header should be case insensitive.'
| def test_from_request_is_case_insensitive_checking_for_auth(self):
| url = 'http://sp.example.com/'
params = {'oauth_version': '1.0', 'oauth_nonce': '4572616e48616d6d65724c61686176', 'oauth_timestamp': '137131200', 'oauth_consumer_key': '0685bd9184jfhq22', 'oauth_signature_method': 'HMAC-SHA1', 'oauth_token': 'ad180jjd733klru7', 'oauth_signature': 'wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%... |
'Test getting an access token via GET.'
| def test_access_token_get(self):
| client = oauth.Client(self.consumer, None)
(resp, content) = client.request(self._uri('request_token'), 'GET')
self.assertEqual(int(resp['status']), 200)
|
'Test getting an access token via POST.'
| def test_access_token_post(self):
| client = oauth.Client(self.consumer, None)
(resp, content) = client.request(self._uri('request_token'), 'POST')
self.assertEqual(int(resp['status']), 200)
res = dict(parse_qsl(content))
self.assertTrue(('oauth_token' in res))
self.assertTrue(('oauth_token_secret' in res))
|
'A test of a two-legged OAuth POST request.'
| def test_two_legged_post(self):
| (resp, content) = self._two_legged('POST')
self.assertEqual(int(resp['status']), 200)
|
'A test of a two-legged OAuth GET request.'
| def test_two_legged_get(self):
| (resp, content) = self._two_legged('GET')
self.assertEqual(int(resp['status']), 200)
|
'Return an OAuth Request object for the current request.'
| def get_oauth_request(self):
| try:
method = os.environ['REQUEST_METHOD']
except:
method = 'GET'
postdata = None
if (method in ('POST', 'PUT')):
postdata = self.request.body
return oauth.Request.from_request(method, self.request.uri, headers=self.request.headers, query_string=postdata)
|
'Return the client from the OAuth parameters.'
| def get_client(self, request=None):
| if (not isinstance(request, oauth.Request)):
request = self.get_oauth_request()
client_key = request.get_parameter('oauth_consumer_key')
if (not client_key):
raise Exception('Missing "oauth_consumer_key" parameter in OAuth "Authorization" header')
client = models.Client... |
'Returns a Client object if this is a valid OAuth request.'
| def is_valid(self):
| try:
request = self.get_oauth_request()
client = self.get_client(request)
params = self._server.verify_request(request, client, None)
except Exception as e:
raise e
return client
|
'Runs the model on the given data for one full pass.'
| def run_epoch(self, session, data_size, batch_generator, is_training, verbose=0, freq=10, summary_writer=None, debug=False, divide_by_n=1):
| epoch_size = (data_size // (self.batch_size * self.num_unrollings))
if ((data_size % (self.batch_size * self.num_unrollings)) != 0):
epoch_size += 1
if (verbose > 0):
logging.info('epoch_size: %d', epoch_size)
logging.info('data_size: %d', data_size)
logging.info('num_u... |
'Generate a single batch from the current cursor position in the data.'
| def _next_batch(self):
| batch = np.zeros(shape=self._batch_size, dtype=np.float)
for b in range(self._batch_size):
batch[b] = char2id(self._text[self._cursor[b]], self.vocab_index_dict)
self._cursor[b] = ((self._cursor[b] + 1) % self._text_size)
return batch
|
'Generate the next array of batches from the data. The array consists of
the last batch of the previous array, followed by num_unrollings new ones.'
| def next(self):
| batches = [self._last_batch]
for step in range(self._n_unrollings):
batches.append(self._next_batch())
self._last_batch = batches[(-1)]
return batches
|
'Returns a single_color_func associated with the word'
| def get_color_func(self, word):
| try:
color_func = next((color_func for (color_func, words) in self.color_func_to_words if (word in words)))
except StopIteration:
color_func = self.default_color_func
return color_func
|
'Generate a color for a given word using a fixed image.'
| def __call__(self, word, font_size, font_path, position, orientation, **kwargs):
| font = ImageFont.truetype(font_path, font_size)
transposed_font = ImageFont.TransposedFont(font, orientation=orientation)
box_size = transposed_font.getsize(word)
x = position[0]
y = position[1]
patch = self.image[x:(x + box_size[0]), y:(y + box_size[1])]
if (patch.ndim == 3):
patch ... |
'Create a word_cloud from words and frequencies.
Alias to generate_from_frequencies.
Parameters
frequencies : dict from string to float
A contains words and associated frequency.
Returns
self'
| def fit_words(self, frequencies):
| return self.generate_from_frequencies(frequencies)
|
'Create a word_cloud from words and frequencies.
Parameters
frequencies : dict from string to float
A contains words and associated frequency.
max_font_size : int
Use this font-size instead of self.max_font_size
Returns
self'
| def generate_from_frequencies(self, frequencies, max_font_size=None):
| frequencies = sorted(frequencies.items(), key=item1, reverse=True)
if (len(frequencies) <= 0):
raise ValueError(('We need at least 1 word to plot a word cloud, got %d.' % len(frequencies)))
frequencies = frequencies[:self.max_words]
max_frequency = float(frequ... |
'Splits a long text into words, eliminates the stopwords.
Parameters
text : string
The text to be processed.
Returns
words : dict (string, int)
Word tokens with associated frequency.
..versionchanged:: 1.2.2
Changed return type from list of tuples to dict.
Notes
There are better ways to do word tokenization, but I don\... | def process_text(self, text):
| stopwords = set([i.lower() for i in self.stopwords])
flags = (re.UNICODE if ((sys.version < '3') and (type(text) is unicode)) else 0)
regexp = (self.regexp if (self.regexp is not None) else "\\w[\\w']+")
words = re.findall(regexp, text, flags)
words = [word for word in words if (word.lower() not in ... |
'Generate wordcloud from text.
The input "text" is expected to be a natural text. If you pass a sorted
list of words, words will appear in your output twice. To remove this
duplication, set ``collocations=False``.
Calls process_text and generate_from_frequencies.
..versionchanged:: 1.2.2
Argument of generate_from_frequ... | def generate_from_text(self, text):
| words = self.process_text(text)
self.generate_from_frequencies(words)
return self
|
'Generate wordcloud from text.
The input "text" is expected to be a natural text. If you pass a sorted
list of words, words will appear in your output twice. To remove this
duplication, set ``collocations=False``.
Alias to generate_from_text.
Calls process_text and generate_from_frequencies.
Returns
self'
| def generate(self, text):
| return self.generate_from_text(text)
|
'Check if ``layout_`` was computed, otherwise raise error.'
| def _check_generated(self):
| if (not hasattr(self, 'layout_')):
raise ValueError('WordCloud has not been calculated, call generate first.')
|
'Recolor existing layout.
Applying a new coloring is much faster than generating the whole
wordcloud.
Parameters
random_state : RandomState, int, or None, default=None
If not None, a fixed random state is used. If an int is given, this
is used as seed for a random.Random state.
color_func : function or None, default=No... | def recolor(self, random_state=None, color_func=None, colormap=None):
| if isinstance(random_state, int):
random_state = Random(random_state)
self._check_generated()
if (color_func is None):
if (colormap is None):
color_func = self.color_func
else:
color_func = colormap_color_func(colormap)
self.layout_ = [(word_freq, font_siz... |
'Export to image file.
Parameters
filename : string
Location to write to.
Returns
self'
| def to_file(self, filename):
| img = self.to_image()
img.save(filename)
return self
|
'Convert to numpy array.
Returns
image : nd-array size (width, height, 3)
Word cloud image as numpy matrix.'
| def to_array(self):
| return np.array(self.to_image())
|
'Convert to numpy array.
Returns
image : nd-array size (width, height, 3)
Word cloud image as numpy matrix.'
| def __array__(self):
| return self.to_array()
|
'Generates the list of ips to reverse'
| def get_ip_list(self, ips):
| try:
list = IPy.IP(ips)
except:
print 'Error in IP format, check the input and try again. (Eg. 192.168.1.0/24)'
sys.exit()
name = []
for x in list:
name.append(str(x))
return name
|
'Create an instance of an IP object.
Data can be a network specification or a single IP. IP
Addresses can be specified in all forms understood by
parseAddress.() the size of a network can be specified as
/prefixlen a.b.c.0/24 2001:658:22a:cafe::/64
-lastIP a.b.c.0-a.b.c.255 2001:65... | def __init__(self, data, ipversion=0):
| self.NoPrefixForSingleIp = 1
self.WantPrefixLen = None
netbits = 0
prefixlen = (-1)
if (isinstance(data, types.IntType) or isinstance(data, types.LongType)):
self.ip = long(data)
if (ipversion == 0):
if (self.ip < 4294967296):
ipversion = 4
els... |
'Return the first / base / network addess as an (long) integer.
The same as IP[0].
>>> hex(IP(\'10.0.0.0/8\').int())
\'0xA000000L\''
| def int(self):
| return self.ip
|
'Return the IP version of this Object.
>>> IP(\'10.0.0.0/8\').version()
4
>>> IP(\'::1\').version()
6'
| def version(self):
| return self._ipversion
|
'Returns Network Prefixlen.
>>> IP(\'10.0.0.0/8\').prefixlen()
8'
| def prefixlen(self):
| return self._prefixlen
|
'Return the base (first) address of a network as an (long) integer.'
| def net(self):
| return self.int()
|
'Return the broadcast (last) address of a network as an (long) integer.
The same as IP[-1].'
| def broadcast(self):
| return ((self.int() + self.len()) - 1)
|
'Prints Prefixlen/Netmask.
Not really. In fact it is our universal Netmask/Prefixlen printer.
This is considered an internel function.
want == 0 / None don\'t return anything 1.2.3.0
want == 1 /prefix 1.2.3.0/24
want == 2 /netmask 1.2.3.0/255.255.25... | def _printPrefix(self, want):
| if (((self._ipversion == 4) and (self._prefixlen == 32)) or ((self._ipversion == 6) and (self._prefixlen == 128))):
if self.NoPrefixForSingleIp:
want = 0
if (want is None):
want = self.WantPrefixLen
if (want is None):
want = 1
if want:
if (want == 2):
... |
'Return a string representation as a binary value.
>>> print IP(\'127.0.0.1\').strBin()
01111111000000000000000000000001'
| def strBin(self, wantprefixlen=None):
| if (self._ipversion == 4):
bits = 32
elif (self._ipversion == 6):
bits = 128
else:
raise ValueError('only IPv4 and IPv6 supported')
if ((self.WantPrefixLen is None) and (wantprefixlen is None)):
wantprefixlen = 0
ret = _intToBin(self.ip)
return ((('0' ... |
'Return a string representation in compressed format using \'::\' Notation.
>>> print IP(\'127.0.0.1\').strCompressed()
127.0.0.1
>>> print IP(\'2001:0658:022a:cafe:0200::1\').strCompressed()
2001:658:22a:cafe:200::1'
| def strCompressed(self, wantprefixlen=None):
| if ((self.WantPrefixLen is None) and (wantprefixlen is None)):
wantprefixlen = 1
if (self._ipversion == 4):
return self.strFullsize(wantprefixlen)
else:
hextets = [int(x, 16) for x in self.strFullsize(0).split(':')]
followingzeros = ([0] * 8)
for i in range(len(hextet... |
'Return a string representation in the usual format.
>>> print IP(\'127.0.0.1\').strNormal()
127.0.0.1
>>> print IP(\'2001:0658:022a:cafe:0200::1\').strNormal()
2001:658:22a:cafe:200:0:0:1'
| def strNormal(self, wantprefixlen=None):
| if ((self.WantPrefixLen is None) and (wantprefixlen is None)):
wantprefixlen = 1
if (self._ipversion == 4):
ret = self.strFullsize(0)
elif (self._ipversion == 6):
ret = ':'.join([hex(x)[2:] for x in [int(x, 16) for x in self.strFullsize(0).split(':')]])
else:
raise ValueE... |
'Return a string representation in the non mangled format.
>>> print IP(\'127.0.0.1\').strFullsize()
127.0.0.1
>>> print IP(\'2001:0658:022a:cafe:0200::1\').strFullsize()
2001:0658:022a:cafe:0200:0000:0000:0001'
| def strFullsize(self, wantprefixlen=None):
| if ((self.WantPrefixLen is None) and (wantprefixlen is None)):
wantprefixlen = 1
return (intToIp(self.ip, self._ipversion).lower() + self._printPrefix(wantprefixlen))
|
'Return a string representation in hex format.
>>> print IP(\'127.0.0.1\').strHex()
0x7F000001
>>> print IP(\'2001:0658:022a:cafe:0200::1\').strHex()
0x20010658022ACAFE0200000000000001'
| def strHex(self, wantprefixlen=None):
| if ((self.WantPrefixLen is None) and (wantprefixlen is None)):
wantprefixlen = 0
x = hex(self.ip)
if (x[(-1)] == 'L'):
x = x[:(-1)]
return (x + self._printPrefix(wantprefixlen))
|
'Return a string representation in decimal format.
>>> print IP(\'127.0.0.1\').strDec()
2130706433
>>> print IP(\'2001:0658:022a:cafe:0200::1\').strDec()
42540616829182469433547762482097946625'
| def strDec(self, wantprefixlen=None):
| if ((self.WantPrefixLen is None) and (wantprefixlen is None)):
wantprefixlen = 0
x = str(self.ip)
if (x[(-1)] == 'L'):
x = x[:(-1)]
return (x + self._printPrefix(wantprefixlen))
|
'Return a description of the IP type (\'PRIVATE\', \'RESERVERD\', etc).
>>> print IP(\'127.0.0.1\').iptype()
PRIVATE
>>> print IP(\'192.168.1.1\').iptype()
PRIVATE
>>> print IP(\'195.185.1.2\').iptype()
PUBLIC
>>> print IP(\'::1\').iptype()
LOOPBACK
>>> print IP(\'2001:0658:022a:cafe:0200::1\').iptype()
ASSIGNABLE RIPE... | def iptype(self):
| if (self._ipversion == 4):
iprange = IPv4ranges
elif (self._ipversion == 6):
iprange = IPv6ranges
else:
raise ValueError('only IPv4 and IPv6 supported')
bits = self.strBin()
for i in range(len(bits), 0, (-1)):
if (bits[:i] in iprange):
return i... |
'Return netmask as an integer.
>>> print hex(IP(\'195.185.0.0/16\').netmask().int())
0xFFFF0000L'
| def netmask(self):
| if (self._ipversion == 4):
locallen = (32 - self._prefixlen)
elif (self._ipversion == 6):
locallen = (128 - self._prefixlen)
else:
raise ValueError('only IPv4 and IPv6 supported')
return (((2 ** self._prefixlen) - 1) << locallen)
|
'Return netmask as an string. Mostly useful for IPv6.
>>> print IP(\'195.185.0.0/16\').strNetmask()
255.255.0.0
>>> print IP(\'2001:0658:022a:cafe::0/64\').strNetmask()
/64'
| def strNetmask(self):
| if (self._ipversion == 4):
locallen = (32 - self._prefixlen)
return intToIp((((2 ** self._prefixlen) - 1) << locallen), 4)
elif (self._ipversion == 6):
locallen = (128 - self._prefixlen)
return ('/%d' % self._prefixlen)
else:
raise ValueError('only IPv4 and I... |
'Return the length of an subnet.
>>> print IP(\'195.185.1.0/28\').len()
16
>>> print IP(\'195.185.1.0/24\').len()
256'
| def len(self):
| if (self._ipversion == 4):
locallen = (32 - self._prefixlen)
elif (self._ipversion == 6):
locallen = (128 - self._prefixlen)
else:
raise ValueError('only IPv4 and IPv6 supported')
return (2 ** locallen)
|
'Return the length of an subnet.
Called to implement the built-in function len().
It breaks with IPv6 Networks. Anybody knows how to fix this.'
| def __len__(self):
| return int(self.len())
|
'Called to implement evaluation of self[key].
>>> ip=IP(\'127.0.0.0/30\')
>>> for x in ip:
... print hex(x.int())
0x7F000000L
0x7F000001L
0x7F000002L
0x7F000003L
>>> hex(ip[2].int())
\'0x7F000002L\'
>>> hex(ip[-1].int())
\'0x7F000003L\''
| def __getitem__(self, key):
| if ((not isinstance(key, types.IntType)) and (not isinstance(key, types.LongType))):
raise TypeError
if (abs(key) >= self.len()):
raise IndexError
if (key < 0):
key = (self.len() - abs(key))
return (self.ip + long(key))
|
'Called to implement membership test operators.
Should return true if item is in self, false otherwise. Item
can be other IP-objects, strings or ints.
>>> print IP(\'195.185.1.1\').strHex()
0xC3B90101
>>> 0xC3B90101L in IP(\'195.185.1.0/24\')
1
>>> \'127.0.0.1\' in IP(\'127.0.0.0/24\')
1
>>> IP(\'127.0.0.0/24\') in IP(... | def __contains__(self, item):
| item = IP(item)
if ((item.ip >= self.ip) and (item.ip < (((self.ip + self.len()) - item.len()) + 1))):
return 1
else:
return 0
|
'Check if two IP address ranges overlap.
Returns 0 if the two ranged don\'t overlap, 1 if the given
range overlaps at the end and -1 if it does at the beginning.
>>> IP(\'192.168.0.0/23\').overlaps(\'192.168.1.0/24\')
1
>>> IP(\'192.168.0.0/23\').overlaps(\'192.168.1.255\')
1
>>> IP(\'192.168.0.0/23\').overlaps(\'192.1... | def overlaps(self, item):
| item = IP(item)
if ((item.ip >= self.ip) and (item.ip < (self.ip + self.len()))):
return 1
elif ((self.ip >= item.ip) and (self.ip < (item.ip + item.len()))):
return (-1)
else:
return 0
|
'Dispatch to the prefered String Representation.
Used to implement str(IP).'
| def __str__(self):
| return self.strFullsize()
|
'Print a representation of the Object.
Used to implement repr(IP). Returns a string which evaluates
to an identical Object (without the wnatprefixlen stuff - see
module docstring.
>>> print repr(IP(\'10.0.0.0/24\'))
IP(\'10.0.0.0/24\')'
| def __repr__(self):
| return ("IPint('%s')" % self.strCompressed(1))
|
'Called by comparison operations.
Should return a negative integer if self < other, zero if self
== other, a positive integer if self > other.
Networks with different prefixlen are considered non-equal.
Networks with the same prefixlen and differing addresses are
considered non equal but are compared by thair base addr... | def __cmp__(self, other):
| if (self._prefixlen < other.prefixlen()):
return (other.prefixlen() - self._prefixlen)
elif (self._prefixlen > other.prefixlen()):
return ((self._prefixlen - other.prefixlen()) * (-1))
elif (self.ip < other.ip):
return (-1)
elif (self.ip > other.ip):
return 1
else:
... |
'Called for the key object for dictionary operations, and by
the built-in function hash() Should return a 32-bit integer
usable as a hash value for dictionary operations. The only
required property is that objects which compare equal have the
same hash value
>>> hex(IP(\'10.0.0.0/24\').__hash__())
\'0xf5ffffe7\''
| def __hash__(self):
| thehash = int((-1))
ip = self.ip
while (ip > 0):
thehash = (thehash ^ (ip & 2147483647))
ip = (ip >> 32)
thehash = (thehash ^ self._prefixlen)
return int(thehash)
|
'Return the base (first) address of a network as an IP object.
The same as IP[0].
>>> IP(\'10.0.0.0/8\').net()
IP(\'10.0.0.0\')'
| def net(self):
| return IP(IPint.net(self))
|
'Return the broadcast (last) address of a network as an IP object.
The same as IP[-1].
>>> IP(\'10.0.0.0/8\').broadcast()
IP(\'10.255.255.255\')'
| def broadcast(self):
| return IP(IPint.broadcast(self))
|
'Return netmask as an IP object.
>>> IP(\'10.0.0.0/8\').netmask()
IP(\'255.0.0.0\')'
| def netmask(self):
| return IP(IPint.netmask(self))
|
'Return a list with values forming the reverse lookup.
>>> IP(\'213.221.113.87/32\').reverseNames()
[\'87.113.221.213.in-addr.arpa.\']
>>> IP(\'213.221.112.224/30\').reverseNames()
[\'224.112.221.213.in-addr.arpa.\', \'225.112.221.213.in-addr.arpa.\', \'226.112.221.213.in-addr.arpa.\', \'227.112.221.213.in-addr.arpa.\'... | def reverseNames(self):
| if (self._ipversion == 4):
ret = []
if (self.len() < (2 ** 8)):
for x in self:
ret.append(x.reverseName())
elif (self.len() < (2 ** 16)):
for i in range(0, self.len(), (2 ** 8)):
ret.append(self[i].reverseName()[2:])
elif (self.... |
'Return the value for reverse lookup/PTR records as RfC 2317 look alike.
RfC 2317 is an ugly hack which only works for sub-/24 e.g. not
for /23. Do not use it. Better set up a Zone for every
address. See reverseName for a way to arcive that.
>>> print IP(\'195.185.1.1\').reverseName()
1.1.185.195.in-addr.arpa.
>>> prin... | def reverseName(self):
| if (self._ipversion == 4):
s = self.strFullsize(0)
s = s.split('.')
s.reverse()
first_byte_index = int((4 - (self._prefixlen / 8)))
if ((self._prefixlen % 8) != 0):
nibblepart = ('%s-%s' % (s[(3 - (self._prefixlen / 8))], intToIp(((self.ip + self.len()) - 1), 4).s... |
'Called to implement evaluation of self[key].
>>> ip=IP(\'127.0.0.0/30\')
>>> for x in ip:
... print str(x)
127.0.0.0
127.0.0.1
127.0.0.2
127.0.0.3
>>> print str(ip[2])
127.0.0.2
>>> print str(ip[-1])
127.0.0.3'
| def __getitem__(self, key):
| return IP(IPint.__getitem__(self, key))
|
'Print a representation of the Object.
>>> IP(\'10.0.0.0/8\')
IP(\'10.0.0.0/8\')'
| def __repr__(self):
| return ("IP('%s')" % self.strCompressed(1))
|
'Emulate numeric objects through network aggregation'
| def __add__(self, other):
| if (self.prefixlen() != other.prefixlen()):
raise ValueError('Only networks with the same prefixlen can be added.')
if (self.prefixlen < 1):
raise ValueError("Networks with a prefixlen longer than /1 can't be added.")
if (self.version() != o... |
'_Service._Proto.Name TTL Class SRV Priority Weight Port Target'
| def getSRVdata(self):
| priority = self.get16bit()
weight = self.get16bit()
port = self.get16bit()
target = self.getname()
return (priority, weight, port, target)
|
'needs a refactoring'
| def req(self, *name, **args):
| import time
import Lib
self.argparse(name, args)
protocol = self.args['protocol']
self.port = self.args['port']
opcode = self.args['opcode']
rd = self.args['rd']
server = self.args['server']
if isinstance(self.args['qtype'], types.StringType):
try:
qtype = getattr... |
'refactor me'
| def sendUDPRequest(self, server):
| self.response = None
self.socketInit(socket.AF_INET, socket.SOCK_DGRAM)
for self.ns in server:
try:
self.conn()
self.time_start = time.time()
if (not self.async):
self.s.send(self.request)
self.response = self.processUDPReply()
... |
'do the work of sending a TCP request'
| def sendTCPRequest(self, server):
| import time
import Lib
self.response = None
for self.ns in server:
try:
self.socketInit(socket.AF_INET, socket.SOCK_STREAM)
self.time_start = time.time()
self.conn()
self.s.send((Lib.pack16bit(len(self.request)) + self.request))
self.s.... |
'Generates the list of ips to reverse'
| def get_ip_list(self, ips):
| try:
list = IPy.IP(ips)
except:
print 'Error in IP format, check the input and try again. (Eg. 192.168.1.0/24)'
sys.exit()
name = []
for x in list:
name.append(str(x))
return name
|
'Search the Dataloss DB archive.
Arguments:
name -- Name of the affected company/ organisation
arrest -- whether the incident resulted in an arrest
breaches -- the type of breach that occurred (Hack, MissingLaptop etc.)
country -- country where the incident took place
ext -- whether... | def search(self, **kwargs):
| return self.parent._request('datalossdb/search', dict(**kwargs))
|
'Search the entire Shodan Exploits archive using the same query syntax
as the website.
Arguments:
query -- exploit search query; same syntax as website
Optional arguments:
sources -- metasploit, cve, osvdb, exploitdb, or packetstorm
cve -- CVE identifier (ex. 2010-0432)
osvdb -- OSVDB identifier (ex. 11666)... | def search(self, query, sources=[], cve=None, osvdb=None, msb=None, bid=None):
| if sources:
query += (' source:' + ','.join(sources))
if cve:
query += (' cve:%s' % str(cve).strip())
if osvdb:
query += (' osvdb:%s' % str(osvdb).strip())
if msb:
query += (' msb:%s' % str(msb).strip())
if bid:
query += (' bid:%s' % str(bid).st... |
'Download the exploit code from the ExploitDB archive.
Arguments:
id -- ID of the ExploitDB entry
Returns:
A dictionary with the following fields:
filename -- Name of the file
content-type -- Mimetype
data -- Contents of the file'
| def download(self, id):
| return self.parent._request('exploitdb/download', {'id': id})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.