code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
with lock:
host_lock = get_host_lock(scraperobj.url)
with host_lock:
self._getStrips(scraperobj) | def getStrips(self, scraperobj) | Download comic strips. | 6.311453 | 6.456774 | 0.977493 |
if self.options.all or self.options.cont:
numstrips = None
elif self.options.numstrips:
numstrips = self.options.numstrips
else:
# get current strip
numstrips = 1
try:
if scraperobj.isComplete(self.options.basepath):
... | def _getStrips(self, scraperobj) | Get all strips from a scraper. | 4.917362 | 4.887863 | 1.006035 |
allskipped = True
for image in strip.getImages():
try:
if self.options.dry_run:
filename, saved = "", False
else:
filename, saved = image.save(self.options.basepath)
if saved:
... | def saveComicStrip(self, strip) | Save a comic strip which can consist of multiple images. | 5.387417 | 5.302083 | 1.016094 |
out = {}
out['value'] = var2.get('value', var1.get('value', None))
out['mimetype'] = var2.get('mimetype', var1.get('mimetype', None))
out['types'] = var2.get('types') + [x for x in var1.get('types') if x not in var2.get('types')]
out['optional'] = var2.get('optional', var1.get('optional', False... | def merge(var1, var2) | Take two copies of a variable and reconcile them. var1 is assumed
to be the higher-level variable, and so will be overridden by var2
where such becomes necessary. | 2.511091 | 2.527768 | 0.993402 |
if self.has_value() and self.has_type(var_type):
return True
return False | def has_value_of_type(self, var_type) | Does the variable both have the given type and
have a variable value we can use? | 3.845765 | 2.943544 | 1.306508 |
for name, var in self.items():
if var.get('optional', False):
yield name | def optional_names(self) | Get a list of the variables that are defined, but not required | 6.812539 | 5.232823 | 1.301886 |
opt_names = list(self.optional_names())
if opt_names:
return '[, {}]'.format(', '.join(opt_names))
else:
return '' | def optional_namestring(self) | Compose a string showing the optional variables (helper for the
API printing function) | 3.944065 | 3.270542 | 1.205936 |
output = set()
for var in self.values():
if var.has_value():
output.update(var.types())
return list(output) | def types(self) | Return a list of all the variable types that exist in the
Variables object. | 5.611725 | 4.611096 | 1.217005 |
return {x: y for x, y in self.items() if y.has_value_of_type(var_type)} | def vals(self, var_type) | Create a dictionary with name/value pairs listing the
variables of a particular type that have a value. | 4.49394 | 3.720569 | 1.207864 |
for name, var in kwargs.items():
if iskeyword(name):
var['name'] = name
name = '_' + name
if name in self:
self[name] = merge(self[name], Variable(self.default_type, **var))
else:
self[name] = Variable(s... | def add(self, **kwargs) | Add additional single Variable objects to the Variables
object. | 3.612399 | 3.301426 | 1.094194 |
missing = self.missing_vars()
if len(args) == len(missing) == 1:
self.setval(missing[0], args[0]) | def fill_arg(self, *args) | If we get a single positional argument, and only a single
variable needs to be filled, fill that variable with
the value from that positional argument. | 5.348773 | 4.418836 | 1.210448 |
for var, val in kwargs.items():
self.setval(var, val) | def fill_kwargs(self, **kwargs) | Fill empty variable objects by name with the values from
any present keyword arguments. | 6.353346 | 5.534631 | 1.147926 |
self.fill_kwargs(**kwargs)
self.fill_arg(*args)
self.assert_full()
return self | def fill(self, *args, **kwargs) | Take args and kwargs and fill up any variables that
don't have a value yet. | 8.446252 | 7.13807 | 1.183268 |
if varname in self:
self[varname]['value'] = value
else:
self[varname] = Variable(self.default_type, value=value) | def setval(self, varname, value) | Set the value of the variable with the given name. | 4.003664 | 3.82501 | 1.046707 |
try:
self.chart_obj = self._chart(x, y, chart_type, opts, style, label,
options=options, **kwargs)
except Exception as e:
self.err(e, self.chart, "Can not create chart") | def chart(self, x=None, y=None, chart_type=None, opts=None,
style=None, label=None, options={}, **kwargs) | Get a chart | 3.301495 | 3.536764 | 0.933479 |
if opts is not None:
self.chart_opts = opts
if style is not None:
self.chart_style = style
if label is not None:
self.label = label
self.x = x
self.y = y
if chart_type is None:
return
try:
chart_obj = self._get_chart(chart_type, x, y, style=style,
opts=opts, label=label,
... | def _chart(self, x, y, chart_type, opts, style, label, options, **kwargs) | Initialize chart options | 2.150549 | 2.128154 | 1.010523 |
try:
return self._get_chart("bar", style=style, opts=opts, label=label,
options=options)
except Exception as e:
self.err(e, self.bar_, "Can not draw bar chart") | def bar_(self, label=None, style=None, opts=None, options={}) | Get a bar chart | 4.616053 | 4.504362 | 1.024796 |
self.opts(dict(stack_index=stack_index, color_index=stack_index))
try:
if stack_index is None:
self.err(self.sbar_, "Please provide a stack index parameter")
options["stack_index"] = stack_index
return self._get_chart("bar", style=style, opts=opts, label=label,
options=options)
except E... | def sbar_(self, stack_index=None, label=None, style=None, opts=None,
options={}) | Get a stacked bar chart | 3.795553 | 3.722609 | 1.019595 |
try:
return self._bokeh_quants(inf, sup, chart_type, color)
except Exception as e:
self.err(e, self.quants_, "Can not draw quantile chart") | def quants_(self, inf, sup, chart_type="point",
color="green") | Draw a chart to visualize quantiles | 4.512897 | 4.634251 | 0.973814 |
options = dict(window_size=window_size, y_label=y_label)
try:
return self._get_chart("sline", style=self.chart_style,
opts=self.chart_opts, label=chart_label,
options=options)
except Exception as e:
self.err(e, self.sline_, "Can not draw smooth curve chart") | def sline_(self, window_size=5,
y_label="Moving average", chart_label=None) | Get a moving average curve chart to smooth between points | 3.852181 | 3.94191 | 0.977237 |
try:
charts = self._multiseries(col, x, y, "area", rsum, rmean)
return hv.Area.stack(charts)
except Exception as e:
self.err(e, self.sarea_, "Can not draw stacked area chart") | def sarea_(self, col, x=None, y=None, rsum=None, rmean=None) | Get an stacked area chart | 6.851863 | 6.064076 | 1.12991 |
try:
if style is None:
style = self.chart_style
if "size" not in style:
style["size"] = 10
style["color"] = colors["line"]
c = self._get_chart("line", style=style, opts=opts,
label=label, options=options)
style["color"] = colors["point"]
c2 = self._get_chart("point", style=style... | def line_point_(self, label=None, style=None, opts=None, options={},
colors={"line": "orange", "point": "#30A2DA"}) | Get a line and point chart | 2.701075 | 2.584546 | 1.045087 |
return self._multiseries(col, x, y, "point", rsum, rmean) | def mpoint_(self, col, x=None, y=None, rsum=None, rmean=None) | Splits a column into multiple series based on the column's
unique values. Then visualize theses series in a chart.
Parameters: column to split, x axis column, y axis column
Optional: rsum="1D" to resample and sum data an rmean="1D"
to mean the data | 6.083711 | 7.976831 | 0.762673 |
return self._multiseries(col, x, y, "line", rsum, rmean) | def mline_(self, col, x=None, y=None, rsum=None, rmean=None) | Splits a column into multiple series based on the column's
unique values. Then visualize theses series in a chart.
Parameters: column to split, x axis column, y axis column
Optional: rsum="1D" to resample and sum data an rmean="1D"
to mean the data | 6.39388 | 7.405288 | 0.863421 |
return self._multiseries(col, x, y, "bar", rsum, rmean) | def mbar_(self, col, x=None, y=None, rsum=None, rmean=None) | Splits a column into multiple series based on the column's
unique values. Then visualize theses series in a chart.
Parameters: column to split, x axis column, y axis column
Optional: rsum="1D" to resample and sum data an rmean="1D"
to mean the data | 6.098487 | 7.219538 | 0.84472 |
line = self._multiseries(col, x, y, "line", rsum, rmean)
point = self._multiseries(col, x, y, "point", rsum, rmean)
return line * point | def mline_point_(self, col, x=None, y=None, rsum=None, rmean=None) | Splits a column into multiple series based on the column's
unique values. Then visualize theses series in a chart.
Parameters: column to split, x axis column, y axis column
Optional: rsum="1D" to resample and sum data an rmean="1D"
to mean the data | 3.504462 | 3.971868 | 0.882321 |
try:
arrow = hv.Arrow(
xloc,
yloc,
text,
orientation,
arrowstyle=arrowstyle)
return arrow
except Exception as e:
self.err(e, self.arrow_, "Can not draw arrow chart") | def arrow_(self, xloc, yloc, text, orientation="v", arrowstyle='->') | Returns an arrow for a chart. Params: the text, xloc and yloc are
coordinates to position the arrow. Orientation is the way to display
the arrow: possible values are ``[<, ^, >, v]``. Arrow style is the
graphic style of the arrow:
possible values: ``[-, ->, -[, -|>, <->, <|-|>]`` | 4.497152 | 4.181398 | 1.075514 |
self.autoprint = False
x, y = self._check_fields(x, y)
chart = None
series = self.split_(col)
for key in series:
instance = series[key]
if rsum is not None:
instance.rsum(rsum, index_col=x)
if rmean is not None:
instance.rmean(rmean, index_col=x)
instance.chart(x, y)
self.scolor()
... | def _multiseries(self, col, x, y, ctype, rsum, rmean) | Chart multiple series from a column distinct values | 3.163855 | 3.099921 | 1.020624 |
try:
return self._get_chart("distribution", style=style, opts=opts, label=label)
except Exception as e:
self.err(e, "Can not draw distrinution chart") | def distrib_(self, label=None, style=None, opts=None) | Get a Seaborn distribution chart | 5.714716 | 5.285284 | 1.08125 |
for k in dictobj:
self.chart_opts[k] = dictobj[k] | def opts(self, dictobj) | Add or update options | 4.525753 | 4.822682 | 0.938431 |
for k in dictobj:
self.chart_style[k] = dictobj[k] | def styles(self, dictobj) | Add or update styles | 4.710727 | 4.572895 | 1.030141 |
try:
del self.chart_opts[name]
except KeyError:
self.warning("Option " + name + " is not set")
except:
self.err("Can not remove option " + name) | def ropt(self, name) | Remove one option | 4.488042 | 4.328003 | 1.036978 |
try:
del self.chart_style[name]
except KeyError:
self.warning("Style " + name + " is not set")
except:
self.err("Can not remove style " + name) | def rstyle(self, name) | Remove one style | 4.549668 | 4.395663 | 1.035036 |
self.chart_style = {}
self.chart_opts = {}
self.style("color", "#30A2DA")
self.width(900)
self.height(250) | def defaults(self) | Reset the chart options and style to defaults | 5.919652 | 4.420182 | 1.339232 |
if x is None:
if self.x is None:
self.err(
self._check_fields,
"X field is not set: please specify a parameter")
return
x = self.x
if y is None:
if self.y is None:
self.err(
self._check_fields,
"Y field is not set: please specify a parameter")
return
y = self.y
r... | def _check_fields(self, x, y) | Check x and y fields parameters and initialize | 2.421044 | 2.246668 | 1.077615 |
sbcharts = ["density", "distribution", "dlinear"]
acharts = ["tick", "circle", "text", "line_num", "bar_num"]
if chart_type in sbcharts:
self._set_seaborn_engine()
if chart_type in acharts:
self._set_altair_engine()
if chart_type != "sline":
x, y = self._check_fields(x, y)
if opts is None:
op... | def _get_chart(self, chart_type, x=None, y=None, style=None, opts=None,
label=None, options={}, **kwargs) | Get a full chart object | 2.590975 | 2.639028 | 0.981791 |
if self.x is None:
self.err(self._check_defaults,
"X field is not set: please specify a parameter")
return
if x_only is True:
return
if self.y is None:
self.err(self._check_defaults,
"Y field is not set: please specify a parameter")
return | def _check_defaults(self, x_only=True) | Checks if charts defaults are set | 3.438152 | 3.205317 | 1.07264 |
chapter, num = index.split('-')
return self.stripUrl % (chapter, chapter, num) | def getIndexStripUrl(self, index) | Get comic strip URL from index. | 8.929104 | 7.603506 | 1.17434 |
if not isinstance(flags, (list, tuple)):
flags = [str(flags)]
self.extend(["--%s" % f for f in flags])
return self | def add_flags(self, *flags) | Adds one or more flags to the query.
For example:
current-patch-set -> --current-patch-set | 4.224835 | 4.947325 | 0.853964 |
from cms.plugin_pool import plugin_pool
qs = self.get_queryset()
qs = qs.public()
if current_site_only:
site = Site.objects.get_current()
qs = qs.filter(tree__site=site)
qt = Q(title_set__title__icontains=q)
# find 'searchable' plugins... | def search(self, q, language=None, current_site_only=True) | Simple search function
Plugins can define a 'search_fields' tuple similar to ModelAdmin classes | 2.70447 | 2.741598 | 0.986458 |
try:
title = self.get(language=language, article=article)
return title
except self.model.DoesNotExist:
if language_fallback:
try:
titles = self.filter(article=article)
fallbacks = get_fallback_languages(... | def get_title(self, article, language, language_fallback=False) | Gets the latest content for a particular article and language. Falls back
to another language if wanted. | 2.637193 | 2.618403 | 1.007176 |
base_fields = [
'slug',
'title',
'description',
'meta_description',
'page_title',
'menu_title',
'image',
]
cleaned_data = form.cleaned_data
try:
obj = self.get(article=article, langua... | def set_or_create(self, request, article, form, language) | set or create a title for a particular article and language | 2.072102 | 2.080595 | 0.995918 |
if not uname or not pwd:
logging.error("Username or password not supplied")
return False
ld = ldap.initialize(LDAP_URL)
if LDAP_VERSION_3:
ld.set_option(ldap.VERSION3, 1)
ld.start_tls_s()
udn = ld.search_s(LDAP_SEARCH_BASE, ldap.SCOPE_ONELEVEL,
... | def auth_user_ldap(uname, pwd) | Attempts to bind using the uname/pwd combo passed in.
If that works, returns true. Otherwise returns false. | 3.10928 | 3.100786 | 1.002739 |
try:
if os.name == 'nt':
return get_nt_system_uid()
if sys.platform == 'darwin':
return get_osx_system_uid()
except Exception:
return get_mac_uid()
else:
return get_mac_uid() | def get_system_uid() | Get a (probably) unique ID to identify a system.
Used to differentiate votes. | 3.076536 | 3.093485 | 0.994521 |
try:
import _winreg as winreg
except ImportError:
import winreg
lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
try:
key = winreg.OpenKey(lm, r"Software\Microsoft\Cryptography")
try:
return winreg.QueryValueEx(key, "MachineGuid")[0]
f... | def get_nt_system_uid() | Get the MachineGuid from
HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\MachineGuid | 2.238789 | 1.825271 | 1.226552 |
res = backtick(["system_profile"]).splitlines()
for line in res:
if "r (system)" in line:
return line.split(':', 1)[1].strip()
raise ValueError("Could not find system number in %r" % res) | def get_osx_system_uid() | Get the OSX system ID.
$ system_profiler |grep "r (system)"
Serial Number (system): C24E1322XYZ | 8.290788 | 4.985417 | 1.663008 |
try:
text_type = unicode
except NameError:
text_type = str
if isinstance(text, text_type):
return text
return text.decode(encoding, errors) | def unicode_safe(text, encoding=UrlEncoding, errors='ignore') | Decode text to Unicode if not already done. | 2.211741 | 2.043183 | 1.082498 |
if before:
prefix = r"[^>]*%s[^>]*\s+" % before
else:
prefix = r"(?:[^>]*\s+)?"
attrs = dict(
tag=case_insensitive_re(tag),
attribute=case_insensitive_re(attribute),
value=value,
quote=quote,
prefix=prefix,
after=after,
)
return r'... | def tagre(tag, attribute, value, quote='"', before="", after="") | Return a regular expression matching the given HTML tag, attribute
and value. It matches the tag and attribute names case insensitive,
and skips arbitrary whitespace and leading HTML attributes. The "<>" at
the start and end of the HTML tag is also matched.
@param tag: the tag name
@ptype tag: strin... | 2.980492 | 3.106926 | 0.959306 |
check_robotstxt(url, session)
# read page data
try:
page = urlopen(url, session, max_content_bytes=max_content_bytes)
except IOError:
page = urlopen(url, session, max_content_bytes=max_content_bytes)
data = page.text
tries = MaxRetries
while not isValidPageContent(data) ... | def getPageContent(url, session, max_content_bytes=MaxContentBytes) | Get text content of given URL. | 3.008388 | 3.001174 | 1.002404 |
return urlopen(url, session, referrer=referrer, max_content_bytes=max_content_bytes, stream=True) | def getImageObject(url, referrer, session, max_content_bytes=MaxImageBytes) | Get response object for given image URL. | 3.896861 | 3.668824 | 1.062155 |
norm = []
for x in makeSequence(things):
if hasattr(x, 'pattern'):
norm.append(x.pattern)
else:
norm.append(x)
return "('%s')" % "', '".join(norm) | def prettyMatcherList(things) | Try to construct a nicely-formatted string for a list of matcher
objects. Those may be compiled regular expressions or strings... | 4.271325 | 3.632679 | 1.175806 |
url = unicode_safe(url).strip()
# XXX: brutal hack
url = unescape(url)
pu = list(urlparse(url))
segments = pu[2].split('/')
while segments and segments[0] in ('', '..'):
del segments[0]
pu[2] = '/' + '/'.join(segments)
# remove leading '&' from query
if pu[4].startswith... | def normaliseURL(url) | Normalising
- strips and leading or trailing whitespace,
- replaces HTML entities and character references,
- removes any leading empty segments to avoid breaking urllib2. | 3.914771 | 3.979398 | 0.98376 |
roboturl = get_roboturl(url)
rp = get_robotstxt_parser(roboturl, session=session)
if not rp.can_fetch(UserAgent, str(url)):
raise IOError("%s is disallowed by %s" % (url, roboturl)) | def check_robotstxt(url, session) | Check if robots.txt allows our user agent for the given URL.
@raises: IOError if URL is not allowed | 5.201637 | 4.614809 | 1.127162 |
rp = robotparser.RobotFileParser()
try:
req = urlopen(url, session, max_content_bytes=MaxContentBytes, raise_for_status=False)
except Exception:
# connect or timeout errors are treated as an absent robots.txt
rp.allow_all = True
else:
if req.status_code >= 400:
... | def get_robotstxt_parser(url, session=None) | Get a RobotFileParser for the given robots.txt URL. | 4.197128 | 4.201419 | 0.998979 |
out.debug(u'Open URL %s' % url)
headers = {'User-Agent': useragent}
if referrer:
headers['Referer'] = referrer
out.debug(u'Sending headers %s' % headers, level=3)
out.debug(u'Sending cookies %s' % session.cookies)
kwargs = {
"headers": headers,
"timeout": timeout,
... | def urlopen(url, session, referrer=None, max_content_bytes=None,
timeout=ConnectionTimeoutSecs, raise_for_status=True,
stream=False, data=None, useragent=UserAgent) | Open an URL and return the response object. | 2.566572 | 2.572261 | 0.997788 |
if not max_content_bytes:
return
if 'content-length' in headers:
size = int(headers['content-length'])
if size > max_content_bytes:
msg = 'URL content of %s with %d bytes exceeds %d bytes.' % (url, size, max_content_bytes)
raise IOError(msg) | def check_content_size(url, headers, max_content_bytes) | Check that content length in URL response headers do not exceed the
given maximum bytes. | 2.608402 | 2.418025 | 1.078732 |
c = []
head, tail = os.path.split(path)
while tail:
c.insert(0, tail)
head, tail = os.path.split(head)
return c | def splitpath(path) | Split a path in its components. | 2.222656 | 2.1584 | 1.02977 |
basepath = splitpath(os.path.abspath(basepath))
path = splitpath(os.path.abspath(path))
afterCommon = False
for c in basepath:
if afterCommon or path[0] != c:
path.insert(0, os.path.pardir)
afterCommon = True
else:
del path[0]
return os.path.j... | def getRelativePath(basepath, path) | Get a path that is relative to the given base path. | 2.756791 | 2.791948 | 0.987408 |
query = urlsplit(url)[3]
out.debug(u'Extracting query parameters from %r (%r)...' % (url, query))
return cgi.parse_qs(query) | def getQueryParams(url) | Get URL query parameters. | 6.18031 | 6.371085 | 0.970056 |
print(os.linesep, file=out)
print( % dict(app=AppName, url=SupportUrl), file=out)
if etype is None:
etype = sys.exc_info()[0]
if evalue is None:
evalue = sys.exc_info()[1]
print(etype, evalue, file=out)
if tb is None:
tb = sys.exc_info()[2]
traceback.print_except... | def internal_error(out=sys.stderr, etype=None, evalue=None, tb=None) | Print internal error message (output defaults to stderr). | 3.194313 | 3.21714 | 0.992905 |
while '%' in text:
newtext = url_unquote(text)
if newtext == text:
break
text = newtext
return text | def unquote(text) | Replace all percent-encoded entities in text. | 3.979756 | 4.07749 | 0.976031 |
if b < 0:
raise ValueError("Invalid negative byte number")
if b < 1024:
return "%dB" % b
if b < 1024 * 10:
return "%dKB" % (b // 1024)
if b < 1024 * 1024:
return "%.2fKB" % (float(b) / 1024)
if b < 1024 * 1024 * 10:
return "%.2fMB" % (float(b) / (1024*102... | def strsize (b) | Return human representation of bytes b. A negative number of bytes
raises a value error. | 1.429209 | 1.370727 | 1.042665 |
# first replace all illegal chars
name = re.sub(r"[^0-9a-zA-Z_\-\.]", "_", name)
# then remove double dots and underscores
while ".." in name:
name = name.replace('..', '.')
while "__" in name:
name = name.replace('__', '_')
# remove a leading dot or minus
if name.starts... | def getFilename(name) | Get a filename from given name without dangerous or incompatible characters. | 3.096774 | 3.052623 | 1.014463 |
num = 1
stem, ext = os.path.splitext(name)
filename = name
while not os.path.exists(filename):
suffix = "-%d" % num
filename = stem + suffix + ext
num += 1
if num >= max_suffix:
raise ValueError("No file %r found" % name)
return filename | def getExistingFile(name, max_suffix=1000) | Add filename suffix until file exists
@return: filename if file is found
@raise: ValueError if maximum suffix number is reached while searching | 2.833186 | 2.950005 | 0.9604 |
num = 1
stem, ext = os.path.splitext(name)
filename = name
while os.path.exists(filename):
suffix = "-%d" % num
filename = stem + suffix + ext
num += 1
return filename | def getNonexistingFile(name) | Add filename suffix until file not exists
@return: filename | 2.888281 | 2.997892 | 0.963437 |
assert length >= 0, "length limit must be a non-negative integer"
if not s or len(s) <= length:
return s
if length == 0:
return ""
return "%s..." % s[:length] | def strlimit (s, length=72) | If the length of the string exceeds the given limit, it will be cut
off and three dots will be appended.
@param s: the string to limit
@type s: string
@param length: maximum length
@type length: non-negative integer
@return: limited string, at most length+3 characters long | 3.614821 | 3.417169 | 1.057841 |
if not content:
raise OSError("empty content for file %s" % filename)
def getfp(filename, encoding):
if encoding:
return codecs.open(filename, 'w', encoding)
return open(filename, 'wb')
try:
with getfp(filename, encoding) as fp:
fp.writ... | def writeFile(filename, content, encoding=None) | Write content to given filename. Checks for zero-sized files.
If encoding is given writes to a codec.open() file. | 2.683196 | 2.669484 | 1.005137 |
if 'chapter04' in url:
return url.replace('chapter04', 'chapter03')
if 'chapter03' in url:
return url.replace('chapter03', 'chapter02')
if 'chapter02' in url:
return url.replace('chapter02', 'chapter01')
return None | def getPrevUrl(self, url, data) | Find previous URL. | 2.004209 | 1.933175 | 1.036744 |
print("Parsing", url, file=sys.stderr)
try:
data = getPageContent(url, session)
except IOError as msg:
print("ERROR:", msg, file=sys.stderr)
return
for match in url_matcher.finditer(data):
url = match.group(1)
name = unescape(match.group(2))
name = as... | def handle_url(url, session, res) | Parse one search result page. | 4.243057 | 4.112388 | 1.031775 |
# store info in a dictionary {name -> shortname}
res = {}
session = requests.Session()
handle_url('http://www.creators.com/comics/cat-seeall.html', session, res)
save_result(res, json_file) | def get_results() | Parse all search result pages. | 15.096634 | 14.527065 | 1.039207 |
cname = "Gocomics/%s" % name
for scraperclass in get_scraperclasses():
lname = scraperclass.getName().lower()
if lname == cname.lower():
return True
return False | def has_gocomics_comic(name) | Test if comic name already exists. | 5.181245 | 5.298032 | 0.977957 |
min_comics, filename = args
with codecs.open(filename, 'a', 'utf-8') as fp:
for name, url in sorted(load_result(json_file).items()):
if name in exclude_comics:
continue
if has_gocomics_comic(name):
prefix = u'# duplicate of gocomics '
... | def print_results(args) | Print comics. | 6.951107 | 6.333431 | 1.097526 |
response = self.request(E.searchProductSslCertRequest(
E.limit(limit),
E.offset(offset),
E.withPrice(int(with_price)),
E.withSupportedSoftware(int(with_supported_software)),
E.withDescription(int(with_description)),
))
return ... | def search_product(self, limit=100, offset=0, with_price=0, with_supported_software=0,
with_description=0) | Search the list of available products. | 3.961688 | 4.127213 | 0.959894 |
response = self.request(E.retrieveProductSslCertRequest(
E.id(product_id)
))
return response.as_model(SSLProduct) | def retrieve_product(self, product_id) | Retrieve details on a single product. | 16.156197 | 16.643585 | 0.970716 |
response = self.request(E.searchOrderSslCertRequest(
E.limit(limit),
E.offset(offset),
OE('commonNamePattern', common_name_pattern),
OE('status', status, transform=_simple_array),
OE('contactHandle', contact_handle),
))
retur... | def search_order(self, limit=100, offset=0, common_name_pattern=None, status=None,
contact_handle=None) | Search all SSL certificate orders. | 6.728467 | 6.431242 | 1.046216 |
response = self.request(E.retrieveOrderSslCertRequest(
E.id(order_id)
))
return response.as_model(SSLOrder) | def retrieve_order(self, order_id) | Retrieve details on a single order. | 16.884045 | 16.335594 | 1.033574 |
response = self.request(E.createSslCertRequest(
E.productId(product_id),
E.period(period),
E.csr(csr),
E.softwareId(software_id),
E.organizationHandle(organization_handle),
OE('approverEmail', approver_email),
OE('sign... | def create(self, product_id, period, csr, software_id, organization_handle,
approver_email=None, signature_hash_algorithm=None, domain_validation_methods=None,
hostnames=None, technical_handle=None) | Order a new SSL certificate. | 2.603017 | 2.556634 | 1.018142 |
response = self.request(E.reissueSslCertRequest(
E.id(order_id),
E.csr(csr),
E.softwareId(software_id),
E.organizationHandle(organization_handle),
OE('approverEmail', approver_email),
OE('signatureHashAlgorithm', signature_hash_al... | def reissue(self, order_id, csr, software_id, organization_handle, approver_email=None,
signature_hash_algorithm=None, domain_validation_methods=None, hostnames=None,
technical_handle=None) | Reissue an SSL certificate order | 2.80564 | 2.814595 | 0.996818 |
response = self.request(E.modifySslCertRequest(
E.id(order_id),
OE('approverEmail', approver_email),
OE('domainValidationMethods', domain_validation_methods, transform=_domain_validation_methods),
))
return response.data | def modify(self, order_id, approver_email=None, domain_validation_methods=None) | Modify an ordered SSL certificate. | 6.176929 | 5.608596 | 1.101333 |
response = self.request(E.cancelSslCertRequest(
E.id(order_id)
))
return int(response.data.id) | def cancel(self, order_id) | Cancel an ordered SSL certificate. | 12.177555 | 7.850419 | 1.551198 |
response = self.request(E.retrieveApproverEmailListSslCertRequest(
E.domain(domain),
E.productId(product_id)
))
return [str(i) for i in response.data.array[0].item] | def retrieve_approver_email_list(self, domain, product_id) | Retrieve the list of allowed approver email addresses. | 7.927793 | 7.390853 | 1.072649 |
response = self.request(E.resendApproverEmailSslCertRequest(
E.id(order_id)
))
return int(response.data.id) | def resend_approver_email(self, order_id) | Resend the activation email to the approver. | 13.704106 | 12.157364 | 1.127227 |
response = self.request(
E.changeApproverEmailAddressSslCertRequest(
E.id(order_id),
E.approverEmail(approver_email)
)
)
return int(response.data.id) | def change_approver_email_address(self, order_id, approver_email) | Change the approver email address for an ordered SSL certificate. | 6.68107 | 5.531664 | 1.207787 |
response = self.request(E.decodeCsrSslCertRequest(
E.csr(csr)
))
return response.data | def decode_csr(self, csr) | Decode a CSR and return its data. | 15.027416 | 14.410712 | 1.042795 |
'''
quantity: 数量
type: 类型
1.国内高匿代理
2.国内普通代理
3.国外高匿代理
4.国外普通代理
'''
url_queue = Queue()
need_pages = int(math.ceil(quantity/15))
# 判断类型
if type == 1:
# 国内高匿代理
base_url = self.domestic_gn... | def get_proxies(self, quantity, type) | quantity: 数量
type: 类型
1.国内高匿代理
2.国内普通代理
3.国外高匿代理
4.国外普通代理 | 2.604495 | 2.312285 | 1.126373 |
if config.LOG_FUNCTION in self.settings:
self.settings[config.LOG_FUNCTION](handler)
return
if handler.get_status() < 400:
log_method = LOGGER.info
elif handler.get_status() < 500:
log_method = LOGGER.warning
else:
log_... | def log_request(self, handler) | Writes a completed HTTP request to the logs.
By default writes to the tinman.application LOGGER. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary as
'log_function'.
:param tornado.web.Reques... | 2.381163 | 2.411507 | 0.987417 |
LOGGER.debug('Importing %s', class_path)
try:
return utils.import_namespaced_class(class_path)
except ImportError as error:
LOGGER.critical('Could not import %s: %s', class_path, error)
return None | def _import_class(self, class_path) | Try and import the specified namespaced class.
:param str class_path: The full path to the class (foo.bar.Baz)
:rtype: class | 3.142009 | 3.073076 | 1.022431 |
LOGGER.debug('Importing %s', module_path)
try:
return __import__(module_path)
except ImportError as error:
LOGGER.critical('Could not import %s: %s', module_path, error)
return None | def _import_module(self, module_path) | Dynamically import a module returning a handle to it.
:param str module_path: The module path
:rtype: module | 2.64969 | 2.703407 | 0.98013 |
if config.BASE in self.paths:
sys.path.insert(0, self.paths[config.BASE]) | def _insert_base_path(self) | If the "base" path is set in the paths section of the config, insert
it into the python path. | 6.19344 | 3.501385 | 1.768854 |
if config.BASE in self.paths:
for path in [path for path in self.paths if path != config.BASE]:
if config.BASE_VARIABLE in self.paths[path]:
self.paths[path] = \
self.paths[path].replace(config.BASE_VARIABLE,
... | def _prepare_paths(self) | Set the value of {{base}} in paths if the base path is set in the
configuration.
:raises: ValueError | 3.404861 | 3.368497 | 1.010795 |
if type(attrs) not in (list, tuple):
LOGGER.error('Invalid route, must be a list or tuple: %r', attrs)
return
# By default there are not any extra kwargs
kwargs = None
# If there is a regex based route, set it up with a raw string
if attrs[0] ==... | def _prepare_route(self, attrs) | Take a given inbound list for a route and parse it creating the
route and importing the class it belongs to.
:param list attrs: Route attributes
:rtype: list | 3.28597 | 3.220224 | 1.020417 |
if not isinstance(routes, list):
raise ValueError('Routes parameter must be a list of tuples')
prepared_routes = list()
for parts in routes:
route = self._prepare_route(parts)
if route:
LOGGER.info('Appending handler: %r', route)
... | def _prepare_routes(self, routes) | Prepare the routes by iterating through the list of tuples & calling
prepare route on them.
:param routes: Routes to prepare
:type routes: list
:rtype: list
:raises: ValueError | 3.759964 | 3.603084 | 1.04354 |
for offset, value in enumerate(self._config.get(config.TRANSFORMS, [])):
self._config[config.TRANSFORMS][offset] = self._import_class(value) | def _prepare_transforms(self) | Prepare the list of transforming objects | 6.040632 | 5.070024 | 1.19144 |
if config.TRANSLATIONS in self.paths:
LOGGER.info('Loading translations from %s',
self.paths[config.TRANSLATIONS])
from tornado import locale
locale.load_translations(self.paths[config.TRANSLATIONS])
if config.DEFAULT_LOCALE in sel... | def _prepare_translations(self) | Load in translations if they are set, and add the default locale as
well. | 2.604111 | 2.346338 | 1.109862 |
for key, value in self._config.get(config.UI_MODULES, {}).iteritems():
self._config[config.UI_MODULES][key] = self._import_class(value)
self._config[config.UI_MODULES] = dict(self._config[config.UI_MODULES] or {}) | def _prepare_uimodules(self) | Prepare the UI Modules from a list of namespaced paths. | 3.314753 | 3.17399 | 1.044349 |
if config.VERSION not in self._config:
self._config[config.VERSION] = __version__ | def _prepare_version(self) | Setup the application version | 7.871354 | 5.628982 | 1.398362 |
if item in self.__dict__[self.ATTRIBUTES].keys():
raise AttributeError('%s already exists' % item)
setattr(self, item, value) | def add(self, item, value) | Add an attribute value to our object instance.
:param str item: Application attribute name
:param any value: Value to associate with the attribute
:raises: AttributeError | 5.355396 | 4.92952 | 1.086393 |
if item not in self.__dict__[self.ATTRIBUTES].keys():
raise AttributeError('%s does not exist' % item)
delattr(self, item) | def remove(self, item) | Remove an attribute value to our object instance.
:param str item: Application attribute name
:raises: AttributeError | 5.633249 | 4.659757 | 1.208915 |
response_dict = None
res = {
'status': NOT_RUN,
'err': '',
'record': response_dict
}
try:
url = 'https://{}'.format(
address)
if not token:
try:
token = get_session_key.get_session_key(
user=user,
... | def search(
user=None,
password=None,
token=None,
address=None,
query_dict=None,
verify=False,
debug=False) | search
Search Splunk with a pre-built query dictionary and
wait until it finishes.
:param user: splunk username
:param password: splunk password
:param token: splunk token
:param address: splunk HEC address: localhost:8089
:param query_dict: query dictionary to search
:param verify: ss... | 2.432404 | 2.406097 | 1.010934 |
ret = int(integer_string)
if ret < 0 or (ret == 0 and strict):
raise ValueError()
if cutoff:
ret = min(ret, cutoff)
return ret | def _positive_int(integer_string, strict=False, cutoff=None) | Cast a string to a strictly positive integer. | 3.347781 | 3.329554 | 1.005474 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.