_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q263700 | scanAllProcessesForCwd | validation | def scanAllProcessesForCwd(searchPortion, isExactMatch=False):
'''
scanAllProcessesForCwd - Scans all processes on the system for a given search pattern.
@param searchPortion <str> - Any portion of directory to search
@param isExactMatch <bool> Default False - If match should be exa... | python | {
"resource": ""
} |
q263701 | scanProcessForMapping | validation | def scanProcessForMapping(pid, searchPortion, isExactMatch=False, ignoreCase=False):
'''
scanProcessForMapping - Searches a given pid's mappings for a certain pattern.
@param pid <int> - A running process ID on this system
@param searchPortion <str> - A mapping for which to search, ... | python | {
"resource": ""
} |
q263702 | scanAllProcessesForMapping | validation | def scanAllProcessesForMapping(searchPortion, isExactMatch=False, ignoreCase=False):
'''
scanAllProcessesForMapping - Scans all processes on the system for a given search pattern.
@param searchPortion <str> - A mapping for which to search, example: libc or python or libz.so.1. Give empty string... | python | {
"resource": ""
} |
q263703 | scanProcessForOpenFile | validation | def scanProcessForOpenFile(pid, searchPortion, isExactMatch=True, ignoreCase=False):
'''
scanProcessForOpenFile - Scans open FDs for a given pid to see if any are the provided searchPortion
@param searchPortion <str> - Filename to check
@param isExactMatch <bool> Default True - If m... | python | {
"resource": ""
} |
q263704 | scanAllProcessesForOpenFile | validation | def scanAllProcessesForOpenFile(searchPortion, isExactMatch=True, ignoreCase=False):
'''
scanAllProcessessForOpenFile - Scans all processes on the system for a given filename
@param searchPortion <str> - Filename to check
@param isExactMatch <bool> Default True - If match should be ... | python | {
"resource": ""
} |
q263705 | Hub.connect | validation | def connect(self):
"""Create and connect to socket for TCP communication with hub."""
try:
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.settimeout(TIMEOUT_SECONDS)
self._socket.connect((self._ip, self._port))
_LOGGER.debug(... | python | {
"resource": ""
} |
q263706 | Hub.send_command | validation | def send_command(self, command):
"""Send TCP command to hub and return response."""
# use lock to make TCP send/receive thread safe
with self._lock:
try:
self._socket.send(command.encode("utf8"))
result = self.receive()
# hub may send "... | python | {
"resource": ""
} |
q263707 | Hub.receive | validation | def receive(self):
"""Receive TCP response, looping to get whole thing or timeout."""
try:
buffer = self._socket.recv(BUFFER_SIZE)
except socket.timeout as error:
# Something is wrong, assume it's offline temporarily
_LOGGER.error("Error receiving: %s", error)... | python | {
"resource": ""
} |
q263708 | Hub.get_data | validation | def get_data(self):
"""Get current light data as dictionary with light zids as keys."""
response = self.send_command(GET_LIGHTS_COMMAND)
_LOGGER.debug("get_data response: %s", repr(response))
if not response:
_LOGGER.debug("Empty response: %s", response)
return {}... | python | {
"resource": ""
} |
q263709 | Hub.get_lights | validation | def get_lights(self):
"""Get current light data, set and return as list of Bulb objects."""
# Throttle updates. Use cached data if within UPDATE_INTERVAL_SECONDS
now = datetime.datetime.now()
if (now - self._last_updated) < datetime.timedelta(
seconds=UPDATE_INTERVAL_SECO... | python | {
"resource": ""
} |
q263710 | Bulb.set_brightness | validation | def set_brightness(self, brightness):
"""Set brightness of bulb."""
command = "C {},,,,{},\r\n".format(self._zid, brightness)
response = self._hub.send_command(command)
_LOGGER.debug("Set brightness %s: %s", repr(command), response)
return response | python | {
"resource": ""
} |
q263711 | Bulb.set_all | validation | def set_all(self, red, green, blue, brightness):
"""Set color and brightness of bulb."""
command = "C {},{},{},{},{},\r\n".format(self._zid, red, green, blue,
brightness)
response = self._hub.send_command(command)
_LOGGER.debug("Set all %s... | python | {
"resource": ""
} |
q263712 | Bulb.update | validation | def update(self):
"""Update light objects to their current values."""
bulbs = self._hub.get_lights()
if not bulbs:
_LOGGER.debug("%s is offline, send command failed", self._zid)
self._online = False | python | {
"resource": ""
} |
q263713 | retrieve_document | validation | def retrieve_document(file_path, directory='sec_filings'):
'''
This function takes a file path beginning with edgar and stores the form in a directory.
The default directory is sec_filings but can be changed through a keyword argument.
'''
ftp = FTP('ftp.sec.gov', timeout=None)
ftp.login... | python | {
"resource": ""
} |
q263714 | readtxt | validation | def readtxt(filepath):
""" read file as is"""
with open(filepath, 'rt') as f:
lines = f.readlines()
return ''.join(lines) | python | {
"resource": ""
} |
q263715 | _clean_up | validation | def _clean_up(paths):
"""
Clean up after ourselves, removing created files.
@param {[String]} A list of file paths specifying the files we've created
during run. Will all be deleted.
@return {None}
"""
print('Cleaning up')
# Iterate over the given paths, unlinking them
for path i... | python | {
"resource": ""
} |
q263716 | _create_index_file | validation | def _create_index_file(
root_dir, location, image_files, dirs, force_no_processing=False):
"""
Create an index file in the given location, supplying known lists of
present image files and subdirectories.
@param {String} root_dir - The root directory of the entire crawl. Used to
ascertain... | python | {
"resource": ""
} |
q263717 | _create_index_files | validation | def _create_index_files(root_dir, force_no_processing=False):
"""
Crawl the root directory downwards, generating an index HTML file in each
directory on the way down.
@param {String} root_dir - The top level directory to crawl down from. In
normal usage, this will be '.'.
@param {Boolean=Fal... | python | {
"resource": ""
} |
q263718 | _get_image_from_file | validation | def _get_image_from_file(dir_path, image_file):
"""
Get an instance of PIL.Image from the given file.
@param {String} dir_path - The directory containing the image file
@param {String} image_file - The filename of the image file within dir_path
@return {PIL.Image} An instance of the image file as a ... | python | {
"resource": ""
} |
q263719 | _get_src_from_image | validation | def _get_src_from_image(img, fallback_image_file):
"""
Get base-64 encoded data as a string for the given image. Fallback to return
fallback_image_file if cannot get the image data or img is None.
@param {Image} img - The PIL Image to get src data for
@param {String} fallback_image_file - The filena... | python | {
"resource": ""
} |
q263720 | _get_thumbnail_image_from_file | validation | def _get_thumbnail_image_from_file(dir_path, image_file):
"""
Get a PIL.Image from the given image file which has been scaled down to
THUMBNAIL_WIDTH wide.
@param {String} dir_path - The directory containing the image file
@param {String} image_file - The filename of the image file within dir_path
... | python | {
"resource": ""
} |
q263721 | _run_server | validation | def _run_server():
"""
Run the image server. This is blocking. Will handle user KeyboardInterrupt
and other exceptions appropriately and return control once the server is
stopped.
@return {None}
"""
# Get the port to run on
port = _get_server_port()
# Configure allow_reuse_address to... | python | {
"resource": ""
} |
q263722 | serve_dir | validation | def serve_dir(dir_path):
"""
Generate indexes and run server from the given directory downwards.
@param {String} dir_path - The directory path (absolute, or relative to CWD)
@return {None}
"""
# Create index files, and store the list of their paths for cleanup later
# This time, force no pro... | python | {
"resource": ""
} |
q263723 | static | validation | def static(**kwargs):
""" USE carefully ^^ """
def wrap(fn):
fn.func_globals['static'] = fn
fn.__dict__.update(kwargs)
return fn
return wrap | python | {
"resource": ""
} |
q263724 | rand_blend_mask | validation | def rand_blend_mask(shape, rand=rand.uniform(-10, 10), **kwargs):
""" random blending masks """
# batch, channel = shape[0], shape[3]
z = rand(shape[0]) # seed
noise = snoise2dz((shape[1], shape[2]), z, **kwargs)
return noise | python | {
"resource": ""
} |
q263725 | snoise2d | validation | def snoise2d(size, z=0.0, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0):
"""
z value as like a seed
"""
import noise
data = np.empty(size, dtype='float32')
for y in range(size[0]):
for x in range(size[1]):
v = noise.snoise3(x * scale, y * scale, z,
... | python | {
"resource": ""
} |
q263726 | to_permutation_matrix | validation | def to_permutation_matrix(matches):
"""Converts a permutation into a permutation matrix.
`matches` is a dictionary whose keys are vertices and whose values are
partners. For each vertex ``u`` and ``v``, entry (``u``, ``v``) in the
returned matrix will be a ``1`` if and only if ``matches[u] == v``.
... | python | {
"resource": ""
} |
q263727 | four_blocks | validation | def four_blocks(topleft, topright, bottomleft, bottomright):
"""Convenience function that creates a block matrix with the specified
blocks.
Each argument must be a NumPy matrix. The two top matrices must have the
same number of rows, as must the two bottom matrices. The two left matrices
must have ... | python | {
"resource": ""
} |
q263728 | to_bipartite_matrix | validation | def to_bipartite_matrix(A):
"""Returns the adjacency matrix of a bipartite graph whose biadjacency
matrix is `A`.
`A` must be a NumPy array.
If `A` has **m** rows and **n** columns, then the returned matrix has **m +
n** rows and columns.
"""
m, n = A.shape
return four_blocks(zeros(m,... | python | {
"resource": ""
} |
q263729 | to_pattern_matrix | validation | def to_pattern_matrix(D):
"""Returns the Boolean matrix in the same shape as `D` with ones exactly
where there are nonzero entries in `D`.
`D` must be a NumPy array.
"""
result = np.zeros_like(D)
# This is a cleverer way of doing
#
# for (u, v) in zip(*(D.nonzero())):
# ... | python | {
"resource": ""
} |
q263730 | bump_version | validation | def bump_version(version, which=None):
"""Returns the result of incrementing `version`.
If `which` is not specified, the "patch" part of the version number will be
incremented. If `which` is specified, it must be ``'major'``, ``'minor'``,
or ``'patch'``. If it is one of these three strings, the corres... | python | {
"resource": ""
} |
q263731 | get_version | validation | def get_version(filename, pattern):
"""Gets the current version from the specified file.
This function assumes the file includes a string of the form::
<pattern> = <version>
"""
with open(filename) as f:
match = re.search(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern, f.read())
if ma... | python | {
"resource": ""
} |
q263732 | fail | validation | def fail(message=None, exit_status=None):
"""Prints the specified message and exits the program with the specified
exit status.
"""
print('Error:', message, file=sys.stderr)
sys.exit(exit_status or 1) | python | {
"resource": ""
} |
q263733 | git_tag | validation | def git_tag(tag):
"""Tags the current version."""
print('Tagging "{}"'.format(tag))
msg = '"Released version {}"'.format(tag)
Popen(['git', 'tag', '-s', '-m', msg, tag]).wait() | python | {
"resource": ""
} |
q263734 | Renderer.initialize | validation | def initialize(self, templates_path, global_data):
"""initialize with templates' path
parameters
templates_path str the position of templates directory
global_data dict globa data can be got in any templates"""
self.env = Environment(loader=FileSystemLoader(temp... | python | {
"resource": ""
} |
q263735 | Renderer.render | validation | def render(self, template, **data):
"""Render data with template, return html unicodes.
parameters
template str the template's filename
data dict the data to render
"""
# make a copy and update the copy
dct = self.global_data.copy()
dct.update... | python | {
"resource": ""
} |
q263736 | Renderer.render_to | validation | def render_to(self, path, template, **data):
"""Render data with template and then write to path"""
html = self.render(template, **data)
with open(path, 'w') as f:
f.write(html.encode(charset)) | python | {
"resource": ""
} |
q263737 | render | validation | def render(template, **data):
"""shortcut to render data with `template`. Just add exception
catch to `renderer.render`"""
try:
return renderer.render(template, **data)
except JinjaTemplateNotFound as e:
logger.error(e.__doc__ + ', Template: %r' % template)
sys.exit(e.exit_code) | python | {
"resource": ""
} |
q263738 | GenericDataFrameAPIView.get_dataframe | validation | def get_dataframe(self):
"""
Get the DataFrame for this view.
Defaults to using `self.dataframe`.
This method should always be used rather than accessing `self.dataframe`
directly, as `self.dataframe` gets evaluated only once, and those results
are cached for all subsequ... | python | {
"resource": ""
} |
q263739 | GenericDataFrameAPIView.index_row | validation | def index_row(self, dataframe):
"""
Indexes the row based on the request parameters.
"""
return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame().T | python | {
"resource": ""
} |
q263740 | GenericDataFrameAPIView.get_object | validation | def get_object(self):
"""
Returns the row the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if objects are referenced using multiple
keyword arguments in the url conf.
"""
dataframe = self.filter_dataf... | python | {
"resource": ""
} |
q263741 | GenericDataFrameAPIView.paginator | validation | def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
self._paginator = self.pagination_class()
... | python | {
"resource": ""
} |
q263742 | GenericDataFrameAPIView.paginate_dataframe | validation | def paginate_dataframe(self, dataframe):
"""
Return a single page of results, or `None` if pagination is disabled.
"""
if self.paginator is None:
return None
return self.paginator.paginate_dataframe(dataframe, self.request, view=self) | python | {
"resource": ""
} |
q263743 | Config.parse | validation | def parse(self):
"""parse config, return a dict"""
if exists(self.filepath):
content = open(self.filepath).read().decode(charset)
else:
content = ""
try:
config = toml.loads(content)
except toml.TomlSyntaxError:
raise ConfigSyntax... | python | {
"resource": ""
} |
q263744 | render_to | validation | def render_to(path, template, **data):
"""shortcut to render data with `template` and then write to `path`.
Just add exception catch to `renderer.render_to`"""
try:
renderer.render_to(path, template, **data)
except JinjaTemplateNotFound as e:
logger.error(e.__doc__ + ', Template: %r' % t... | python | {
"resource": ""
} |
q263745 | Parser.parse | validation | def parse(self, source):
"""Parse ascii post source, return dict"""
rt, title, title_pic, markdown = libparser.parse(source)
if rt == -1:
raise SeparatorNotFound
elif rt == -2:
raise PostTitleNotFound
# change to unicode
title, title_pic, markdo... | python | {
"resource": ""
} |
q263746 | Parser.parse_filename | validation | def parse_filename(self, filepath):
"""parse post source files name to datetime object"""
name = os.path.basename(filepath)[:-src_ext_len]
try:
dt = datetime.strptime(name, "%Y-%m-%d-%H-%M")
except ValueError:
raise PostNameInvalid
return {'name': name, 'd... | python | {
"resource": ""
} |
q263747 | Server.run_server | validation | def run_server(self, port):
"""run a server binding to port"""
try:
self.server = MultiThreadedHTTPServer(('0.0.0.0', port), Handler)
except socket.error, e: # failed to bind port
logger.error(str(e))
sys.exit(1)
logger.info("HTTP serve at http://0.... | python | {
"resource": ""
} |
q263748 | Server.get_files_stat | validation | def get_files_stat(self):
"""get source files' update time"""
if not exists(Post.src_dir):
logger.error(SourceDirectoryNotFound.__doc__)
sys.exit(SourceDirectoryNotFound.exit_code)
paths = []
for fn in ls(Post.src_dir):
if fn.endswith(src_ext):
... | python | {
"resource": ""
} |
q263749 | Server.watch_files | validation | def watch_files(self):
"""watch files for changes, if changed, rebuild blog. this thread
will quit if the main process ends"""
try:
while 1:
sleep(1) # check every 1s
try:
files_stat = self.get_files_stat()
except... | python | {
"resource": ""
} |
q263750 | deploy_blog | validation | def deploy_blog():
"""Deploy new blog to current directory"""
logger.info(deploy_blog.__doc__)
# `rsync -aqu path/to/res/* .`
call(
'rsync -aqu ' + join(dirname(__file__), 'res', '*') + ' .',
shell=True)
logger.success('Done')
logger.info('Please edit config.toml to meet your nee... | python | {
"resource": ""
} |
q263751 | using | validation | def using(context, alias):
'''
Temporarily update the context to use the BlockContext for the given alias.
'''
# An empty alias means look in the current widget set.
if alias == '':
yield context
else:
try:
widgets = context.render_context[WIDGET_CONTEXT_KEY]
... | python | {
"resource": ""
} |
q263752 | find_block | validation | def find_block(context, *names):
'''
Find the first matching block in the current block_context
'''
block_set = context.render_context[BLOCK_CONTEXT_KEY]
for name in names:
block = block_set.get_block(name)
if block is not None:
return block
raise template.TemplateSy... | python | {
"resource": ""
} |
q263753 | load_widgets | validation | def load_widgets(context, **kwargs):
'''
Load a series of widget libraries.
'''
_soft = kwargs.pop('_soft', False)
try:
widgets = context.render_context[WIDGET_CONTEXT_KEY]
except KeyError:
widgets = context.render_context[WIDGET_CONTEXT_KEY] = {}
for alias, template_name i... | python | {
"resource": ""
} |
q263754 | auto_widget | validation | def auto_widget(field):
'''Return a list of widget names for the provided field.'''
# Auto-detect
info = {
'widget': field.field.widget.__class__.__name__,
'field': field.field.__class__.__name__,
'name': field.name,
}
return [
fmt.format(**info)
for fmt in (... | python | {
"resource": ""
} |
q263755 | reuse | validation | def reuse(context, block_list, **kwargs):
'''
Allow reuse of a block within a template.
{% reuse '_myblock' foo=bar %}
If passed a list of block names, will use the first that matches:
{% reuse list_of_block_names .... %}
'''
try:
block_context = context.render_context[BLOCK_CONTE... | python | {
"resource": ""
} |
q263756 | ChoiceWrapper.display | validation | def display(self):
"""
When dealing with optgroups, ensure that the value is properly force_text'd.
"""
if not self.is_group():
return self._display
return ((force_text(k), v) for k, v in self._display) | python | {
"resource": ""
} |
q263757 | RedisBackend.create_message | validation | def create_message(self, level, msg_text, extra_tags='', date=None, url=None):
"""
Message instances are namedtuples of type `Message`.
The date field is already serialized in datetime.isoformat ECMA-262 format
"""
if not date:
now = timezone.now()
else:
... | python | {
"resource": ""
} |
q263758 | add_message_for | validation | def add_message_for(users, level, message_text, extra_tags='', date=None, url=None, fail_silently=False):
"""
Send a message to a list of users without passing through `django.contrib.messages`
:param users: an iterable containing the recipients of the messages
:param level: message level
:param me... | python | {
"resource": ""
} |
q263759 | broadcast_message | validation | def broadcast_message(level, message_text, extra_tags='', date=None, url=None, fail_silently=False):
"""
Send a message to all users aka broadcast.
:param level: message level
:param message_text: the string containing the message
:param extra_tags: like the Django api, a string containing extra ta... | python | {
"resource": ""
} |
q263760 | mark_read | validation | def mark_read(user, message):
"""
Mark message instance as read for user.
Returns True if the message was `unread` and thus actually marked as `read` or False in case
it is already `read` or it does not exist at all.
:param user: user instance for the recipient
:param message: a Message instanc... | python | {
"resource": ""
} |
q263761 | mark_all_read | validation | def mark_all_read(user):
"""
Mark all message instances for a user as read.
:param user: user instance for the recipient
"""
BackendClass = stored_messages_settings.STORAGE_BACKEND
backend = BackendClass()
backend.inbox_purge(user) | python | {
"resource": ""
} |
q263762 | stored_messages_archive | validation | def stored_messages_archive(context, num_elements=10):
"""
Renders a list of archived messages for the current user
"""
if "user" in context:
user = context["user"]
if user.is_authenticated():
qs = MessageArchive.objects.select_related("message").filter(user=user)
... | python | {
"resource": ""
} |
q263763 | StorageMixin._get | validation | def _get(self, *args, **kwargs):
"""
Retrieve unread messages for current user, both from the inbox and
from other storages
"""
messages, all_retrieved = super(StorageMixin, self)._get(*args, **kwargs)
if self.user.is_authenticated():
inbox_messages = self.bac... | python | {
"resource": ""
} |
q263764 | StorageMixin.add | validation | def add(self, level, message, extra_tags=''):
"""
If the message level was configured for being stored and request.user
is not anonymous, save it to the database. Otherwise, let some other
class handle the message.
Notice: controls like checking the message is not empty and the ... | python | {
"resource": ""
} |
q263765 | StorageMixin._store | validation | def _store(self, messages, response, *args, **kwargs):
"""
persistent messages are already in the database inside the 'archive',
so we can say they're already "stored".
Here we put them in the inbox, or remove from the inbox in case the
messages were iterated.
messages c... | python | {
"resource": ""
} |
q263766 | StorageMixin._prepare_messages | validation | def _prepare_messages(self, messages):
"""
Like the base class method, prepares a list of messages for storage
but avoid to do this for `models.Message` instances.
"""
for message in messages:
if not self.backend.can_handle(message):
message._prepare() | python | {
"resource": ""
} |
q263767 | jocker | validation | def jocker(test_options=None):
"""Main entry point for script."""
version = ver_check()
options = test_options or docopt(__doc__, version=version)
_set_global_verbosity_level(options.get('--verbose'))
jocker_lgr.debug(options)
jocker_run(options) | python | {
"resource": ""
} |
q263768 | init | validation | def init(base_level=DEFAULT_BASE_LOGGING_LEVEL,
verbose_level=DEFAULT_VERBOSE_LOGGING_LEVEL,
logging_config=None):
"""initializes a base logger
you can use this to init a logger in any of your files.
this will use config.py's LOGGER param and logging.dictConfig to configure
the logger... | python | {
"resource": ""
} |
q263769 | BaseConfigurator.configure_custom | validation | def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and \
hasattr(types, 'ClassType') and isinstance(c, types.ClassType):
c = self.resolve(c)
props = config.pop('.', Non... | python | {
"resource": ""
} |
q263770 | _set_global_verbosity_level | validation | def _set_global_verbosity_level(is_verbose_output=False):
"""sets the global verbosity level for console and the jocker_lgr logger.
:param bool is_verbose_output: should be output be verbose
"""
global verbose_output
# TODO: (IMPRV) only raise exceptions in verbose mode
verbose_output = is_verb... | python | {
"resource": ""
} |
q263771 | _import_config | validation | def _import_config(config_file):
"""returns a configuration object
:param string config_file: path to config file
"""
# get config file path
jocker_lgr.debug('config file is: {0}'.format(config_file))
# append to path for importing
try:
jocker_lgr.debug('importing config...')
... | python | {
"resource": ""
} |
q263772 | execute | validation | def execute(varsfile, templatefile, outputfile=None, configfile=None,
dryrun=False, build=False, push=False, verbose=False):
"""generates a Dockerfile, builds an image and pushes it to DockerHub
A `Dockerfile` will be generated by Jinja2 according to the `varsfile`
imported. If build is true, a... | python | {
"resource": ""
} |
q263773 | Jocker._parse_dumb_push_output | validation | def _parse_dumb_push_output(self, string):
"""since the push process outputs a single unicode string consisting of
multiple JSON formatted "status" lines, we need to parse it so that it
can be read as multiple strings.
This will receive the string as an input, count curly braces and ign... | python | {
"resource": ""
} |
q263774 | upload_gif | validation | def upload_gif(gif):
"""Uploads an image file to Imgur"""
client_id = os.environ.get('IMGUR_API_ID')
client_secret = os.environ.get('IMGUR_API_SECRET')
if client_id is None or client_secret is None:
click.echo('Cannot upload - could not find IMGUR_API_ID or IMGUR_API_SECRET environment variabl... | python | {
"resource": ""
} |
q263775 | is_dot | validation | def is_dot(ip):
"""Return true if the IP address is in dotted decimal notation."""
octets = str(ip).split('.')
if len(octets) != 4:
return False
for i in octets:
try:
val = int(i)
except ValueError:
return False
if val > 255 or val < 0:
... | python | {
"resource": ""
} |
q263776 | is_bin | validation | def is_bin(ip):
"""Return true if the IP address is in binary notation."""
try:
ip = str(ip)
if len(ip) != 32:
return False
dec = int(ip, 2)
except (TypeError, ValueError):
return False
if dec > 4294967295 or dec < 0:
return False
return True | python | {
"resource": ""
} |
q263777 | is_oct | validation | def is_oct(ip):
"""Return true if the IP address is in octal notation."""
try:
dec = int(str(ip), 8)
except (TypeError, ValueError):
return False
if dec > 0o37777777777 or dec < 0:
return False
return True | python | {
"resource": ""
} |
q263778 | is_dec | validation | def is_dec(ip):
"""Return true if the IP address is in decimal notation."""
try:
dec = int(str(ip))
except ValueError:
return False
if dec > 4294967295 or dec < 0:
return False
return True | python | {
"resource": ""
} |
q263779 | _check_nm | validation | def _check_nm(nm, notation):
"""Function internally used to check if the given netmask
is of the specified notation."""
# Convert to decimal, and check if it's in the list of valid netmasks.
_NM_CHECK_FUNCT = {
NM_DOT: _dot_to_dec,
NM_HEX: _hex_to_dec,
NM_BIN: _bin_to_dec,
... | python | {
"resource": ""
} |
q263780 | is_bits_nm | validation | def is_bits_nm(nm):
"""Return true if the netmask is in bits notatation."""
try:
bits = int(str(nm))
except ValueError:
return False
if bits > 32 or bits < 0:
return False
return True | python | {
"resource": ""
} |
q263781 | is_wildcard_nm | validation | def is_wildcard_nm(nm):
"""Return true if the netmask is in wildcard bits notatation."""
try:
dec = 0xFFFFFFFF - _dot_to_dec(nm, check=True)
except ValueError:
return False
if dec in _NETMASKS_VALUES:
return True
return False | python | {
"resource": ""
} |
q263782 | _dot_to_dec | validation | def _dot_to_dec(ip, check=True):
"""Dotted decimal notation to decimal conversion."""
if check and not is_dot(ip):
raise ValueError('_dot_to_dec: invalid IP: "%s"' % ip)
octets = str(ip).split('.')
dec = 0
dec |= int(octets[0]) << 24
dec |= int(octets[1]) << 16
dec |= int(octets[2]) ... | python | {
"resource": ""
} |
q263783 | _dec_to_dot | validation | def _dec_to_dot(ip):
"""Decimal to dotted decimal notation conversion."""
first = int((ip >> 24) & 255)
second = int((ip >> 16) & 255)
third = int((ip >> 8) & 255)
fourth = int(ip & 255)
return '%d.%d.%d.%d' % (first, second, third, fourth) | python | {
"resource": ""
} |
q263784 | _hex_to_dec | validation | def _hex_to_dec(ip, check=True):
"""Hexadecimal to decimal conversion."""
if check and not is_hex(ip):
raise ValueError('_hex_to_dec: invalid IP: "%s"' % ip)
if isinstance(ip, int):
ip = hex(ip)
return int(str(ip), 16) | python | {
"resource": ""
} |
q263785 | _oct_to_dec | validation | def _oct_to_dec(ip, check=True):
"""Octal to decimal conversion."""
if check and not is_oct(ip):
raise ValueError('_oct_to_dec: invalid IP: "%s"' % ip)
if isinstance(ip, int):
ip = oct(ip)
return int(str(ip), 8) | python | {
"resource": ""
} |
q263786 | _bin_to_dec | validation | def _bin_to_dec(ip, check=True):
"""Binary to decimal conversion."""
if check and not is_bin(ip):
raise ValueError('_bin_to_dec: invalid IP: "%s"' % ip)
if isinstance(ip, int):
ip = str(ip)
return int(str(ip), 2) | python | {
"resource": ""
} |
q263787 | _BYTES_TO_BITS | validation | def _BYTES_TO_BITS():
"""Generate a table to convert a whole byte to binary.
This code was taken from the Python Cookbook, 2nd edition - O'Reilly."""
the_table = 256*[None]
bits_per_byte = list(range(7, -1, -1))
for n in range(256):
l = n
bits = 8*[None]
for i in bits_per_byt... | python | {
"resource": ""
} |
q263788 | _dec_to_bin | validation | def _dec_to_bin(ip):
"""Decimal to binary conversion."""
bits = []
while ip:
bits.append(_BYTES_TO_BITS[ip & 255])
ip >>= 8
bits.reverse()
return ''.join(bits) or 32*'0' | python | {
"resource": ""
} |
q263789 | _bits_to_dec | validation | def _bits_to_dec(nm, check=True):
"""Bits to decimal conversion."""
if check and not is_bits_nm(nm):
raise ValueError('_bits_to_dec: invalid netmask: "%s"' % nm)
bits = int(str(nm))
return VALID_NETMASKS[bits] | python | {
"resource": ""
} |
q263790 | _wildcard_to_dec | validation | def _wildcard_to_dec(nm, check=False):
"""Wildcard bits to decimal conversion."""
if check and not is_wildcard_nm(nm):
raise ValueError('_wildcard_to_dec: invalid netmask: "%s"' % nm)
return 0xFFFFFFFF - _dot_to_dec(nm, check=False) | python | {
"resource": ""
} |
q263791 | _detect | validation | def _detect(ip, _isnm):
"""Function internally used to detect the notation of the
given IP or netmask."""
ip = str(ip)
if len(ip) > 1:
if ip[0:2] == '0x':
if _CHECK_FUNCT[IP_HEX][_isnm](ip):
return IP_HEX
elif ip[0] == '0':
if _CHECK_FUNCT[IP_OCT][... | python | {
"resource": ""
} |
q263792 | _convert | validation | def _convert(ip, notation, inotation, _check, _isnm):
"""Internally used to convert IPs and netmasks to other notations."""
inotation_orig = inotation
notation_orig = notation
inotation = _get_notation(inotation)
notation = _get_notation(notation)
if inotation is None:
raise ValueError('... | python | {
"resource": ""
} |
q263793 | convert | validation | def convert(ip, notation=IP_DOT, inotation=IP_UNKNOWN, check=True):
"""Convert among IP address notations.
Given an IP address, this function returns the address
in another notation.
@param ip: the IP address.
@type ip: integers, strings or object with an appropriate __str()__ method.
@param ... | python | {
"resource": ""
} |
q263794 | convert_nm | validation | def convert_nm(nm, notation=IP_DOT, inotation=IP_UNKNOWN, check=True):
"""Convert a netmask to another notation."""
return _convert(nm, notation, inotation, _check=check, _isnm=True) | python | {
"resource": ""
} |
q263795 | IPv4Address._add | validation | def _add(self, other):
"""Sum two IP addresses."""
if isinstance(other, self.__class__):
sum_ = self._ip_dec + other._ip_dec
elif isinstance(other, int):
sum_ = self._ip_dec + other
else:
other = self.__class__(other)
sum_ = self._ip_dec + ... | python | {
"resource": ""
} |
q263796 | IPv4Address._sub | validation | def _sub(self, other):
"""Subtract two IP addresses."""
if isinstance(other, self.__class__):
sub = self._ip_dec - other._ip_dec
if isinstance(other, int):
sub = self._ip_dec - other
else:
other = self.__class__(other)
sub = self._ip_dec - ... | python | {
"resource": ""
} |
q263797 | IPv4NetMask.get_bits | validation | def get_bits(self):
"""Return the bits notation of the netmask."""
return _convert(self._ip, notation=NM_BITS,
inotation=IP_DOT, _check=False, _isnm=self._isnm) | python | {
"resource": ""
} |
q263798 | IPv4NetMask.get_wildcard | validation | def get_wildcard(self):
"""Return the wildcard bits notation of the netmask."""
return _convert(self._ip, notation=NM_WILDCARD,
inotation=IP_DOT, _check=False, _isnm=self._isnm) | python | {
"resource": ""
} |
q263799 | CIDR.set | validation | def set(self, ip, netmask=None):
"""Set the IP address and the netmask."""
if isinstance(ip, str) and netmask is None:
ipnm = ip.split('/')
if len(ipnm) != 2:
raise ValueError('set: invalid CIDR: "%s"' % ip)
ip = ipnm[0]
netmask = ipnm[1]
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.