code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if hasattr(self, "_width"):
return
maxi = []
if self._header:
maxi = [ self._len_cell(x) for x in self._header ]
for row in self._rows:
for cell,i in zip(row, range(len(row))):
try:
maxi[i] = max(maxi[i], s... | def _compute_cols_width(self) | Return an array with the width of each column
If a specific width has been specified, exit. If the total of the
columns width exceed the table desired width, another width will be
computed to fit, and cells will be wrapped. | 3.062732 | 2.915312 | 1.050568 |
if not hasattr(self, "_align"):
self._align = ["l"]*self._row_size
if not hasattr(self, "_valign"):
self._valign = ["t"]*self._row_size | def _check_align(self) | Check if alignment has been specified, set default one if not | 3.923671 | 3.203631 | 1.224757 |
line = self._splitit(line, isheader)
space = " "
out = ""
for i in range(len(line[0])):
if self._has_border():
out += "%s " % self._char_vert
length = 0
for cell, width, align in zip(line, self._width, self._align):
... | def _draw_line(self, line, isheader=False) | Draw a line
Loop over a single cell length, over all the cells | 3.641173 | 3.632885 | 1.002281 |
line_wrapped = []
for cell, width in zip(line, self._width):
array = []
for c in cell.split('\n'):
array.extend(textwrap.wrap(unicode(c, 'utf'), width))
line_wrapped.append(array)
max_cell_lines = reduce(max, map(len, line_wrapped))
... | def _splitit(self, line, isheader) | Split each element of line to fit the column width
Each element is turned into a list, result of the wrapping of the
string to the desired width | 2.785357 | 2.752198 | 1.012048 |
return round(start + (end - start) * value / maximum, 2) | def transition(value, maximum, start, end) | Transition between two values.
:param value: Current iteration.
:param maximum: Maximum number of iterations.
:param start: Start value.
:param end: End value.
:returns: Transitional value. | 3.639852 | 8.140024 | 0.447155 |
if current < 0 or current > 1.0:
raise ValueError("current value %s is out of bounds (0.0-1.0)", current)
if target < 0 or target > 1.0:
raise ValueError("target value %s is out of bounds (0.0-1.0)", target)
return int(abs((current * max_steps) - (target * max_steps))) | def steps(current, target, max_steps) | Steps between two values.
:param current: Current value (0.0-1.0).
:param target: Target value (0.0-1.0).
:param max_steps: Maximum number of steps. | 2.280312 | 2.175738 | 1.048064 |
if self.cmd_2 is not None:
cmd = [self.cmd_1, self.cmd_2]
else:
cmd = [self.cmd_1, self.SUFFIX_BYTE]
if bridge.version < self.BRIDGE_SHORT_VERSION_MIN:
cmd.append(self.BRIDGE_LONG_BYTE)
return bytearray(cmd) | def get_bytes(self, bridge) | Gets the full command as bytes.
:param bridge: The bridge, to which the command should be sent. | 4.708678 | 4.49736 | 1.046987 |
brightness = math.ceil(brightness * self.brightness_steps)
return brightness + self.BRIGHTNESS_OFFSET | def convert_brightness(self, brightness) | Convert the brightness from decimal percent (0.0-1.0)
to byte representation for use in commands.
:param brightness: The brightness from in decimal percent (0.0-1.0).
:return: The brightness in byte representation. | 8.68155 | 11.315875 | 0.767201 |
return CommandLegacy(cmd_1, cmd_2,
self._group_number, select, select_command) | def _build_command(self, cmd_1, cmd_2=None,
select=False, select_command=None) | Constructs the complete command.
:param cmd_1: Light command 1.
:param cmd_2: Light command 2.
:param select: If command requires selection.
:param select_command: Selection command bytes.
:return: The complete command. | 9.181025 | 11.857416 | 0.774285 |
return self._build_command(self.NIGHT_BYTES[self._group_number - 1],
select=True, select_command=self.off()) | def night_light(self) | Build command for turning the led to night light mode.
:return: The command. | 21.222891 | 18.488054 | 1.147925 |
return self._build_command(self._offset(0xC6),
select=True, select_command=self.off()) | def night_light(self) | Build command for turning the led to night light mode.
:return: The command. | 29.889427 | 27.184473 | 1.099504 |
return self._build_command(self._offset(0xC5),
select=True, select_command=self.on()) | def white(self) | Build command for turning the led into white mode.
:return: The command. | 40.413864 | 30.18697 | 1.338785 |
return self._build_command(0x40, self.convert_hue(hue),
select=True, select_command=self.on()) | def hue(self, hue) | Build command for setting the hue of the led.
:param hue: Value to set (0.0-1.0).
:return: The command. | 15.597496 | 13.792531 | 1.130865 |
return self._build_command(0x4E, self.convert_brightness(brightness),
select=True, select_command=self.on()) | def brightness(self, brightness) | Build command for setting the brightness of the led.
:param brightness: Value to set (0.0-1.0).
:return: The command. | 17.888817 | 15.621396 | 1.145148 |
self.votable_URL= votable_URL
self.votable_options= votable_options
self.votable_from_URL_flag= not self.votable_from_URL_flag | def add_catalog_from_URL(self, votable_URL, votable_options={}) | load a VOTable table from an url and load its data into the widget
Args:
votable_URL: string url
votable_options: dictionary object | 3.235134 | 3.16292 | 1.022832 |
self.moc_URL = moc_URL
self.moc_options = moc_options
self.moc_from_URL_flag = not self.moc_from_URL_flag | def add_moc_from_URL(self, moc_URL, moc_options = {}) | load a MOC from a URL and display it in Aladin Lite widget
Arguments:
moc_URL: string url
moc_options: dictionary object | 2.603529 | 2.780225 | 0.936445 |
self.moc_dict = moc_dict
self.moc_options = moc_options
self.moc_from_dict_flag = not self.moc_from_dict_flag | def add_moc_from_dict(self, moc_dict, moc_options = {}) | load a MOC from a dict object and display it in Aladin Lite widget
Arguments:
moc_dict: the dict containing the MOC cells. Key are the HEALPix orders,
values are the pixel indexes, eg: {"1":[1,2,4], "2":[12,13,14,21,23,25]}
moc_options: dictionary object | 2.589789 | 2.816425 | 0.919531 |
# theses library must be installed, and are used in votable operations
# http://www.astropy.org/
import astropy
table_array = table.__array__()
self.table_keys= table.keys()
table_columns= []
for i in range(0,len(table.columns[0])):
... | def add_table(self, table) | load a VOTable -already accessible on the python side- into the widget
Args:
table: votable object | 6.410112 | 5.884968 | 1.089235 |
self.listener_type= listener_type
if listener_type == 'objectHovered':
self.listener_callback_source_hover= callback
elif listener_type == 'objectClicked':
self.listener_callback_source_click= callback
elif listener_type == 'click':
self.liste... | def add_listener(self, listener_type, callback) | add a listener to the widget
Args:
listener_type: string that can either be 'objectHovered' or 'objClicked'
callback: python function | 3.036137 | 2.703866 | 1.122887 |
if content.get('event', '').startswith('callback'):
if content.get('type') == 'objectHovered':
result= self.listener_callback_source_hover(content.get('data'))
elif content.get('type') == 'objectClicked':
result= self.listener_callback_source_clic... | def handle_aladin_event(self, _, content, buffers) | used to collect json objects that are sent by the js-side of the application by using the send() method | 2.951567 | 2.944778 | 1.002305 |
try:
accounts = APPLICATION.accounts.search({'email': self.cleaned_data['email']})
if len(accounts):
msg = 'User with that email already exists.'
raise forms.ValidationError(msg)
except Error as e:
raise forms.ValidationError(s... | def clean_email(self) | Check if email exists on Stormpath.
The email address is unique across all Stormpath applications.
The username is only unique within a Stormpath application. | 3.762055 | 3.475453 | 1.082465 |
password1 = self.cleaned_data.get('new_password1')
password2 = self.cleaned_data.get('new_password2')
try:
directory = APPLICATION.default_account_store_mapping.account_store
directory.password_policy.strength.validate_password(password2)
except ValueErr... | def clean_new_password2(self) | Check if passwords match and are valid. | 3.333352 | 3.24111 | 1.02846 |
dir = CLIENT.directories.create({
'name': APPLICATION.name + '-' + provider,
'provider': {
'client_id': settings.STORMPATH_SOCIAL[provider.upper()]['client_id'],
'client_secret': settings.STORMPATH_SOCIAL[provider.upper()]['client_secret'],
'redirect_uri': re... | def create_provider_directory(provider, redirect_uri) | Helper function for creating a provider directory | 3.80742 | 3.789095 | 1.004836 |
canvas.setStrokeColorRGB(0.9, 0.5, 0.2)
canvas.setFillColorRGB(0.2, 0.2, 0.2)
canvas.setFont('Helvetica', 16)
canvas.drawString(18 * cm, -1 * cm, 'Invoice')
canvas.drawInlineImage(settings.INV_LOGO, 1 * cm, -1 * cm, 250, 16)
canvas.setLineWidth(4)
canvas.line(0, -1.25 * cm, 21.7 * cm, -... | def draw_header(canvas) | Draws the invoice header | 3.120062 | 2.893039 | 1.078472 |
business_details = (
u'COMPANY NAME LTD',
u'STREET',
u'TOWN',
U'COUNTY',
U'POSTCODE',
U'COUNTRY',
u'',
u'',
u'Phone: +00 (0) 000 000 000',
u'Email: example@example.com',
u'Website: www.example.com',
u'Reg No: 000000... | def draw_address(canvas) | Draws the business address | 3.644464 | 3.524876 | 1.033927 |
note = (
u'Bank Details: Street address, Town, County, POSTCODE',
u'Sort Code: 00-00-00 Account No: 00000000 (Quote invoice number).',
u'Please pay via bank transfer or cheque. All payments should be made in CURRENCY.',
u'Make cheques payable to Company Name Ltd.',
)
tex... | def draw_footer(canvas) | Draws the invoice footer | 9.207507 | 8.487532 | 1.084827 |
canvas = Canvas(buffer, pagesize=A4)
canvas.translate(0, 29.7 * cm)
canvas.setFont('Helvetica', 10)
canvas.saveState()
header_func(canvas)
canvas.restoreState()
canvas.saveState()
footer_func(canvas)
canvas.restoreState()
canvas.saveState()
address_func(canvas)
ca... | def draw_pdf(buffer, invoice) | Draws the invoice | 1.896206 | 1.894004 | 1.001163 |
mod_name, class_name = name.rsplit('.', 1)
mod = __import__(mod_name)
inst = getattr(mod, class_name)()
sections = cmdln.man_sections_from_cmdln(inst)
sys.stdout.write(''.join(sections)) | def mkmanpage(name) | Return man page content for the given `cmdln.Cmdln` subclass name. | 4.242525 | 3.455212 | 1.227862 |
self.check_and_delete_test_cookie()
login(self.request, form.get_user())
return super(LoginView, self).form_valid(form) | def form_valid(self, form) | The user has provided valid credentials (this was checked in AuthenticationForm.is_valid()). So now we
can check the test cookie stuff and log him in. | 4.222056 | 2.365641 | 1.784741 |
self.set_test_cookie()
return super(LoginView, self).form_invalid(form) | def form_invalid(self, form) | The user has provided invalid credentials (this was checked in AuthenticationForm.is_valid()). So now we
set the test cookie again and re-render the form with errors. | 4.416547 | 2.091912 | 2.111249 |
self.set_test_cookie()
return super(LoginView, self).get(request, *args, **kwargs) | def get(self, request, *args, **kwargs) | Same as django.views.generic.edit.ProcessFormView.get(), but adds test cookie stuff | 4.4648 | 2.395875 | 1.863537 |
# to unicode
uri_parts = [unicode(x) for x in uri_parts]
# and encoded
uri_parts = [urllib.quote(x) for x in uri_parts]
# Add enpoint and version
all_uri_parts = [endpoint, api_version, ] + uri_parts
# join parts
url_to_call = "/".join(all_uri_parts)
# add params if any
if... | def build_uri(endpoint, api_version, uri_parts, uri_args={}) | Build the URL using the endpoint, the api version, the uri parts and the args.
:param dict uri_args: parameters to include in the URL.
:param tuple uri_parts: url encoded and `uri_parts` too.
:return: A string that represents the absolute URL of the request
:rtype : str
... | 2.848081 | 2.967277 | 0.95983 |
try:
js_resp = resp.json()
if resp.ok:
if "items" in js_resp.keys():
r = ApiListResponse(js_resp["items"])
else:
r = ApiDictResponse(js_resp)
if "paging" in js_resp.keys():
cursors = js_resp.get("paging", {}).ge... | def wrap_response(resp, api_call) | Wrap the requests response in an `ApiResponse` object
:param object resp: response object provided by the `requests` library.
:param object api_call: Api Call
:return: An `ApiResponse` object that wraps the content of the response.
:rtype: object, list or dict | 2.294844 | 2.346729 | 0.977891 |
action = {
None: "Crush",
"sword": "Swipe",
"spear": "Pierce",
"maul": "Crush",
}.get(opts.weapon, None)
if not action:
print("Conan confused.")
else:
for enemy in enemies:
print("%s %s!" % (... | def do_crush(self, subcmd, opts, *enemies) | ${cmd_name}: crush your enemies!
${cmd_usage}
${cmd_option_list}
C.f. Conan the Barbarian. | 6.075914 | 5.960195 | 1.019415 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_add(self, subcmd, opts, *args) | Put files and directories under version control, scheduling
them for addition to repository. They will be added in next commit.
usage:
add PATH...
${cmd_option_list} | 4.297829 | 4.880997 | 0.880523 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_blame(self, subcmd, opts, *args) | Output the content of specified files or
URLs with revision and author information in-line.
usage:
blame TARGET...
${cmd_option_list} | 4.207954 | 4.900093 | 0.85875 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_cat(self, subcmd, opts, *args) | Output the content of specified files or URLs.
usage:
cat TARGET...
${cmd_option_list} | 4.487568 | 5.45557 | 0.822566 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_checkout(self, subcmd, opts, *args) | Check out a working copy from a repository.
usage:
checkout URL... [PATH]
Note: If PATH is omitted, the basename of the URL will be used as
the destination. If multiple URLs are given each will be checked
out into a sub-directory of PATH, with the name of the sub-di... | 3.955091 | 4.776735 | 0.82799 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_cleanup(self, subcmd, opts, *args) | Recursively clean up the working copy, removing locks, resuming
unfinished operations, etc.
usage:
cleanup [PATH...]
${cmd_option_list} | 4.337741 | 4.587154 | 0.945628 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_commit(self, subcmd, opts, *args) | Send changes from your working copy to the repository.
usage:
commit [PATH...]
A log message must be provided, but it can be empty. If it is not
given by a --message or --file option, an editor will be started.
${cmd_option_list} | 4.00916 | 4.758193 | 0.84258 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_copy(self, subcmd, opts, *args) | Duplicate something in working copy or repository, remembering history.
usage:
copy SRC DST
SRC and DST can each be either a working copy (WC) path or URL:
WC -> WC: copy and schedule for addition (with history)
WC -> URL: immediately commit a copy of WC to... | 4.134017 | 4.235815 | 0.975967 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_delete(self, subcmd, opts, *args) | Remove files and directories from version control.
usage:
1. delete PATH...
2. delete URL...
1. Each item specified by a PATH is scheduled for deletion upon
the next commit. Files, and directories that have not been
committed, are immediately remove... | 4.131067 | 4.446172 | 0.929129 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_diff(self, subcmd, opts, *args) | Display the differences between two paths.
usage:
1. diff [-r N[:M]] [TARGET[@REV]...]
2. diff [-r N[:M]] --old=OLD-TGT[@OLDREV] [--new=NEW-TGT[@NEWREV]] \
[PATH...]
3. diff OLD-URL[@OLDREV] NEW-URL[@NEWREV]
1. Display the changes made to... | 4.014647 | 4.296575 | 0.934383 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_export(self, subcmd, opts, *args) | Create an unversioned copy of a tree.
usage:
1. export [-r REV] URL [PATH]
2. export [-r REV] PATH1 [PATH2]
1. Exports a clean directory tree from the repository specified by
URL, at revision REV if it is given, otherwise at HEAD, into
PATH. If PAT... | 4.370662 | 4.904637 | 0.891128 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_import(self, subcmd, opts, *args) | Commit an unversioned file or tree into the repository.
usage:
import [PATH] URL
Recursively commit a copy of PATH to URL.
If PATH is omitted '.' is assumed. Parent directories are created
as necessary in the repository.
${cmd_option_list} | 4.359921 | 4.893907 | 0.890888 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_info(self, subcmd, opts, *args) | Display information about a file or directory.
usage:
info [PATH...]
Print information about each PATH (default: '.').
${cmd_option_list} | 4.173885 | 5.217373 | 0.799997 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_list(self, subcmd, opts, *args) | List directory entries in the repository.
usage:
list [TARGET...]
List each TARGET file and the contents of each TARGET directory as
they exist in the repository. If TARGET is a working copy path, the
corresponding repository URL will be used.
The ... | 4.311687 | 5.252383 | 0.820901 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_log(self, subcmd, opts, *args) | Show the log messages for a set of revision(s) and/or file(s).
usage:
1. log [PATH]
2. log URL [PATH...]
1. Print the log messages for a local PATH (default: '.').
The default revision range is BASE:1.
2. Print the log messages for the PATHs ... | 4.191847 | 4.684783 | 0.894779 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_merge(self, subcmd, opts, *args) | Apply the differences between two sources to a working copy path.
usage:
1. merge sourceURL1[@N] sourceURL2[@M] [WCPATH]
2. merge sourceWCPATH1@N sourceWCPATH2@M [WCPATH]
3. merge -r N:M SOURCE[@REV] [WCPATH]
1. In the first form, the source URLs are specifi... | 4.068336 | 4.578655 | 0.888544 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_mkdir(self, subcmd, opts, *args) | Create a new directory under version control.
usage:
1. mkdir PATH...
2. mkdir URL...
Create version controlled directories.
1. Each directory specified by a working copy PATH is created locally
and scheduled for addition upon the next commit.... | 4.10849 | 4.735809 | 0.867537 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_move(self, subcmd, opts, *args) | Move and/or rename something in working copy or repository.
usage:
move SRC DST
Note: this subcommand is equivalent to a 'copy' and 'delete'.
SRC and DST can both be working copy (WC) paths or URLs:
WC -> WC: move and schedule for addition (with histo... | 4.094527 | 4.193481 | 0.976403 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_propdel(self, subcmd, opts, *args) | Remove PROPNAME from files, dirs, or revisions.
usage:
1. propdel PROPNAME [PATH...]
2. propdel PROPNAME --revprop -r REV [URL]
1. Removes versioned props in working copy.
2. Removes unversioned remote prop on repos revision.
${cmd_option_list} | 4.351571 | 4.312963 | 1.008952 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_propedit(self, subcmd, opts, *args) | Edit property PROPNAME with an external editor on targets.
usage:
1. propedit PROPNAME PATH...
2. propedit PROPNAME --revprop -r REV [URL]
1. Edits versioned props in working copy.
2. Edits unversioned remote prop on repos revision.
${cmd_option_list} | 4.492198 | 4.467299 | 1.005574 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_propget(self, subcmd, opts, *args) | Print value of PROPNAME on files, dirs, or revisions.
usage:
1. propget PROPNAME [PATH...]
2. propget PROPNAME --revprop -r REV [URL]
1. Prints versioned prop in working copy.
2. Prints unversioned remote prop on repos revision.
By default, this... | 4.14998 | 5.204885 | 0.797324 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_proplist(self, subcmd, opts, *args) | List all properties on files, dirs, or revisions.
usage:
1. proplist [PATH...]
2. proplist --revprop -r REV [URL]
1. Lists versioned props in working copy.
2. Lists unversioned remote props on repos revision.
${cmd_option_list} | 4.248294 | 4.65431 | 0.912766 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_propset(self, subcmd, opts, *args) | Set PROPNAME to PROPVAL on files, dirs, or revisions.
usage:
1. propset PROPNAME [PROPVAL | -F VALFILE] PATH...
2. propset PROPNAME --revprop -r REV [PROPVAL | -F VALFILE] [URL]
1. Creates a versioned, local propchange in working copy.
2. Creates an unversioned,... | 4.281115 | 4.475679 | 0.956529 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_resolved(self, subcmd, opts, *args) | Remove 'conflicted' state on working copy files or directories.
usage:
resolved PATH...
Note: this subcommand does not semantically resolve conflicts or
remove conflict markers; it merely removes the conflict-related
artifact files and allows PATH to be committed a... | 4.14202 | 5.163795 | 0.802127 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_revert(self, subcmd, opts, *args) | Restore pristine working copy file (undo most local edits).
usage:
revert PATH...
Note: this subcommand does not require network access, and resolves
any conflicted states. However, it does not restore removed directories.
${cmd_option_list} | 3.945341 | 4.366678 | 0.903511 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_status(self, subcmd, opts, *args) | Print the status of working copy files and directories.
usage:
status [PATH...]
With no args, print only locally modified items (no network access).
With -u, add working revision and server out-of-date information.
With -v, print full revision information on every i... | 4.127584 | 4.75558 | 0.867945 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_switch(self, subcmd, opts, *args) | Update the working copy to a different URL.
usage:
1. switch URL [PATH]
2. switch --relocate FROM TO [PATH...]
1. Update the working copy to mirror a new URL within the repository.
This behaviour is similar to 'svn update', and is the way to
move a... | 4.209391 | 3.942973 | 1.067568 |
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | def do_update(self, subcmd, opts, *args) | Bring changes from the repository into the working copy.
usage:
update [PATH...]
If no revision given, bring working copy up-to-date with HEAD rev.
Else synchronize working copy to revision given by -r.
For each updated item a line will start with a charact... | 4.167444 | 4.886248 | 0.852892 |
# Get version file *type*.
version_file_type = None
match = re.compile("^([a-z]+):(.*)$").search(version_file)
if match:
version_file = match.group(2)
version_file_type = match.group(1)
aliases = {
"js": "javascript"
}
if version_file_type in alia... | def _parse_version_file(version_file) | Get version info from the given file. It can be any of:
Supported version file types (i.e. types of files from which we know
how to parse the version string/number -- often by some convention):
- json: use the "version" key
- javascript: look for a `var VERSION = "1.2.3";` or
`var VERSION = '1.2.... | 2.331893 | 2.211281 | 1.054544 |
if not exists(changes_path):
raise Error("changelog file '%s' not found" % changes_path)
content = codecs.open(changes_path, 'r', 'utf-8').read()
parser = re.compile(
r'^##\s*(?P<verline>[^\n]*?)\s*$(?P<body>.*?)(?=^##|\Z)',
re.M | re.S)
sections = parser.findall(content)
... | def parse_changelog(changes_path) | Parse the given changelog path and return `(content, parsed, nyr)`
where `nyr` is the ' (not yet released)' marker and `parsed` looks like:
[{'body': u'\n(nothing yet)\n\n',
'verline': u'restify 1.0.1 (not yet released)',
'version': u'1.0.1'}, # version is parsed out for top section ... | 3.896406 | 3.232847 | 1.205255 |
log.debug("running '%s'", cmd)
fixed_cmd = cmd
if sys.platform == "win32" and cmd.count('"') > 2:
fixed_cmd = '"' + cmd + '"'
retval = os.system(fixed_cmd)
if hasattr(os, "WEXITSTATUS"):
status = os.WEXITSTATUS(retval)
else:
status = retval
if status:
rai... | def run(cmd) | Run the given command.
Raises OSError is the command returns a non-zero exit status. | 2.735198 | 2.758725 | 0.991472 |
redirect_field_name = kwargs.get("redirect_field_name", "next")
next = request.POST.get(redirect_field_name,
request.GET.get(redirect_field_name, ''))
if not next:
# try the session if available
if hasattr(request, "session"):
session_key_value = ... | def default_redirect(request, fallback_url, **kwargs) | Evaluates a redirect url by consulting GET, POST and the session. | 3.485181 | 3.430129 | 1.01605 |
if errors1 is None:
return errors2
elif errors2 is None:
return errors1
if isinstance(errors1, list):
if not errors1:
return errors2
if isinstance(errors2, list):
return errors1 + errors2
elif isinstance(errors2, dict):
retur... | def merge_errors(errors1, errors2) | Deeply merges two error messages. Error messages can be
string, list of strings or dict of error messages (recursively).
Format is the same as accepted by :exc:`ValidationError`.
Returns new error messages. | 1.523755 | 1.506315 | 1.011578 |
self.errors = merge_errors(self.errors, self._make_error(path, error)) | def add_error(self, path, error) | Add error message for given field path.
Example: ::
builder = ValidationErrorBuilder()
builder.add_error('foo.bar.baz', 'Some error')
print builder.errors
# => {'foo': {'bar': {'baz': 'Some error'}}}
:param str path: '.'-separated list of field names
... | 5.485658 | 7.196204 | 0.762299 |
# The highest acceptable factor will be the square root of the size.
highest_acceptable_factor = int(math.sqrt(SIZE))
# Too high a factor (eg SIZE/2) and the interval is too small, too
# low (eg 2) and the period is too small.
# We would prefer it to be lower than the number of VALID_CHARS, bu... | def find_suitable_period() | Automatically find a suitable period to use.
Factors are best, because they will have 1 left over when
dividing SIZE+1.
This only needs to be run once, on import. | 6.417281 | 6.007739 | 1.068169 |
# Convert to a (shorter) string for human consumption
string = ""
# The length of the string can be determined by STRING_LENGTH or by how many
# characters are necessary to present a base 30 representation of SIZE.
while STRING_LENGTH and len(string) <= STRING_LENGTH \
or len(VALID_... | def friendly_number(num) | Convert a base 10 number to a base X string.
Charcters from VALID_CHARS are chosen, to convert the number
to eg base 24, if there are 24 characters to choose from.
Use valid chars to choose characters that are friendly, avoiding
ones that could be confused in print or over the phone. | 11.356159 | 11.29051 | 1.005815 |
def wrapped(*args):
try:
return function(*args)
except FedexError:
_login(*args)
return function(*args)
return wrapped | def authenticated(function) | Re-authenticate if session expired. | 5.945454 | 6.576214 | 0.904085 |
session.get(LOGIN_REFERER)
resp = session.post(LOGIN_URL, {
'user': session.auth.username,
'pwd': session.auth.password
}, headers={
'Referer': LOGIN_REFERER,
'X-Requested-With': 'XMLHttpRequest'
})
if resp.status_code != 200:
raise FedexError('could not ... | def _login(session) | Login to Fedex Delivery Manager. | 2.938006 | 2.702145 | 1.087287 |
resp = session.post(TRACKING_URL, {
'data': json.dumps(SHIPMENT_LIST_REQUEST),
'action': SHIPMENT_LIST_ACTION,
'format': SHIPMENT_LIST_FORMAT,
'locale': session.auth.locale,
'version': 1
})
data = resp.json().get('ShipmentListLightResponse')
if not data.get('... | def get_packages(session) | Get packages. | 4.374025 | 4.310999 | 1.01462 |
if mapper is None:
mapper = identity
def hinter(data):
return mapper(data.get(key))
return hinter | def dict_value_hint(key, mapper=None) | Returns a function that takes a dictionary and returns value of
particular key. The returned value can be optionally processed by `mapper`
function.
To be used as a type hint in :class:`OneOf`. | 6.064955 | 6.410867 | 0.946043 |
if validate is None:
validate = []
if not is_sequence(validate):
validate = [validate]
class ValidatedSubtype(base_type):
if name is not None:
__name__ = name
def __init__(self, *args, **kwargs):
super(ValidatedSubtype, self).__init__(*args, **k... | def validated_type(base_type, name=None, validate=None) | Convenient way to create a new type by adding validation to existing type.
Example: ::
Ipv4Address = validated_type(
String, 'Ipv4Address',
# regexp simplified for demo purposes
Regexp('^\d+\.\d+\.\d+\.\d+$', error='Invalid IP address')
)
Percentage = v... | 2.339448 | 2.446057 | 0.956416 |
try:
self.load(data, context)
return None
except ValidationError as ve:
return ve.messages | def validate(self, data, context=None) | Takes serialized data and returns validation errors or None.
:param data: Data to validate.
:param context: Context data.
:returns: validation errors or None | 5.574319 | 6.051416 | 0.921159 |
errors_builder = ValidationErrorBuilder()
for validator in self.validators:
try:
validator(data, context)
except ValidationError as ve:
errors_builder.add_errors(ve.messages)
errors_builder.raise_errors()
return data | def load(self, data, context=None) | Deserialize data from primitive types. Raises
:exc:`~lollipop.errors.ValidationError` if data is invalid.
:param data: Data to deserialize.
:param context: Context data.
:returns: Loaded data
:raises: :exc:`~lollipop.errors.ValidationError` | 3.857431 | 4.240819 | 0.909596 |
return self.field_type.load(data.get(name, MISSING), context=context) | def load(self, name, data, context=None) | Deserialize data from primitive types. Raises
:exc:`~lollipop.errors.ValidationError` if data is invalid.
:param str name: Name of attribute to deserialize.
:param data: Raw data to get value to deserialize from.
:param kwargs: Same keyword arguments as for :meth:`Type.load`.
:r... | 8.265078 | 11.159741 | 0.740616 |
if obj is None:
raise ValueError('Load target should not be None')
value = data.get(name, MISSING)
if value is MISSING:
return
target = self.get_value(name, obj, context=context)
if target is not None and target is not MISSING \
... | def load_into(self, obj, name, data, inplace=True, context=None) | Deserialize data from primitive types updating existing object.
Raises :exc:`~lollipop.errors.ValidationError` if data is invalid.
:param obj: Object to update with deserialized data.
:param str name: Name of attribute to deserialize.
:param data: Raw data to get value to deserialize fr... | 2.832724 | 3.330718 | 0.850485 |
value = self.get_value(name, obj, context=context)
return self.field_type.dump(value, context=context) | def dump(self, name, obj, context=None) | Serialize data to primitive types. Raises
:exc:`~lollipop.errors.ValidationError` if data is invalid.
:param str name: Name of attribute to serialize.
:param obj: Application object to extract serialized value from.
:returns: Serialized data.
:raises: :exc:`~lollipop.errors.Vali... | 3.877206 | 5.376782 | 0.721102 |
if obj is None:
raise ValueError('Load target should not be None')
if data is MISSING:
return
if data is None:
self._fail('required')
if not is_mapping(data):
self._fail('invalid', data=data)
errors_builder = Validation... | def load_into(self, obj, data, inplace=True, *args, **kwargs) | Load data and update existing object.
:param obj: Object to update with deserialized data.
:param data: Raw data to get value to deserialize from.
:param bool inplace: If True update data inplace;
otherwise - create new data.
:param kwargs: Same keyword arguments as for :met... | 2.530549 | 2.569703 | 0.984763 |
try:
self.load_into(obj, data, inplace=False, *args, **kwargs)
return None
except ValidationError as ve:
return ve.messages | def validate_for(self, obj, data, *args, **kwargs) | Takes target object and serialized data, tries to update that object
with data and validate result. Returns validation errors or None.
Object is not updated.
:param obj: Object to check data validity against. In case the data is
partial object is used to get the rest of data from.
... | 5.605179 | 5.03556 | 1.113119 |
return [item for item in api_response if item[ISCOUNTRY]==is_country] | def filter_country_locations(api_response, is_country=True) | Filter the response to only include the elements that are countries.
This uses the 'api_response' object as input. Plain `list`s are also
valid, but they must contain the location elements, not the `items` wrapper. | 6.985935 | 7.619967 | 0.916793 |
# Recupere les facture de l annee
relative_invoices = Invoice.objects.filter(invoice_date__year=self.invoice_date.year)
# on prend le numero le plus eleve du champs number, sinon on met 0
last_number = relative_invoices.aggregate(Max('number'))['number__max'] or 0
retu... | def _get_next_number(self) | Returnes next invoice number - reset yearly.
.. warning::
This is only used to prepopulate ``number`` field on saving new invoice.
To get invoice number always use ``number`` field.
.. note::
To get invoice full number use ``invoice_id`` field.
:return: s... | 6.663942 | 5.835373 | 1.141991 |
try:
if inspect.ismethod(func):
arg_count = len(inspect.getargspec(func).args) - 1
elif inspect.isfunction(func):
arg_count = len(inspect.getargspec(func).args)
elif inspect.isclass(func):
arg_count = len(inspect.getargspec(func.__init__).args) - 1
... | def make_context_aware(func, numargs) | Check if given function has no more arguments than given. If so, wrap it
into another function that takes extra argument and drops it.
Used to support user providing callback functions that are not context aware. | 1.975988 | 1.894726 | 1.042889 |
return make_context_aware(func, len(args))(*args + (context,)) | def call_with_context(func, context, *args) | Check if given function has more arguments than given. Call it with context
as last argument or without it. | 12.693566 | 12.990664 | 0.97713 |
return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s) | def to_snake_case(s) | Converts camel-case identifiers to snake-case. | 2.151369 | 2.197531 | 0.978994 |
if not (settings.STORMPATH_ID and settings.STORMPATH_SECRET):
raise ImproperlyConfigured('Both STORMPATH_ID and STORMPATH_SECRET must be specified in settings.py.')
if not settings.STORMPATH_APPLICATION:
raise ImproperlyConfigured('STORMPATH_APPLICATION must be specified in settings.py.') | def validate_settings(settings) | Ensure all user-supplied settings exist, or throw a useful error message.
:param obj settings: The Django settings object. | 3.001021 | 2.826347 | 1.061802 |
directory = APPLICATION.default_account_store_mapping.account_store
verif_email = directory.account_creation_policy.verification_email_status
return verif_email == AccountCreationPolicy.EMAIL_STATUS_DISABLED | def get_default_is_active() | Stormpath user is active by default if e-mail verification is
disabled. | 17.016853 | 10.732801 | 1.5855 |
if sync_groups:
sp_groups = [g.name for g in APPLICATION.groups]
db_groups = set(Group.objects.all().values_list('name', flat=True))
missing_from_db = set(sp_groups).difference(db_groups)
if missing_from_db:
groups_to_create = []
... | def sync_accounts_from_stormpath(self, sync_groups=True) | :arg sync_groups: WARNING!!! Groups will be deleted from stormpath
if not present locally when user logs in!
Sync accounts from stormpath -> local database.
This may take a long time, depending on how many users you have in your
Stormpath application. It also mak... | 2.39264 | 2.391425 | 1.000508 |
APPLICATION = get_application()
try:
result = APPLICATION.authenticate_account(username, password)
return result.account
except Error as e:
log.debug(e)
return None | def _stormpath_authenticate(self, username, password) | Check if Stormpath authentication works
:param username: Can be actual username or email
:param password: Account password
Returns an account object if successful or None otherwise. | 5.761708 | 4.953197 | 1.16323 |
db_groups = set(Group.objects.all().values_list('name', flat=True))
missing_from_db = set(sp_groups).difference(db_groups)
missing_from_sp = db_groups.difference(sp_groups)
return (missing_from_db, missing_from_sp) | def _get_group_difference(self, sp_groups) | Helper method for gettings the groups that
are present in the local db but not on stormpath
and the other way around. | 2.409959 | 2.333426 | 1.032799 |
APPLICATION = get_application()
sp_groups = [g.name for g in APPLICATION.groups]
missing_from_db, missing_from_sp = self._get_group_difference(sp_groups)
if missing_from_db:
groups_to_create = []
for g_name in missing_from_db:
groups_to_... | def _mirror_groups_from_stormpath(self) | Helper method for saving to the local db groups
that are missing but are on Stormpath | 3.260642 | 3.141033 | 1.038079 |
if username is None:
UserModel = get_user_model()
username = kwargs.get(UserModel.USERNAME_FIELD)
account = self._stormpath_authenticate(username, password)
if account is None:
return None
return self._create_or_get_user(account) | def authenticate(self, username=None, password=None, **kwargs) | The authenticate method takes credentials as keyword arguments,
usually username/email and password.
Returns a user model if the Stormpath authentication was successful or
None otherwise. It expects three variable to be defined in Django
settings: \n
STORMPATH_ID = "apiKeyId... | 3.453369 | 3.336473 | 1.035036 |
'''
Returns a list of pairs (train_context, test_context), one for each cross-validation fold.
The split is stratified.
:param context: DBContext to be split
:param folds: number of folds
:param random_seed: random seed to be used
:return: returns a list of (train_context,... | def cv_split(context, folds=10, random_seed=None) | Returns a list of pairs (train_context, test_context), one for each cross-validation fold.
The split is stratified.
:param context: DBContext to be split
:param folds: number of folds
:param random_seed: random seed to be used
:return: returns a list of (train_context, test_contex... | 3.022662 | 2.11035 | 1.432304 |
if max_width not in (1, 2, 4):
raise ValueError('max_width should be 1, 2 or 4')
if target is None:
target = pwnypack.target.target
addrs = []
cmds = []
piece_writes = []
for write in writes:
if len(write) == 2:
addr, value = write
width =... | def fmtstring(offset, writes, written=0, max_width=2, target=None) | Build a format string that writes given data to given locations. Can be
used easily create format strings to exploit format string bugs.
`writes` is a list of 2- or 3-item tuples. Each tuple represents a memory
write starting with an absolute address, then the data to write as an
integer and finally th... | 2.976484 | 2.827544 | 1.052674 |
if not HAVE_CAPSTONE:
raise NotImplementedError('pwnypack requires capstone to find ROP gadgets')
if not isinstance(elf, pwnypack.elf.ELF):
elf = pwnypack.elf.ELF(elf)
matches = []
gadgets = []
if isinstance(gadget, six.binary_type):
gadget = re.compile(re.escape(gad... | def find_gadget(elf, gadget, align=1, unique=True) | Find a ROP gadget in a the executable sections of an ELF executable or
library. The ROP gadget can be either a set of bytes for an exact match
or a (bytes) regular expression. Once it finds gadgets, it uses the
capstone engine to verify if the gadget consists of valid instructions
and doesn't contain an... | 3.253719 | 2.895545 | 1.123698 |
try:
pwnypack.util.reghex(args.gadget)
args.mode = 'reghex'
except SyntaxError:
args.mode = 'asm'
elf = pwnypack.elf.ELF(args.file)
if args.mode == 'reghex':
try:
gadget = pwnypack.util.reghex(args.gadget)
except SyntaxError:
... | def gadget_app(_parser, cmd, args): # pragma: no cover
parser = argparse.ArgumentParser(
prog=_parser.prog,
description=_parser.description,
)
parser.add_argument('file', help='ELF file to find gadgets in')
parser.add_argument('gadget', help='the assembler source or reghex express... | Find ROP gadgets in an ELF binary. | 2.693445 | 2.618605 | 1.02858 |
from django.core.exceptions import ImproperlyConfigured
if import_path is None:
raise ImproperlyConfigured('No class path specified.')
try:
dot = import_path.rindex('.')
except ValueError:
raise ImproperlyConfigured("%s isn't a module." % import_path)
module, classname =... | def get_class(import_path=None) | Largely based on django.core.files.storage's get_storage_class | 1.540843 | 1.494363 | 1.031104 |
logger.debug('Serving {0} to {1}'.format(path, request.user))
if not permissions.has_read_permission(request, path):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found')
return server.serve(request, path=path) | def serve_private_file(request, path) | Serve private files to users with read permission. | 3.647448 | 3.293193 | 1.107572 |
if args.symbol:
if args.exact:
if symbol.name != args.symbol:
continue
else:
if args.symbol.lower() not in symbol.name.lower():
continue
if symbol.shndx == symbol.SpecialSection.undef:
shndx = 'U... | def symbols_app(parser, _, args): # pragma: no cover
parser.add_argument('file', help='ELF file to list the symbols of')
parser.add_argument('symbol', nargs='?', help='show only this symbol')
parser.add_argument('--exact', '-e', action='store_const', const=True, help='filter by exact symbol name')
... | List ELF symbol table. | 2.013459 | 1.868821 | 1.077396 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.