_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q33200 | ONVIFCamera.get_definition | train | def get_definition(self, name):
'''Returns xaddr and wsdl of specified service'''
# Check if the service is supported
if name not in SERVICES:
raise ONVIFError('Unknown service %s' % name)
wsdl_file = SERVICES[name]['wsdl']
ns = SERVICES[name]['ns']
wsdlpath ... | python | {
"resource": ""
} |
q33201 | ONVIFCamera.create_onvif_service | train | def create_onvif_service(self, name, from_template=True, portType=None):
'''Create ONVIF service client'''
name = name.lower()
xaddr, wsdl_file = self.get_definition(name)
with self.services_lock:
svt = self.services_template.get(name)
# Has a template, clone fr... | python | {
"resource": ""
} |
q33202 | Map.build_rectangle_dict | train | def build_rectangle_dict(self,
north,
west,
south,
east,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
... | python | {
"resource": ""
} |
q33203 | Map.add_rectangle | train | def add_rectangle(self,
north=None,
west=None,
south=None,
east=None,
**kwargs):
""" Adds a rectangle dict to the Map.rectangles attribute
The Google Maps API describes a rectangle using the La... | python | {
"resource": ""
} |
q33204 | Map.build_circle_dict | train | def build_circle_dict(self,
center_lat,
center_lng,
radius,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
fill_color='#FF000... | python | {
"resource": ""
} |
q33205 | Map.add_circle | train | def add_circle(self,
center_lat=None,
center_lng=None,
radius=None,
**kwargs):
""" Adds a circle dict to the Map.circles attribute
The circle in a sphere is called "spherical cap" and is defined in the
Google Maps API b... | python | {
"resource": ""
} |
q33206 | Map.build_polylines | train | def build_polylines(self, polylines):
""" Process data to construct polylines
This method is built from the assumption that the polylines parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[la... | python | {
"resource": ""
} |
q33207 | Map.build_polyline_dict | train | def build_polyline_dict(self,
path,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2):
""" Set a dictionary with the javascript class Polyline parameters
This function sets a defaul... | python | {
"resource": ""
} |
q33208 | Map.add_polyline | train | def add_polyline(self, path=None, **kwargs):
""" Adds a polyline dict to the Map.polylines attribute
The Google Maps API describes a polyline as a "linear overlay of
connected line segments on the map". The linear paths are defined
by a list of Latitude and Longitude coordinate pairs, l... | python | {
"resource": ""
} |
q33209 | Map.build_polygons | train | def build_polygons(self, polygons):
""" Process data to construct polygons
This method is built from the assumption that the polygons parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[lat,ln... | python | {
"resource": ""
} |
q33210 | Map.build_polygon_dict | train | def build_polygon_dict(self,
path,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
fill_color='#FF0000',
fill_opacity=0.3):
""" Set a dict... | python | {
"resource": ""
} |
q33211 | Map.add_polygon | train | def add_polygon(self, path=None, **kwargs):
""" Adds a polygon dict to the Map.polygons attribute
The Google Maps API describes a polyline as a "linear overlay of
connected line segments on the map" and "form a closed loop and define
a filled region.". The linear paths are defined by a ... | python | {
"resource": ""
} |
q33212 | _Captcha.generate | train | def generate(self, chars, format='png'):
"""Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format
"""
im = self.generate_image(chars)
out = BytesIO()
im.save(out, format=format)
out.seek(0)... | python | {
"resource": ""
} |
q33213 | _Captcha.write | train | def write(self, chars, output, format='png'):
"""Generate and write an image CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destination.
:param format: image file format
"""
im = self.generate_image(chars)
return im.save(out... | python | {
"resource": ""
} |
q33214 | ImageCaptcha.generate_image | train | def generate_image(self, chars):
"""Generate the image of the given characters.
:param chars: text to be generated.
"""
background = random_color(238, 255)
color = random_color(10, 200, random.randint(220, 255))
im = self.create_captcha_image(chars, color, background)
... | python | {
"resource": ""
} |
q33215 | change_speed | train | def change_speed(body, speed=1):
"""Change the voice speed of the wave body."""
if speed == 1:
return body
length = int(len(body) * speed)
rv = bytearray(length)
step = 0
for v in body:
i = int(step)
while i < int(step + speed) and i < length:
rv[i] = v
... | python | {
"resource": ""
} |
q33216 | patch_wave_header | train | def patch_wave_header(body):
"""Patch header to the given wave body.
:param body: the wave content body, it should be bytearray.
"""
length = len(body)
padded = length + length % 2
total = WAVE_HEADER_LENGTH + padded
header = copy.copy(WAVE_HEADER)
# fill the total length position
... | python | {
"resource": ""
} |
q33217 | create_noise | train | def create_noise(length, level=4):
"""Create white noise for background"""
noise = bytearray(length)
adjust = 128 - int(level / 2)
i = 0
while i < length:
v = random.randint(0, 256)
noise[i] = v % level + adjust
i += 1
return noise | python | {
"resource": ""
} |
q33218 | create_silence | train | def create_silence(length):
"""Create a piece of silence."""
data = bytearray(length)
i = 0
while i < length:
data[i] = 128
i += 1
return data | python | {
"resource": ""
} |
q33219 | mix_wave | train | def mix_wave(src, dst):
"""Mix two wave body into one."""
if len(src) > len(dst):
# output should be longer
dst, src = src, dst
for i, sv in enumerate(src):
dv = dst[i]
if sv < 128 and dv < 128:
dst[i] = int(sv * dv / 128)
else:
dst[i] = int(2... | python | {
"resource": ""
} |
q33220 | AudioCaptcha.choices | train | def choices(self):
"""Available choices for characters to be generated."""
if self._choices:
return self._choices
for n in os.listdir(self._voicedir):
if len(n) == 1 and os.path.isdir(os.path.join(self._voicedir, n)):
self._choices.append(n)
return... | python | {
"resource": ""
} |
q33221 | AudioCaptcha.generate | train | def generate(self, chars):
"""Generate audio CAPTCHA data. The return data is a bytearray.
:param chars: text to be generated.
"""
if not self._cache:
self.load()
body = self.create_wave_body(chars)
return patch_wave_header(body) | python | {
"resource": ""
} |
q33222 | AudioCaptcha.write | train | def write(self, chars, output):
"""Generate and write audio CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destionation.
"""
data = self.generate(chars)
with open(output, 'wb') as f:
return f.write(data) | python | {
"resource": ""
} |
q33223 | render_to_json | train | def render_to_json(templates, context, request):
"""
Generate a JSON HttpResponse with rendered template HTML.
"""
html = render_to_string(
templates,
context=context,
request=request
)
_json = json.dumps({
"html": html
})
return HttpResponse(_json) | python | {
"resource": ""
} |
q33224 | GZipMixin.path | train | def path(self):
"""
Serve gzip file if client accept it.
Generate or update the gzip file if needed.
"""
path = self._path()
statobj = os.stat(path)
ae = self.request.META.get('HTTP_ACCEPT_ENCODING', '')
if re_accepts_gzip.search(ae) and getattr(settings, ... | python | {
"resource": ""
} |
q33225 | DataLayerUpdate.if_match | train | def if_match(self):
"""Optimistic concurrency control."""
match = True
if_match = self.request.META.get('HTTP_IF_MATCH')
if if_match:
etag = self.etag()
if etag != if_match:
match = False
return match | python | {
"resource": ""
} |
q33226 | map_permissions_check | train | def map_permissions_check(view_func):
"""
Used for URLs dealing with the map.
"""
@wraps(view_func)
def wrapper(request, *args, **kwargs):
map_inst = get_object_or_404(Map, pk=kwargs['map_id'])
user = request.user
kwargs['map_inst'] = map_inst # Avoid rerequesting the map in... | python | {
"resource": ""
} |
q33227 | get_uri_template | train | def get_uri_template(urlname, args=None, prefix=""):
'''
Utility function to return an URI Template from a named URL in django
Copied from django-digitalpaper.
Restrictions:
- Only supports named urls! i.e. url(... name="toto")
- Only support one namespace level
- Only returns the first URL... | python | {
"resource": ""
} |
q33228 | BaseWriter.calculate_size | train | def calculate_size(self, modules_per_line, number_of_lines, dpi=300):
"""Calculates the size of the barcode in pixel.
:parameters:
modules_per_line : Integer
Number of modules in one line.
number_of_lines : Integer
Number of lines of the barcode.
... | python | {
"resource": ""
} |
q33229 | BaseWriter.render | train | def render(self, code):
"""Renders the barcode to whatever the inheriting writer provides,
using the registered callbacks.
:parameters:
code : List
List of strings matching the writer spec
(only contain 0 or 1).
"""
if self._callbacks[... | python | {
"resource": ""
} |
q33230 | Barcode.save | train | def save(self, filename, options=None, text=None):
"""Renders the barcode and saves it in `filename`.
:parameters:
filename : String
Filename to save the barcode in (without filename
extension).
options : Dict
The same as in `self.... | python | {
"resource": ""
} |
q33231 | Barcode.write | train | def write(self, fp, options=None, text=None):
"""Renders the barcode and writes it to the file like object
`fp`.
:parameters:
fp : File like object
Object to write the raw data in.
options : Dict
The same as in `self.render`.
t... | python | {
"resource": ""
} |
q33232 | UniversalProductCodeA.build | train | def build(self):
"""Builds the barcode pattern from 'self.upc'
:return: The pattern as string
:rtype: String
"""
code = _upc.EDGE[:]
for i, number in enumerate(self.upc[0:6]):
code += _upc.CODES['L'][int(number)]
code += _upc.MIDDLE
for num... | python | {
"resource": ""
} |
q33233 | Issue.search | train | def search(query, stats):
""" Perform issue search for given stats instance """
log.debug("Search query: {0}".format(query))
issues = []
# Fetch data from the server in batches of MAX_RESULTS issues
for batch in range(MAX_BATCHES):
response = stats.parent.session.get(... | python | {
"resource": ""
} |
q33234 | Issue.updated | train | def updated(self, user, options):
""" True if the issue was commented by given user """
for comment in self.comments:
created = dateutil.parser.parse(comment["created"]).date()
try:
if (comment["author"]["emailAddress"] == user.email and
cr... | python | {
"resource": ""
} |
q33235 | Bitly.user_link_history | train | def user_link_history(self, created_before=None, created_after=None,
limit=100, **kwargs):
""" Bit.ly API - user_link_history wrapper"""
""" Bit.ly link
Link History Keys
-----------------
[u'aggregate_link', u'archived', u'campaign_ids',
... | python | {
"resource": ""
} |
q33236 | SavedLinks.fetch | train | def fetch(self):
'''
Bit.ly API expect unix timestamps
'''
since = time.mktime(self.options.since.datetime.timetuple())
until = time.mktime(self.options.until.datetime.timetuple())
log.info("Searching for links saved by {0}".format(self.user))
self.stats = self.pa... | python | {
"resource": ""
} |
q33237 | Sentry.issues | train | def issues(self, kind, email):
""" Filter unique issues for given activity type and email """
return list(set([unicode(activity.issue)
for activity in self.activities()
if kind == activity.kind and activity.user['email'] == email])) | python | {
"resource": ""
} |
q33238 | Sentry._fetch_activities | train | def _fetch_activities(self):
""" Get organization activity, handle pagination """
activities = []
# Prepare url of the first page
url = '{0}/organizations/{1}/activity/'.format(
self.url, self.organization)
while url:
# Fetch one page of activities
... | python | {
"resource": ""
} |
q33239 | NitrateStats.cases | train | def cases(self):
""" All test cases created by the user """
import nitrate
if self._cases is None:
log.info(u"Searching for cases created by {0}".format(self.user))
self._cases = [
case for case in nitrate.TestCase.search(
author__email... | python | {
"resource": ""
} |
q33240 | NitrateStats.copies | train | def copies(self):
""" All test case copies created by the user """
import nitrate
if self._copies is None:
log.info(u"Searching for cases copied by {0}".format(self.user))
self._copies = [
case for case in nitrate.TestCase.search(
autho... | python | {
"resource": ""
} |
q33241 | authorized_http | train | def authorized_http(client_id, client_secret, apps, file=None):
"""
Start an authorized HTTP session.
Try fetching valid user credentials from storage. If nothing has been
stored, or if the stored credentials are invalid, complete the OAuth2 flow
to obtain new credentials.
"""
if not os.pat... | python | {
"resource": ""
} |
q33242 | GoogleCalendar.events | train | def events(self, **kwargs):
""" Fetch events meeting specified criteria """
events_result = self.service.events().list(**kwargs).execute()
return [Event(event) for event in events_result.get("items", [])] | python | {
"resource": ""
} |
q33243 | Event.attended_by | train | def attended_by(self, email):
""" Check if user attended the event """
for attendee in self["attendees"] or []:
if (attendee["email"] == email
and attendee["responseStatus"] == "accepted"):
return True
return False | python | {
"resource": ""
} |
q33244 | GoogleTasks.tasks | train | def tasks(self, **kwargs):
""" Fetch tasks specified criteria """
tasks_result = self.service.tasks().list(**kwargs).execute()
return [Task(task) for task in tasks_result.get("items", [])] | python | {
"resource": ""
} |
q33245 | GoogleStatsBase.events | train | def events(self):
""" All events in calendar within specified time range """
if self._events is None:
self._events = self.parent.calendar.events(
calendarId="primary", singleEvents=True, orderBy="startTime",
timeMin=self.since, timeMax=self.until)
retu... | python | {
"resource": ""
} |
q33246 | GoogleStatsBase.tasks | train | def tasks(self):
""" All completed tasks within specified time range """
if self._tasks is None:
self._tasks = self.parent.tasks.tasks(
tasklist="@default", showCompleted="true", showHidden="true",
completedMin=self.since, completedMax=self.until)
log.... | python | {
"resource": ""
} |
q33247 | Stats.name | train | def name(self):
""" Use the first line of docs string unless name set. """
if self._name:
return self._name
return [
line.strip() for line in self.__doc__.split("\n")
if line.strip()][0] | python | {
"resource": ""
} |
q33248 | Stats.add_option | train | def add_option(self, group):
""" Add option for self to the parser group object. """
group.add_argument(
"--{0}".format(self.option), action="store_true", help=self.name) | python | {
"resource": ""
} |
q33249 | Stats.check | train | def check(self):
""" Check the stats if enabled. """
if not self.enabled():
return
try:
self.fetch()
except (xmlrpclib.Fault, did.base.ConfigError) as error:
log.error(error)
self._error = True
# Raise the exception if debugging... | python | {
"resource": ""
} |
q33250 | Stats.show | train | def show(self):
""" Display indented statistics. """
if not self._error and not self.stats:
return
self.header()
for stat in self.stats:
utils.item(stat, level=1, options=self.options) | python | {
"resource": ""
} |
q33251 | StatsGroup.add_option | train | def add_option(self, parser):
""" Add option group and all children options. """
group = parser.add_argument_group(self.name)
for stat in self.stats:
stat.add_option(group)
group.add_argument(
"--{0}".format(self.option), action="store_true", help="All above") | python | {
"resource": ""
} |
q33252 | StatsGroup.merge | train | def merge(self, other):
""" Merge all children stats. """
for this, other in zip(self.stats, other.stats):
this.merge(other) | python | {
"resource": ""
} |
q33253 | RequestTracker.get | train | def get(self, path):
""" Perform a GET request with GSSAPI authentication """
# Generate token
service_name = gssapi.Name('HTTP@{0}'.format(self.url.netloc),
gssapi.NameType.hostbased_service)
ctx = gssapi.SecurityContext(usage="initiate", name=service_... | python | {
"resource": ""
} |
q33254 | RequestTracker.search | train | def search(self, query):
""" Perform request tracker search """
# Prepare the path
log.debug("Query: {0}".format(query))
path = self.url.path + '?Format=__id__+__Subject__'
path += "&Order=ASC&OrderBy=id&Query=" + urllib.quote(query)
# Get the tickets
lines = sel... | python | {
"resource": ""
} |
q33255 | Bugzilla.server | train | def server(self):
""" Connection to the server """
if self._server is None:
self._server = bugzilla.Bugzilla(url=self.parent.url)
return self._server | python | {
"resource": ""
} |
q33256 | Bugzilla.search | train | def search(self, query, options):
""" Perform Bugzilla search """
query["query_format"] = "advanced"
log.debug("Search query:")
log.debug(pretty(query))
# Fetch bug info
try:
result = self.server.query(query)
except xmlrpclib.Fault as error:
... | python | {
"resource": ""
} |
q33257 | Bug.summary | train | def summary(self):
""" Bug summary including resolution if enabled """
if not self.bug.resolution:
return self.bug.summary
if (self.bug.resolution.lower() in self.parent.resolutions
or "all" in self.parent.resolutions):
return "{0} [{1}]".format(
... | python | {
"resource": ""
} |
q33258 | Bug.logs | train | def logs(self):
""" Return relevant who-did-what pairs from the bug history """
for record in self.history:
if (record["when"] >= self.options.since.date
and record["when"] < self.options.until.date):
for change in record["changes"]:
yi... | python | {
"resource": ""
} |
q33259 | Bug.verified | train | def verified(self):
""" True if bug was verified in given time frame """
for who, record in self.logs:
if record["field_name"] == "status" \
and record["added"] == "VERIFIED":
return True
return False | python | {
"resource": ""
} |
q33260 | Bug.fixed | train | def fixed(self):
""" Moved to MODIFIED and not later moved to ASSIGNED """
decision = False
for record in self.history:
# Completely ignore older changes
if record["when"] < self.options.since.date:
continue
# Look for status change to MODIFIED... | python | {
"resource": ""
} |
q33261 | Bug.closed | train | def closed(self, user):
""" Moved to CLOSED and not later moved to ASSIGNED """
decision = False
for record in self.history:
# Completely ignore older changes
if record["when"] < self.options.since.date:
continue
# Look for status change to CLO... | python | {
"resource": ""
} |
q33262 | Bug.posted | train | def posted(self):
""" True if bug was moved to POST in given time frame """
for who, record in self.logs:
if record["field_name"] == "status" and record["added"] == "POST":
return True
return False | python | {
"resource": ""
} |
q33263 | Bug.commented | train | def commented(self, user):
""" True if comment was added in given time frame """
for comment in self.comments:
# Description (comment #0) is not considered as a comment
if comment["count"] == 0:
continue
if (comment.get('author', comment.get('creator')... | python | {
"resource": ""
} |
q33264 | Bug.subscribed | train | def subscribed(self, user):
""" True if CC was added in given time frame """
for who, record in self.logs:
if (record["field_name"] == "cc" and
user.email in record["added"]):
return True
return False | python | {
"resource": ""
} |
q33265 | set_name_email | train | def set_name_email(configurator, question, answer):
'''
prepare "Full Name" <email@eg.com>" string
'''
name = configurator.variables['author.name']
configurator.variables['author.name_email'] = '"{0}" <{1}>'.format(
name, answer)
return answer | python | {
"resource": ""
} |
q33266 | load | train | def load():
""" Check available plugins and attempt to import them """
# Code is based on beaker-client's command.py script
plugins = []
for filename in os.listdir(PLUGINS_PATH):
if not filename.endswith(".py") or filename.startswith("_"):
continue
if not os.path.isfile(os.pa... | python | {
"resource": ""
} |
q33267 | GitHub.search | train | def search(self, query):
""" Perform GitHub query """
url = self.url + "/" + query
log.debug("GitHub query: {0}".format(url))
try:
request = urllib2.Request(url, headers=self.headers)
response = urllib2.urlopen(request)
log.debug("Response headers:\n{0... | python | {
"resource": ""
} |
q33268 | Config.item | train | def item(self, section, it):
""" Return content of given item in selected section """
for key, value in self.section(section, skip=[]):
if key == it:
return value
raise ConfigError(
"Item '{0}' not found in section '{1}'".format(it, section)) | python | {
"resource": ""
} |
q33269 | Config.path | train | def path():
""" Detect config file path """
# Detect config directory
try:
directory = os.environ["DID_DIR"]
except KeyError:
directory = CONFIG
# Detect config file (even before options are parsed)
filename = "config"
matched = re.search("... | python | {
"resource": ""
} |
q33270 | Date.this_week | train | def this_week():
""" Return start and end date of the current week. """
since = TODAY + delta(weekday=MONDAY(-1))
until = since + delta(weeks=1)
return Date(since), Date(until) | python | {
"resource": ""
} |
q33271 | Date.this_year | train | def this_year():
""" Return start and end date of this fiscal year """
since = TODAY
while since.month != 3 or since.day != 1:
since -= delta(days=1)
until = since + delta(years=1)
return Date(since), Date(until) | python | {
"resource": ""
} |
q33272 | Date.last_year | train | def last_year():
""" Return start and end date of the last fiscal year """
since, until = Date.this_year()
since = since.date - delta(years=1)
until = until.date - delta(years=1)
return Date(since), Date(until) | python | {
"resource": ""
} |
q33273 | Date.period | train | def period(argument):
""" Detect desired time period for the argument """
since, until, period = None, None, None
if "today" in argument:
since = Date("today")
until = Date("today")
until.date += delta(days=1)
period = "today"
elif "yesterd... | python | {
"resource": ""
} |
q33274 | Trac.search | train | def search(query, parent, options):
""" Perform Trac search """
# Extend the default max number of tickets to be fetched
query = "{0}&max={1}".format(query, MAX_TICKETS)
log.debug("Search query: {0}".format(query))
try:
result = parent.proxy.ticket.query(query)
... | python | {
"resource": ""
} |
q33275 | Trac.history | train | def history(self, user=None):
""" Return relevant who-did-what logs from the ticket history """
for event in self.changelog:
when, who, what, old, new, ignore = event
if (when >= self.options.since.date and
when <= self.options.until.date):
if ... | python | {
"resource": ""
} |
q33276 | Trac.updated | train | def updated(self, user):
""" True if the user commented the ticket in given time frame """
for who, what, old, new in self.history(user):
if (what == "comment" or what == "description") and new != "":
return True
return False | python | {
"resource": ""
} |
q33277 | Trac.closed | train | def closed(self):
""" True if ticket was closed in given time frame """
for who, what, old, new in self.history():
if what == "status" and new == "closed":
return True
return False | python | {
"resource": ""
} |
q33278 | GitRepo.commits | train | def commits(self, user, options):
""" List commits for given user. """
# Prepare the command
command = "git log --all --author={0}".format(user.login).split()
command.append("--format=format:%h - %s")
command.append("--since='{0} 00:00:00'".format(options.since))
command.... | python | {
"resource": ""
} |
q33279 | Pagure.search | train | def search(self, query, pagination, result_field):
""" Perform Pagure query """
result = []
url = "/".join((self.url, query))
while url:
log.debug("Pagure query: {0}".format(url))
try:
response = requests.get(url, headers=self.headers)
... | python | {
"resource": ""
} |
q33280 | GerritUnit.fetch | train | def fetch(self, query_string="", common_query_options=None,
limit_since=False):
"""
Backend for the actual gerrit query.
query_string:
basic query terms, e.g., 'status:abandoned'
common_query_options:
[optional] rest of the query string; if omitted,... | python | {
"resource": ""
} |
q33281 | shorted | train | def shorted(text, width=79):
""" Shorten text, make sure it's not cut in the middle of a word """
if len(text) <= width:
return text
# We remove any word after first overlapping non-word character
return u"{0}...".format(re.sub(r"\W+\w*$", "", text[:width - 2])) | python | {
"resource": ""
} |
q33282 | item | train | def item(text, level=0, options=None):
""" Print indented item. """
# Extra line before in each section (unless brief)
if level == 0 and not options.brief:
print('')
# Only top-level items displayed in brief mode
if level == 1 and options.brief:
return
# Four space for each level... | python | {
"resource": ""
} |
q33283 | pluralize | train | def pluralize(singular=None):
""" Naively pluralize words """
if singular.endswith("y") and not singular.endswith("ay"):
plural = singular[:-1] + "ies"
elif singular.endswith("s"):
plural = singular + "es"
else:
plural = singular + "s"
return plural | python | {
"resource": ""
} |
q33284 | split | train | def split(values, separator=re.compile("[ ,]+")):
"""
Convert space-or-comma-separated values into a single list
Common use case for this is merging content of options with multiple
values allowed into a single list of strings thus allowing any of
the formats below and converts them into ['a', 'b',... | python | {
"resource": ""
} |
q33285 | ascii | train | def ascii(text):
""" Transliterate special unicode characters into pure ascii """
if not isinstance(text, unicode):
text = unicode(text)
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') | python | {
"resource": ""
} |
q33286 | Logging._create_logger | train | def _create_logger(name='did', level=None):
""" Create did logger """
# Create logger, handler and formatter
logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(Logging.ColoredFormatter())
logger.addHandler(handler)
# Save log l... | python | {
"resource": ""
} |
q33287 | Logging.set | train | def set(self, level=None):
"""
Set the default log level
If the level is not specified environment variable DEBUG is used
with the following meaning::
DEBUG=0 ... LOG_WARN (default)
DEBUG=1 ... LOG_INFO
DEBUG=2 ... LOG_DEBUG
DEBUG=3 ... L... | python | {
"resource": ""
} |
q33288 | Coloring.set | train | def set(self, mode=None):
"""
Set the coloring mode
If enabled, some objects (like case run Status) are printed in color
to easily spot failures, errors and so on. By default the feature is
enabled when script is attached to a terminal. Possible values are::
COLOR=0... | python | {
"resource": ""
} |
q33289 | Coloring.enabled | train | def enabled(self):
""" True if coloring is currently enabled """
# In auto-detection mode color enabled when terminal attached
if self._mode == COLOR_AUTO:
return sys.stdout.isatty()
return self._mode == COLOR_ON | python | {
"resource": ""
} |
q33290 | main | train | def main(arguments=None):
"""
Parse options, gather stats and show the results
Takes optional parameter ``arguments`` which can be either
command line string or list of options. This is very useful
for testing purposes. Function returns a tuple of the form::
([user_stats], team_stats)
... | python | {
"resource": ""
} |
q33291 | Options.parse | train | def parse(self):
""" Parse the options. """
# Run the parser
opt, arg = self.parser.parse_known_args(self.arguments)
self.opt = opt
self.arg = arg
self.check()
# Enable --all if no particular stat or group selected
opt.all = not any([
getattr(... | python | {
"resource": ""
} |
q33292 | Options.check | train | def check(self):
""" Perform additional check for given options """
keywords = "today yesterday this last week month quarter year".split()
for argument in self.arg:
if argument not in keywords:
raise did.base.OptionError(
"Invalid argument: '{0}'".... | python | {
"resource": ""
} |
q33293 | GitLab.search | train | def search(self, user, since, until, target_type, action_name):
""" Perform GitLab query """
if not self.user:
self.user = self.get_user(user)
if not self.events:
self.events = self.user_events(self.user['id'], since, until)
result = []
for event in self.e... | python | {
"resource": ""
} |
q33294 | TrelloAPI.board_links_to_ids | train | def board_links_to_ids(self):
""" Convert board links to ids """
resp = self.stats.session.open(
"{0}/members/{1}/boards?{2}".format(
self.stats.url, self.username, urllib.urlencode({
"key": self.key,
"token": self.token,
... | python | {
"resource": ""
} |
q33295 | EngineMixin.engine | train | def engine(self):
"""Return Render Engine."""
return self.backend({
'APP_DIRS': True,
'DIRS': [str(ROOT / self.backend.app_dirname)],
'NAME': 'djangoforms',
'OPTIONS': {},
}) | python | {
"resource": ""
} |
q33296 | CompatibleDateTimeBaseInput.format_value | train | def format_value(self, value):
"""
Return a value as it should appear when rendered in a template.
Missing method of django.forms.widgets.Widget class
"""
if value == '' or value is None:
return None
return formats.localize_input(value, self.format) | python | {
"resource": ""
} |
q33297 | CompatibleDateTimeBaseInput.render | train | def render(self, name, value, attrs=None, renderer=None):
"""
Render the widget as an HTML string.
Missing method of django.forms.widgets.Widget class
"""
context = self.get_context(name, value, attrs)
return self._render(self.template_name, context, renderer) | python | {
"resource": ""
} |
q33298 | YearPickerInput._link_to | train | def _link_to(self, linked_picker):
"""Customize the options when linked with other date-time input"""
yformat = self.config['options']['format'].replace('-01-01', '-12-31')
self.config['options']['format'] = yformat | python | {
"resource": ""
} |
q33299 | BasePickerInput.format_py2js | train | def format_py2js(cls, datetime_format):
"""Convert python datetime format to moment datetime format."""
for js_format, py_format in cls.format_map:
datetime_format = datetime_format.replace(py_format, js_format)
return datetime_format | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.