_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q4200 | challenge | train | def challenge():
"""Creates an enum for contest type"""
enums = dict(
ACTIVE="active",
UPCOMING="upcoming",
HIRING="hiring",
ALL="all",
SHORT="short",
)
return type('Enum', (), enums) | python | {
"resource": ""
} |
q4201 | time_difference | train | def time_difference(target_time):
"""Calculate the difference between the current time and the given time"""
TimeDiff = namedtuple("TimeDiff", ["days", "hours", "minutes", "seconds"])
time_diff = format_date(target_time) - datetime.utcnow()
hours, remainder = divmod(time_diff.seconds, 3600)
minutes, seconds =... | python | {
"resource": ""
} |
q4202 | CSVofIntegers | train | def CSVofIntegers(msg=None):
'''
Checks whether a value is list of integers.
Returns list of integers or just one integer in
list if there is only one element in given CSV string.
'''
def fn(value):
try:
if isinstance(value, basestring):
if ',' in value:
... | python | {
"resource": ""
} |
q4203 | TeamsViewSet.get_queryset | train | def get_queryset(self):
"""
Optionally restricts the queryset by filtering against
query parameters in the URL.
"""
query_params = self.request.query_params
url_params = self.kwargs
# get queryset_filters from FilterMixin
queryset_filters = self.get_db_f... | python | {
"resource": ""
} |
q4204 | get_setting | train | def get_setting(name, default):
"""
A little helper for fetching global settings with a common prefix.
"""
parent_name = "CMSPLUGIN_NEWS_{0}".format(name)
return getattr(django_settings, parent_name, default) | python | {
"resource": ""
} |
q4205 | NewsAdmin.make_published | train | def make_published(self, request, queryset):
"""
Marks selected news items as published
"""
rows_updated = queryset.update(is_published=True)
self.message_user(request,
ungettext('%(count)d newsitem was published',
... | python | {
"resource": ""
} |
q4206 | NewsAdmin.make_unpublished | train | def make_unpublished(self, request, queryset):
"""
Marks selected news items as unpublished
"""
rows_updated = queryset.update(is_published=False)
self.message_user(request,
ungettext('%(count)d newsitem was unpublished',
... | python | {
"resource": ""
} |
q4207 | _execute_wk | train | def _execute_wk(*args, input=None):
"""
Generate path for the wkhtmltopdf binary and execute command.
:param args: args to pass straight to subprocess.Popen
:return: stdout, stderr
"""
wk_args = (WK_PATH,) + args
return subprocess.run(wk_args, input=input, stdout=subprocess.PIPE, stderr=sub... | python | {
"resource": ""
} |
q4208 | generate_pdf | train | def generate_pdf(html, *,
cache_dir: Path=DFT_CACHE_DIR,
grayscale: bool=False,
lowquality: bool=False,
margin_bottom: str=None,
margin_left: str=None,
margin_right: str=None,
margin_top: str=None,
... | python | {
"resource": ""
} |
q4209 | get_version | train | def get_version():
"""
Get version of pydf and wkhtmltopdf binary
:return: version string
"""
try:
wk_version = _string_execute('-V')
except Exception as e:
# we catch all errors here to make sure we get a version no matter what
wk_version = '%s: %s' % (e.__class__.__nam... | python | {
"resource": ""
} |
q4210 | PyJsParser._interpret_regexp | train | def _interpret_regexp(self, string, flags):
'''Perform sctring escape - for regexp literals'''
self.index = 0
self.length = len(string)
self.source = string
self.lineNumber = 0
self.lineStart = 0
octal = False
st = ''
inside_square = 0
whil... | python | {
"resource": ""
} |
q4211 | Crossref.works | train | def works(self, ids = None, query = None, filter = None, offset = None,
limit = None, sample = None, sort = None,
order = None, facet = None, select = None, cursor = None,
cursor_max = 5000, **kwargs):
'''
Search Crossref works
:param ids: [Array] DOIs ... | python | {
"resource": ""
} |
q4212 | Crossref.prefixes | train | def prefixes(self, ids = None, filter = None, offset = None,
limit = None, sample = None, sort = None,
order = None, facet = None, works = False, select = None,
cursor = None, cursor_max = 5000, **kwargs):
'''
Search Crossref prefixes
:param ids: [Array... | python | {
"resource": ""
} |
q4213 | Crossref.types | train | def types(self, ids = None, query = None, filter = None, offset = None,
limit = None, sample = None, sort = None,
order = None, facet = None, works = False, select = None,
cursor = None, cursor_max = 5000, **kwargs):
'''
Search Crossref types
:param ids... | python | {
"resource": ""
} |
q4214 | Crossref.licenses | train | def licenses(self, query = None, offset = None,
limit = None, sample = None, sort = None,
order = None, facet = None, **kwargs):
'''
Search Crossref licenses
:param query: [String] A query string
:param offset: [Fixnum] Number of record to start at, from 1 to... | python | {
"resource": ""
} |
q4215 | Crossref.registration_agency | train | def registration_agency(self, ids, **kwargs):
'''
Determine registration agency for DOIs
:param ids: [Array] DOIs (digital object identifier) or other identifiers
:param kwargs: additional named arguments passed on to `requests.get`, e.g., field
queries (see examples)
... | python | {
"resource": ""
} |
q4216 | Crossref.random_dois | train | def random_dois(self, sample = 10, **kwargs):
'''
Get a random set of DOIs
:param sample: [Fixnum] Number of random DOIs to return. Default: 10. Max: 100
:param kwargs: additional named arguments passed on to `requests.get`, e.g., field
queries (see examples)
:retur... | python | {
"resource": ""
} |
q4217 | content_negotiation | train | def content_negotiation(ids = None, format = "bibtex", style = 'apa',
locale = "en-US", url = None, **kwargs):
'''
Get citations in various formats from CrossRef
:param ids: [str] Search by a single DOI or many DOIs, each a string. If many
passed in, do so in a list
:param format: [str] Nam... | python | {
"resource": ""
} |
q4218 | citation_count | train | def citation_count(doi, url = "http://www.crossref.org/openurl/",
key = "cboettig@ropensci.org", **kwargs):
'''
Get a citation count with a DOI
:param doi: [String] DOI, digital object identifier
:param url: [String] the API url for the function (should be left to default)
:param keyc: [String]... | python | {
"resource": ""
} |
q4219 | TreeOfContents.findHierarchy | train | def findHierarchy(self, max_subs=10):
"""Find hierarchy for the LaTeX source.
>>> TOC.fromLatex(r'\subsection{yo}\section{hello}').findHierarchy()
('section', 'subsection')
>>> TOC.fromLatex(
... r'\subsubsubsection{huh}\subsubsection{hah}').findHierarchy()
('subsubsecti... | python | {
"resource": ""
} |
q4220 | TreeOfContents.getHeadingLevel | train | def getHeadingLevel(ts, hierarchy=default_hierarchy):
"""Extract heading level for a particular Tex element, given a specified
hierarchy.
>>> ts = TexSoup(r'\section{Hello}').section
>>> TOC.getHeadingLevel(ts)
2
>>> ts2 = TexSoup(r'\chapter{hello again}').chapter
... | python | {
"resource": ""
} |
q4221 | TreeOfContents.parseTopDepth | train | def parseTopDepth(self, descendants=()):
"""Parse tex for highest tag in hierarchy
>>> TOC.fromLatex('\\section{Hah}\\subsection{No}').parseTopDepth()
1
>>> s = '\\subsubsubsection{Yo}\\subsubsection{Hah}'
>>> TOC.fromLatex(s).parseTopDepth()
1
>>> h = ('section'... | python | {
"resource": ""
} |
q4222 | TreeOfContents.fromLatex | train | def fromLatex(tex, *args, **kwargs):
"""Creates abstraction using Latex
:param str tex: Latex
:return: TreeOfContents object
"""
source = TexSoup(tex)
return TOC('[document]', source=source,
descendants=list(source.descendants), *args, **kwargs) | python | {
"resource": ""
} |
q4223 | process_options | train | def process_options(opts):
"""Check and prepare options dict."""
# Convert match and exclude args into pattern lists
match = opts.get("match")
if match and type(match) is str:
opts["match"] = [pat.strip() for pat in match.split(",")]
elif match:
assert type(match) is list
else:
... | python | {
"resource": ""
} |
q4224 | match_path | train | def match_path(entry, opts):
"""Return True if `path` matches `match` and `exclude` options."""
if entry.name in ALWAYS_OMIT:
return False
# TODO: currently we use fnmatch syntax and match against names.
# We also might allow glob syntax and match against the whole relative path instead
# pa... | python | {
"resource": ""
} |
q4225 | BaseSynchronizer._tick | train | def _tick(self):
"""Write progress info and move cursor to beginning of line."""
if (self.verbose >= 3 and not IS_REDIRECTED) or self.options.get("progress"):
stats = self.get_stats()
prefix = DRY_RUN_PREFIX if self.dry_run else ""
sys.stdout.write(
"{... | python | {
"resource": ""
} |
q4226 | BaseSynchronizer._sync_dir | train | def _sync_dir(self):
"""Traverse the local folder structure and remote peers.
This is the core algorithm that generates calls to self.sync_XXX()
handler methods.
_sync_dir() is called by self.run().
"""
local_entries = self.local.get_dir()
# Convert into a dict {... | python | {
"resource": ""
} |
q4227 | BaseSynchronizer.on_copy_local | train | def on_copy_local(self, pair):
"""Called when the local resource should be copied to remote."""
status = pair.remote_classification
self._log_action("copy", status, ">", pair.local) | python | {
"resource": ""
} |
q4228 | BaseSynchronizer.on_copy_remote | train | def on_copy_remote(self, pair):
"""Called when the remote resource should be copied to local."""
status = pair.local_classification
self._log_action("copy", status, "<", pair.remote) | python | {
"resource": ""
} |
q4229 | BiDirSynchronizer.on_need_compare | train | def on_need_compare(self, pair):
"""Re-classify pair based on file attributes and options."""
# print("on_need_compare", pair)
# If no metadata is available, we could only classify file entries as
# 'existing'.
# Now we use peer information to improve this classification.
... | python | {
"resource": ""
} |
q4230 | BiDirSynchronizer.on_conflict | train | def on_conflict(self, pair):
"""Return False to prevent visiting of children."""
# self._log_action("skip", "conflict", "!", pair.local, min_level=2)
# print("on_conflict", pair)
any_entry = pair.any_entry
if not self._test_match_or_print(any_entry):
return
r... | python | {
"resource": ""
} |
q4231 | DownloadSynchronizer._interactive_resolve | train | def _interactive_resolve(self, pair):
"""Return 'local', 'remote', or 'skip' to use local, remote resource or skip."""
if self.resolve_all:
if self.verbose >= 5:
self._print_pair_diff(pair)
return self.resolve_all
resolve = self.options.get("resolve", "sk... | python | {
"resource": ""
} |
q4232 | set_pyftpsync_logger | train | def set_pyftpsync_logger(logger=True):
"""Define target for common output.
Args:
logger (bool | None | logging.Logger):
Pass None to use `print()` to stdout instead of logging.
Pass True to create a simple standard logger.
"""
global _logger
prev_logger = _logger
... | python | {
"resource": ""
} |
q4233 | write | train | def write(*args, **kwargs):
"""Redirectable wrapper for print statements."""
debug = kwargs.pop("debug", None)
warning = kwargs.pop("warning", None)
if _logger:
kwargs.pop("end", None)
kwargs.pop("file", None)
if debug:
_logger.debug(*args, **kwargs)
elif warn... | python | {
"resource": ""
} |
q4234 | write_error | train | def write_error(*args, **kwargs):
"""Redirectable wrapper for print sys.stderr statements."""
if _logger:
kwargs.pop("end", None)
kwargs.pop("file", None)
_logger.error(*args, **kwargs)
else:
print(*args, file=sys.stderr, **kwargs) | python | {
"resource": ""
} |
q4235 | namespace_to_dict | train | def namespace_to_dict(o):
"""Convert an argparse namespace object to a dictionary."""
d = {}
for k, v in o.__dict__.items():
if not callable(v):
d[k] = v
return d | python | {
"resource": ""
} |
q4236 | eps_compare | train | def eps_compare(f1, f2, eps):
"""Return true if |f1-f2| <= eps."""
res = f1 - f2
if abs(res) <= eps: # '<=',so eps == 0 works as expected
return 0
elif res < 0:
return -1
return 1 | python | {
"resource": ""
} |
q4237 | get_option | train | def get_option(env_name, section, opt_name, default=None):
"""Return a configuration setting from environment var or .pyftpsyncrc"""
val = os.environ.get(env_name)
if val is None:
try:
val = _pyftpsyncrc_parser.get(section, opt_name)
except (compat.configparser.NoSectionError, co... | python | {
"resource": ""
} |
q4238 | prompt_for_password | train | def prompt_for_password(url, user=None, default_user=None):
"""Prompt for username and password.
If a user name is passed, only prompt for a password.
Args:
url (str): hostname
user (str, optional):
Pass a valid name to skip prompting for a user name
default_user (str, o... | python | {
"resource": ""
} |
q4239 | get_credentials_for_url | train | def get_credentials_for_url(url, opts, force_user=None):
"""Lookup credentials for a given target in keyring and .netrc.
Optionally prompts for credentials if not found.
Returns:
2-tuple (username, password) or None
"""
creds = None
verbose = int(opts.get("verbose"))
force_prompt =... | python | {
"resource": ""
} |
q4240 | save_password | train | def save_password(url, username, password):
"""Store credentials in keyring."""
if keyring:
if ":" in username:
raise RuntimeError(
"Unable to store credentials if username contains a ':' ({}).".format(
username
)
)
try... | python | {
"resource": ""
} |
q4241 | str_to_bool | train | def str_to_bool(val):
"""Return a boolean for '0', 'false', 'on', ..."""
val = str(val).lower().strip()
if val in ("1", "true", "on", "yes"):
return True
elif val in ("0", "false", "off", "no"):
return False
raise ValueError(
"Invalid value '{}'"
"(expected '1', '0', ... | python | {
"resource": ""
} |
q4242 | ansi_code | train | def ansi_code(name):
"""Return ansi color or style codes or '' if colorama is not available."""
try:
obj = colorama
for part in name.split("."):
obj = getattr(obj, part)
return obj
except AttributeError:
return "" | python | {
"resource": ""
} |
q4243 | make_target | train | def make_target(url, extra_opts=None):
"""Factory that creates `_Target` objects from URLs.
FTP targets must begin with the scheme ``ftp://`` or ``ftps://`` for TLS.
Note:
TLS is only supported on Python 2.7/3.2+.
Args:
url (str):
extra_opts (dict, optional): Passed to Target c... | python | {
"resource": ""
} |
q4244 | _get_encoding_opt | train | def _get_encoding_opt(synchronizer, extra_opts, default):
"""Helper to figure out encoding setting inside constructors."""
encoding = default
# if synchronizer and "encoding" in synchronizer.options:
# encoding = synchronizer.options.get("encoding")
if extra_opts and "encoding" in extra_opts:
... | python | {
"resource": ""
} |
q4245 | _Target.walk | train | def walk(self, pred=None, recursive=True):
"""Iterate over all target entries recursively.
Args:
pred (function, optional):
Callback(:class:`ftpsync.resources._Resource`) should return `False` to
ignore entry. Default: `None`.
recursive (bool, opt... | python | {
"resource": ""
} |
q4246 | FsTarget.set_mtime | train | def set_mtime(self, name, mtime, size):
"""Set modification time on file."""
self.check_write(name)
os.utime(os.path.join(self.cur_dir, name), (-1, mtime)) | python | {
"resource": ""
} |
q4247 | FtpTarget._lock | train | def _lock(self, break_existing=False):
"""Write a special file to the target root folder."""
# write("_lock")
data = {"lock_time": time.time(), "lock_holder": None}
try:
assert self.cur_dir == self.root_dir
self.write_text(DirMetadata.LOCK_FILE_NAME, json.... | python | {
"resource": ""
} |
q4248 | FtpTarget._unlock | train | def _unlock(self, closing=False):
"""Remove lock file to the target root folder.
"""
# write("_unlock", closing)
try:
if self.cur_dir != self.root_dir:
if closing:
write(
"Changing to ftp root folder to rem... | python | {
"resource": ""
} |
q4249 | FtpTarget._probe_lock_file | train | def _probe_lock_file(self, reported_mtime):
"""Called by get_dir"""
delta = reported_mtime - self.lock_data["lock_time"]
# delta2 = reported_mtime - self.lock_write_time
self.server_time_ofs = delta
if self.get_option("verbose", 3) >= 4:
write("Server time offse... | python | {
"resource": ""
} |
q4250 | EntryPair.is_same_time | train | def is_same_time(self):
"""Return True if local.mtime == remote.mtime."""
return (
self.local
and self.remote
and FileEntry._eps_compare(self.local.mtime, self.remote.mtime) == 0
) | python | {
"resource": ""
} |
q4251 | EntryPair.override_operation | train | def override_operation(self, operation, reason):
"""Re-Classify entry pair."""
prev_class = (self.local_classification, self.remote_classification)
prev_op = self.operation
assert operation != prev_op
assert operation in PAIR_OPERATIONS
if self.any_entry.target.synchroniz... | python | {
"resource": ""
} |
q4252 | EntryPair.classify | train | def classify(self, peer_dir_meta):
"""Classify entry pair."""
assert self.operation is None
# write("CLASSIFIY", self, peer_dir_meta)
# Note: We pass False if the entry is not listed in the metadata.
# We pass None if we don't have metadata all.
peer_entry_meta = pe... | python | {
"resource": ""
} |
q4253 | _Resource.classify | train | def classify(self, peer_dir_meta):
"""Classify this entry as 'new', 'unmodified', or 'modified'."""
assert self.classification is None
peer_entry_meta = None
if peer_dir_meta:
# Metadata is generally available, so we can detect 'new' or 'modified'
peer_entry_meta ... | python | {
"resource": ""
} |
q4254 | FileEntry.was_modified_since_last_sync | train | def was_modified_since_last_sync(self):
"""Return True if this resource was modified since last sync.
None is returned if we don't know (because of missing meta data).
"""
info = self.get_sync_info()
if not info:
return None
if self.size != info["s"]:
... | python | {
"resource": ""
} |
q4255 | DirMetadata.set_mtime | train | def set_mtime(self, filename, mtime, size):
"""Store real file mtime in meta data.
This is needed on FTP targets, because FTP servers don't allow to set
file mtime, but use to the upload time instead.
We also record size and upload time, so we can detect if the file was
changed ... | python | {
"resource": ""
} |
q4256 | DirMetadata.remove | train | def remove(self, filename):
"""Remove any data for the given file name."""
if self.list.pop(filename, None):
self.modified_list = True
if self.target.peer: # otherwise `scan` command
if self.target.is_local():
remote_target = self.target.peer
... | python | {
"resource": ""
} |
q4257 | DirMetadata.read | train | def read(self):
"""Initialize self from .pyftpsync-meta.json file."""
assert self.path == self.target.cur_dir
try:
self.modified_list = False
self.modified_sync = False
is_valid_file = False
s = self.target.read_text(self.filename)
# p... | python | {
"resource": ""
} |
q4258 | DirMetadata.flush | train | def flush(self):
"""Write self to .pyftpsync-meta.json."""
# We DO write meta files even on read-only targets, but not in dry-run mode
# if self.target.readonly:
# write("DirMetadata.flush(%s): read-only; nothing to do" % self.target)
# return
assert self.path == ... | python | {
"resource": ""
} |
q4259 | scan_handler | train | def scan_handler(parser, args):
"""Implement `scan` sub-command."""
opts = namespace_to_dict(args)
opts.update({"ftp_debug": args.verbose >= 6})
target = make_target(args.target, opts)
target.readonly = True
root_depth = target.root_dir.count("/")
start = time.time()
dir_count = 1
fi... | python | {
"resource": ""
} |
q4260 | TableCell.get_format_spec | train | def get_format_spec(self):
'''
The format specification according to the values of `align` and `width`
'''
return u"{{:{align}{width}}}".format(align=self.align, width=self.width) | python | {
"resource": ""
} |
q4261 | Table.compute_column_width_and_height | train | def compute_column_width_and_height(self):
'''
compute and set the column width for all colls in the table
'''
# skip tables with no row
if not self.rows:
return
# determine row height
for row in self.rows:
max_row_height = max((len(cell.g... | python | {
"resource": ""
} |
q4262 | get_parser | train | def get_parser():
""" Parses the arguments if script is run directly via console """
parser = argparse.ArgumentParser(description='Converts HTML from file or url to a clean text version')
parser.add_argument('input', nargs='?', default=None, help='Html input either from a file or an url (default:stdin)')
... | python | {
"resource": ""
} |
q4263 | Inscriptis.write_line | train | def write_line(self, force=False):
'''
Writes the current line to the buffer, provided that there is any
data to write.
::returns:
True, if a line has been writer, otherwise False
'''
# only break the line if there is any relevant content
if not force... | python | {
"resource": ""
} |
q4264 | CssParse._attr_display | train | def _attr_display(value, html_element):
'''
Set the display value
'''
if value == 'block':
html_element.display = Display.block
elif value == 'none':
html_element.display = Display.none
else:
html_element.display = Display.inline | python | {
"resource": ""
} |
q4265 | read_file | train | def read_file(file_path, default_content=''):
"""
Read file at the specified path.
If file doesn't exist, it will be created with default-content.
Returns the file content.
"""
if not os.path.exists(file_path):
write_file(file_path, default_content)
handler = open(file_path, 'r')
... | python | {
"resource": ""
} |
q4266 | write_file | train | def write_file(file_path, content):
"""
Write file at the specified path with content.
If file exists, it will be overwritten.
"""
handler = open(file_path, 'w+')
handler.write(content)
handler.close() | python | {
"resource": ""
} |
q4267 | set_maintenance_mode | train | def set_maintenance_mode(value):
"""
Set maintenance_mode state to state file.
"""
# If maintenance mode is defined in settings, it can't be changed.
if settings.MAINTENANCE_MODE is not None:
raise ImproperlyConfigured(
'Maintenance mode cannot be set dynamically '
'... | python | {
"resource": ""
} |
q4268 | get_maintenance_response | train | def get_maintenance_response(request):
"""
Return a '503 Service Unavailable' maintenance response.
"""
if settings.MAINTENANCE_MODE_REDIRECT_URL:
return redirect(settings.MAINTENANCE_MODE_REDIRECT_URL)
context = {}
if settings.MAINTENANCE_MODE_GET_TEMPLATE_CONTEXT:
try:
... | python | {
"resource": ""
} |
q4269 | need_maintenance_response | train | def need_maintenance_response(request):
"""
Tells if the given request needs a maintenance response or not.
"""
try:
view_match = resolve(request.path)
view_func = view_match[0]
view_dict = view_func.__dict__
view_force_maintenance_mode_off = view_dict.get(
... | python | {
"resource": ""
} |
q4270 | LDAPLoginManager.format_results | train | def format_results(self, results):
"""
Format the ldap results object into somthing that is reasonable
"""
if not results:
return None
userdn = results[0][0]
userobj = results[0][1]
userobj['dn'] = userdn
keymap = self.config.get('KEY_MAP')
... | python | {
"resource": ""
} |
q4271 | LDAPLoginManager.attrlist | train | def attrlist(self):
'Transform the KEY_MAP paramiter into an attrlist for ldap filters'
keymap = self.config.get('KEY_MAP')
if keymap:
# https://github.com/ContinuumIO/flask-ldap-login/issues/11
# https://continuumsupport.zendesk.com/agent/tickets/393
return [... | python | {
"resource": ""
} |
q4272 | LDAPLoginManager.connect | train | def connect(self):
'initialize ldap connection and set options'
log.debug("Connecting to ldap server %s" % self.config['URI'])
self.conn = ldap.initialize(self.config['URI'])
# There are some settings that can't be changed at runtime without a context restart.
# It's possible to... | python | {
"resource": ""
} |
q4273 | LDAPLoginManager.ldap_login | train | def ldap_login(self, username, password):
"""
Authenticate a user using ldap. This will return a userdata dict
if successfull.
ldap_login will return None if the user does not exist or if the credentials are invalid
"""
self.connect()
if self.config.get('USER_SEA... | python | {
"resource": ""
} |
q4274 | HostIP.address | train | def address(self):
"""
IP Address using bacpypes Address format
"""
port = ""
if self._port:
port = ":{}".format(self._port)
return Address(
"{}/{}{}".format(
self.interface.ip.compressed,
self.interface.exploded.spl... | python | {
"resource": ""
} |
q4275 | HostIP._findIPAddr | train | def _findIPAddr(self):
"""
Retrieve the IP address connected to internet... used as
a default IP address when defining Script
:returns: IP Adress as String
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("google.com", 0))
... | python | {
"resource": ""
} |
q4276 | HostIP._findSubnetMask | train | def _findSubnetMask(self, ip):
"""
Retrieve the broadcast IP address connected to internet... used as
a default IP address when defining Script
:param ip: (str) optionnal IP address. If not provided, default to getIPAddr()
:param mask: (str) optionnal subnet mask. If not provide... | python | {
"resource": ""
} |
q4277 | SQLMixin._read_from_sql | train | def _read_from_sql(self, request, db_name):
"""
Using the contextlib, I hope to close the connection to database when
not in use
"""
with contextlib.closing(sqlite3.connect("{}.db".format(db_name))) as con:
return sql.read_sql(sql=request, con=con) | python | {
"resource": ""
} |
q4278 | SQLMixin.backup_histories_df | train | def backup_histories_df(self):
"""
Build a dataframe of the point histories
"""
backup = {}
for point in self.points:
if point.history.dtypes == object:
backup[point.properties.name] = (
point.history.replace(["inactive", "active"],... | python | {
"resource": ""
} |
q4279 | SQLMixin.save | train | def save(self, filename=None):
"""
Save the point histories to sqlite3 database.
Save the device object properties to a pickle file so the device can be reloaded.
"""
if filename:
if ".db" in filename:
filename = filename.split(".")[0]
se... | python | {
"resource": ""
} |
q4280 | SQLMixin.points_from_sql | train | def points_from_sql(self, db_name):
"""
Retrieve point list from SQL database
"""
points = self._read_from_sql("SELECT * FROM history;", db_name)
return list(points.columns.values)[1:] | python | {
"resource": ""
} |
q4281 | SQLMixin.his_from_sql | train | def his_from_sql(self, db_name, point):
"""
Retrive point histories from SQL database
"""
his = self._read_from_sql('select * from "%s"' % "history", db_name)
his.index = his["index"].apply(Timestamp)
return his.set_index("index")[point] | python | {
"resource": ""
} |
q4282 | SQLMixin.read_point_prop | train | def read_point_prop(self, device_name, point):
"""
Points properties retrieved from pickle
"""
with open("%s.bin" % device_name, "rb") as file:
return pickle.load(file)["points"][point] | python | {
"resource": ""
} |
q4283 | SQLMixin.read_dev_prop | train | def read_dev_prop(self, device_name):
"""
Device properties retrieved from pickle
"""
with open("{}.bin".format(device_name), "rb") as file:
return pickle.load(file)["device"] | python | {
"resource": ""
} |
q4284 | BooleanPoint.value | train | def value(self):
"""
Read the value from BACnet network
"""
try:
res = self.properties.device.properties.network.read(
"{} {} {} presentValue".format(
self.properties.device.properties.address,
self.properties.type,
... | python | {
"resource": ""
} |
q4285 | EnumPointOffline.value | train | def value(self):
"""
Take last known value as the value
"""
try:
value = self.lastValue
except IndexError:
value = "NaN"
except ValueError:
value = "NaN"
return value | python | {
"resource": ""
} |
q4286 | Stats_Mixin.network_stats | train | def network_stats(self):
"""
Used by Flask to show informations on the network
"""
statistics = {}
mstp_networks = []
mstp_map = {}
ip_devices = []
bacoids = []
mstp_devices = []
for address, bacoid in self.whois_answer[0].keys():
... | python | {
"resource": ""
} |
q4287 | DeviceConnected.connect | train | def connect(self, *, db=None):
"""
A connected device can be switched to 'database mode' where the device will
not use the BACnet network but instead obtain its contents from a previously
stored database.
"""
if db:
self.poll(command="stop")
... | python | {
"resource": ""
} |
q4288 | DeviceConnected.df | train | def df(self, list_of_points, force_read=True):
"""
When connected, calling DF should force a reading on the network.
"""
his = []
for point in list_of_points:
try:
his.append(self._findPoint(point, force_read=force_read).history)
... | python | {
"resource": ""
} |
q4289 | DeviceConnected._buildPointList | train | def _buildPointList(self):
"""
Upon connection to build the device point list and properties.
"""
try:
self.properties.pss.value = self.properties.network.read(
"{} device {} protocolServicesSupported".format(
self.properties.address... | python | {
"resource": ""
} |
q4290 | DeviceConnected._findPoint | train | def _findPoint(self, name, force_read=True):
"""
Used by getter and setter functions
"""
for point in self.points:
if point.properties.name == name:
if force_read:
point.value
return point
raise ValueError("... | python | {
"resource": ""
} |
q4291 | discoverPoints | train | def discoverPoints(bacnetapp, address, devID):
"""
Discover the BACnet points in a BACnet device.
:param bacnetApp: The app itself so we can call read
:param address: address of the device as a string (ex. '2:5')
:param devID: device ID of the bacnet device as a string (ex. '1001')
:returns: a... | python | {
"resource": ""
} |
q4292 | CubicBezier.point | train | def point(self, pos):
"""Calculate the x,y position at a certain position of the path"""
return ((1 - pos) ** 3 * self.start) + \
(3 * (1 - pos) ** 2 * pos * self.control1) + \
(3 * (1 - pos) * pos ** 2 * self.control2) + \
(pos ** 3 * self.end) | python | {
"resource": ""
} |
q4293 | WebSocket.register_blueprint | train | def register_blueprint(self, blueprint, **options):
'''
Registers a blueprint on the WebSockets.
'''
first_registration = False
if blueprint.name in self.blueprints:
assert self.blueprints[blueprint.name] is blueprint, \
'A blueprint\'s name collision ... | python | {
"resource": ""
} |
q4294 | adjust_lineno | train | def adjust_lineno(filename, lineno, name):
"""Adjust the line number of an import.
Needed because import statements can span multiple lines, and our lineno
is always the first line number.
"""
line = linecache.getline(filename, lineno)
# Hack warning: might be fooled by comments
rx = re.com... | python | {
"resource": ""
} |
q4295 | ModuleGraph.parsePathname | train | def parsePathname(self, pathname):
"""Parse one or more source files.
``pathname`` may be a file name or a directory name.
"""
if os.path.isdir(pathname):
for root, dirs, files in os.walk(pathname):
dirs.sort()
files.sort()
for... | python | {
"resource": ""
} |
q4296 | ModuleGraph.writeCache | train | def writeCache(self, filename):
"""Write the graph to a cache file."""
with open(filename, 'wb') as f:
pickle.dump(self.modules, f) | python | {
"resource": ""
} |
q4297 | ModuleGraph.readCache | train | def readCache(self, filename):
"""Load the graph from a cache file."""
with open(filename, 'rb') as f:
self.modules = pickle.load(f) | python | {
"resource": ""
} |
q4298 | ModuleGraph.parseFile | train | def parseFile(self, filename):
"""Parse a single file."""
modname = self.filenameToModname(filename)
module = Module(modname, filename)
self.modules[modname] = module
if self.trackUnusedNames:
module.imported_names, module.unused_names = \
find_imports... | python | {
"resource": ""
} |
q4299 | ModuleGraph.filenameToModname | train | def filenameToModname(self, filename):
"""Convert a filename to a module name."""
for ext in reversed(self._exts):
if filename.endswith(ext):
filename = filename[:-len(ext)]
break
else:
self.warn(filename, '%s: unknown file name extension',... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.