code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return self.connection.copy(self, other,
recursive=recursive,
ignore=ignore,
followlinks=followlinks) | def copy(self, other, recursive=False, ignore=None,
followlinks=True) | copy: copy self to other
@type other: URI
@param other: the path to copy itself over.
What will really happen depends on the backend.
Note that file properties are only copied when self and other are
located in the same backend, i.e. it is not possible to copy
permissi... | 3.113632 | 3.844115 | 0.809974 |
if self.connection.islink(self):
return self.connection.removefile(self)
if not self.connection.exists(self):
raise FileDoesNotExistError(str(self))
if self.connection.isdir(self):
if recursive:
return remove_dir_recursively(self.con... | def remove(self, recursive=False) | remove: shortcut method to remove self.
if 'self' represents a file, the backends 'removefile' method id used.
if 'self' represents a directory, it will recursivly removed, if
the options string contains 'r'. Otherwise, the backends 'removedir'
method is used. | 2.669916 | 2.468705 | 1.081505 |
return self.connection.open(self, options, mimetype) | def open(self, options=None, mimetype='application/octet-stream') | open: return a file like object for self.
The method can be used with the 'with' statment. | 5.747858 | 4.747556 | 1.210698 |
return self.connection.isexec(self, mode) | def isexec(self, mode=stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | isexec:
@rtype: bool
@return: Indicates whether the path points to a file or folder
which has the executable flag set.
Note that on systems which do not support executables flags the
result may be unpredicatable. On Windows the value is determined
by the file extension... | 11.496001 | 20.083513 | 0.57241 |
return self.connection.walk(self, topdown=topdown, followlinks=followlinks) | def walk(self, topdown=True, followlinks=True) | walk: walk the filesystem (just like os.walk).
Use like:
path = URI('/some/dir')
for root, dirs, files in path.walk():
do_something()
root will be an URI object. | 4.007306 | 5.720645 | 0.700499 |
return self.connection.info(self, set_info=set_info, followlinks=followlinks) | def info(self, set_info=None, followlinks=True) | info: backend info about self (probably not implemented for
all backends. The result will be backend specific).
@param set_info: If not None, this data will be set on self.
@param followlinks: If True, symlinks will be followed. If
False, the info of the symlink itself will be... | 3.8041 | 5.295763 | 0.718329 |
hash_ = hashlib.md5()
with self.open("rb") as inf:
block = inf.read(4096)
while block:
hash_.update(block)
block = inf.read(4096)
return hash_.hexdigest() | def md5(self) | Returns the md5-sum of this file. This is of course potentially
expensive! | 2.439416 | 2.198346 | 1.10966 |
return self.connection.lock(self, fail_on_lock, cleanup) | def lock(self, fail_on_lock=False, cleanup=False) | Allows to lock a file via abl.util.LockFile, with the
same parameters there.
Returns an opened, writable file. | 4.946064 | 7.984685 | 0.619444 |
self.connection._manipulate(self, *args, **kwargs) | def _manipulate(self, *args, **kwargs) | This is a semi-private method. It's current use is to
manipulate memory file system objects so that
you can create certain conditions, to provoke
errors that otherwise won't occur. | 7.098418 | 7.485721 | 0.948261 |
if source.isfile():
source.copy(destination)
source.remove()
else:
source.copy(destination, recursive=True)
source.remove('r') | def move(self, source, destination) | the semantic should be like unix 'mv' command | 5.007247 | 4.315104 | 1.1604 |
if hasattr(args, 'pythonpath'):
if args.pythonpath:
sys.path.insert(0, args.pythonpath) | def handle_default_args(args) | Include handling of any default arguments that all commands should
implement here (for example, specifying the pythonpath). | 3.274504 | 2.892484 | 1.132074 |
if self._parser is None:
apkw = {
'description': self.description,
'epilog': self.epilog,
}
self._parser = argparse.ArgumentParser(**apkw)
# For Python 3 add version as a default command
if self.version:
... | def parser(self) | Instantiates the argparse parser | 3.789511 | 3.463677 | 1.094072 |
if self._subparsers is None:
apkw = {
'title': 'commands',
'description': 'Commands for the %s program' % self.parser.prog,
}
self._subparsers = self.parser.add_subparsers(**apkw)
return self._subparsers | def subparsers(self) | Insantiates the subparsers for all commands | 3.792589 | 3.663814 | 1.035148 |
command = command()
if command.name in self.commands:
raise ConsoleError(
"Command %s already registered!" % command.name
)
command.create_parser(self.subparsers)
self.commands[command.name] = command | def register(self, command) | Registers a command with the program | 3.778016 | 3.479571 | 1.08577 |
## If we have a parser, use it to exit
if self._parser:
if code > 0:
self.parser.error(message)
else:
self.parser.exit(code, message)
## Else we are exiting before parser creation
else:
if message is not None:... | def exit(self, code=0, message=None) | Exit the console program sanely. | 3.343385 | 3.405267 | 0.981828 |
# Ensure that we have commands registered
if not self.commands or self._parser is None:
raise NotImplementedError(
"No commands registered with this program!"
)
# Handle input from the command line
args = self.parser.parse_args() ... | def execute(self) | Entry point to the execution of the program. | 4.390109 | 4.276019 | 1.026681 |
if observer_name is not None:
observer = STDLibLogObserver(name=observer_name)
globalLogBeginner.beginLoggingTo([observer])
if flask_app is None:
flask_app = create_app(debug=debug)
# Create a Twisted Web resource for our WebSocket server
ws_factory = WebSocketServerFactory... | def create_server(
host="localhost", port=5000, debug=False,
observer_name="twisted", flask_app=None
) | Create and setup twisted server
(only need to do a reactor.run() after)
:param host: Host address to bind to (default: localhost)
:type host: str
:param port: Port to bind to (default: 5000)
:type port: int
:param debug: Should use debug mode (default: False)
:type debug: bool
:param ob... | 3.681308 | 3.619095 | 1.01719 |
r = self.yandex_translate_request("getLangs", "")
self.handle_errors(r)
return r.json()["dirs"] | def get_lang_array(self) | gets supported langs as an array | 13.268682 | 9.913032 | 1.338509 |
r = self.yandex_translate_request("getLangs")
self.handle_errors(r)
return r.json()["langs"] | def get_lang_dict(self) | gets supported langs as an dictionary | 9.725193 | 7.501727 | 1.296394 |
encodedtext = urllib.parse.quote(text)
args = "&text=" + encodedtext
if hint is not None:
args += "&hint=" + hint
r = self.yandex_translate_request("detect", args)
self.handle_errors(r)
return r.json()["lang"] | def detect_language(self, text: str, hint: str = None) | Detects the language of a text
:param text:
Text to analyze
:param hint:
A list which are hints for the API
in which language the text is written in
example:
"de, en"
:return:
detected language code. example: "en" | 4.794001 | 5.090768 | 0.941705 |
encodedtext = urllib.parse.quote(text)
args = "&text=" + encodedtext + "&lang=" + lang + "&format="
if form == FORMAT.PLAIN_TEXT:
args += "plain"
else:
args += "html"
r = self.yandex_translate_request("translate", args)
self.handle_errors... | def translate(self, text: str, lang: str, form: FORMAT = FORMAT.PLAIN_TEXT) | Translates a text
:param text:
text to translate, the maximum size of the text being passed is 10,000 characters
:param lang:
The translation direction. for example: "en-ru"
or target lang. for example, "ru"
:param form:
Possible values:
... | 3.746154 | 3.913609 | 0.957212 |
if self.session:
return
self.session = requests.Session()
headers = {}
if self.user_agent:
headers['User-agent'] = self.user_agent
self.session.headers.update(headers)
if self._auth_method in [None, "", "HTTPBasicAuth"]:
if ... | def _browser_init(self) | Init the browsing instance if not setup
:rtype: None | 2.990491 | 3.037018 | 0.98468 |
self._text_maker = html2text.HTML2Text()
for param in settings:
if not hasattr(self._text_maker, param):
raise WEBParameterException(
"Setting html2text failed - unknown parameter {}".format(
param
)
... | def _set_html2text(self, settings) | Load settings for html2text (https://github.com/Alir3z4/html2text)
Warning: does not check options/values
:param settings: Settings for the object
(see:https://github.com/Alir3z4/html2text/blob/master/docs/usage.md)
:type settings: dict
:rtype: None | 4.142117 | 4.065667 | 1.018804 |
try:
conf = self.load_settings(path)
except:
# Should only be IOError
self.exception("Failed to load file")
raise WEBFileException("Failed to load from {}".format(path))
if "scheme" not in conf:
raise WEBParameterException("Mi... | def load_scrap(self, path) | Load scraper settings from file
:param path: Path to file
:type path: str
:rtype: None
:raises WEBFileException: Failed to load settings
:raises WEBParameterException: Missing parameters in file | 3.7706 | 3.12093 | 1.208166 |
if headers is None:
headers = {}
if not self.session:
self._browser_init()
try:
response = self.session.request(
method,
url,
timeout=timeout,
allow_redirects=self._handle_redirect,
... | def request(
self, method, url, timeout=None,
headers=None, data=None, params=None
) | Make a request using the requests library
:param method: Which http method to use (GET/POST)
:type method: str | unicode
:param url: Url to make request to
:type url: str | unicode
:param timeout: Timeout for request (default: None)
None -> infinite timeout
:... | 2.799653 | 2.610922 | 1.072285 |
if headers is None:
headers = {}
cached = cache_info = None
# TODO: add params to caching key
if self.cache:
cached, cache_info = self.cache.get(url)
if cache_ext:
# Check local cache
if not cache_info:
cac... | def get(self, url, timeout=None, headers=None, params=None, cache_ext=None) | Make get request to url (might use cache)
:param url: Url to make request to
:type url: str | unicode
:param timeout: Timeout for request (default: None)
None -> infinite timeout
:type timeout: None | int | float
:param headers: Headers to be passed along (default: N... | 2.857307 | 2.745889 | 1.040576 |
if tree in [None, []]:
return [ele]
res = []
t = tree[0]
branch = tree[1:]
attributes = {}
for attr in t:
if isinstance(t[attr], dict):
if t[attr].get("type", None) == "reg":
t[attr] = re.compile(t[att... | def _get_tag_match(self, ele, tree) | Match tag
:param ele:
:type ele:
:param tree:
:type tree: None, list
:return:
:rtype: None | list | 2.855325 | 2.79506 | 1.021561 |
if not url:
url = self.url
if not scheme:
scheme = self.scheme
if not timeout:
timeout = self.timeout
if not html_parser:
html_parser = self.html_parser
if not scheme:
raise WEBParameterException("Missing scheme... | def scrap(self,
url=None, scheme=None, timeout=None,
html_parser=None, cache_ext=None
) | Scrap a url and parse the content according to scheme
:param url: Url to parse (default: self._url)
:type url: str
:param scheme: Scheme to apply to html (default: self._scheme)
:type scheme: dict
:param timeout: Timeout for http operation (default: self._timout)
:type t... | 2.738022 | 2.237491 | 1.223702 |
res = []
if len(shrink) == 1:
return self.shrink(shrink[0])
else:
for a in shrink:
temp = self.shrink(a)
if temp:
res.append(temp)
return res | def _shrink_list(self, shrink) | Shrink list down to essentials
:param shrink: List to shrink
:type shrink: list
:return: Shrunk list
:rtype: list | 3.409508 | 3.427881 | 0.99464 |
res = {}
if len(shrink.keys()) == 1 and "value" in shrink:
return self.shrink(shrink['value'])
else:
for a in shrink:
res[a] = self.shrink(shrink[a])
if not res[a]:
del res[a]
return res | def _shrink_dict(self, shrink) | Shrink dict down to essentials
:param shrink: Dict to shrink
:type shrink: dict
:return: Shrunk dict
:rtype: dict | 3.542656 | 3.459564 | 1.024018 |
if isinstance(shrink, list):
return self._shrink_list(shrink)
if isinstance(shrink, dict):
return self._shrink_dict(shrink)
return shrink | def shrink(self, shrink) | Remove unnecessary parts
:param shrink: Object to shringk
:type shrink: dict | list
:return: Shrunk object
:rtype: dict | list | 2.82727 | 2.615414 | 1.081003 |
'''Tries best-effortly to get the right mode name'''
if mode:
l = mode.lower()
if l in ('java', ):
return ('clike', 'text/x-java')
if l in ('c', ):
return ('clike', 'text/x-csrc')
if l in ('c++', 'cxx'):
return ('clike', 'text/x-c++src')
... | def mode_name(mode) | Tries best-effortly to get the right mode name | 3.118824 | 2.57531 | 1.211048 |
if isinstance(grid_size, numbers.Integral):
# default to square-shape grid
grid_size = (grid_size, grid_size)
if pixel_size is None:
# select simulation automatically
rl = radius / wavelength
if rl < 5:
# a lot of diffraction artifacts may occur;
... | def simulate(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, grid_size=(80, 80), model="projection",
pixel_size=None, center=None) | Simulate scattering at a sphere
Parameters
----------
radius: float
Radius of the sphere [m]
sphere_index: float
Refractive index of the object
medium_index: float
Refractive index of the surrounding medium
wavelength: float
Vacuum wavelength of the imaging light... | 4.3555 | 4.18305 | 1.041226 |
par = {"radius": self.radius,
"sphere_index": self.sphere_index,
"pha_offset": self.pha_offset,
"center": [self.posx_offset, self.posy_offset]
}
return par | def params(self) | Current interpolation parameter dictionary | 6.163813 | 5.682414 | 1.084717 |
return self.sphere_index - self.dn, self.sphere_index + self.dn | def range_n(self) | Current interpolation range of refractive index | 14.776654 | 13.713988 | 1.077488 |
return self.radius - self.dr, self.radius + self.dr | def range_r(self) | Current interpolation range of radius | 11.792714 | 8.280379 | 1.424176 |
kwargs = self.model_kwargs.copy()
kwargs["radius"] = self.radius
kwargs["sphere_index"] = self.sphere_index
kwargs["center"] = [self.posx_offset, self.posy_offset]
qpi = self.sphere_method(**kwargs)
# apply phase offset
bg_data = np.ones(qpi.shape) * -sel... | def compute_qpi(self) | Compute model data with current parameters
Returns
-------
qpi: qpimage.QPImage
Modeled phase data
Notes
-----
The model image might deviate from the fitted image
because of interpolation during the fitting process. | 5.385139 | 5.081329 | 1.05979 |
assert idn in [-1, 0, 1]
assert idr in [-1, 0, 1]
n = self.sphere_index + self.dn * idn
r = self.radius + self.dr * idr
# convert to array indices
idn += 1
idr += 1
# find out whether we need to compute a new border field
if self._n_bord... | def get_border_phase(self, idn=0, idr=0) | Return one of nine border fields
Parameters
----------
idn: int
Index for refractive index.
One of -1 (left), 0 (center), 1 (right)
idr: int
Index for radius.
One of -1 (left), 0 (center), 1 (right) | 2.979908 | 2.947938 | 1.010845 |
if nintp is None:
nintp = self.sphere_index
if rintp is None:
rintp = self.radius
assert (rintp == self.radius or nintp ==
self.sphere_index), "Only r or n can be changed at a time."
assert rintp >= self.radius - self.dr
assert r... | def get_phase(self, nintp=None, rintp=None,
delta_offset_x=0, delta_offset_y=0) | Interpolate from the border fields to new coordinates
Parameters
----------
nintp: float or None
Refractive index of the sphere
rintp: float or None
Radius of sphere [m]
delta_offset_x: float
Offset in x-direction [px]
delta_offset_y: ... | 3.18832 | 3.108217 | 1.025771 |
query = db.query(User)
if username:
query = query.filter_by(username=username)
if email:
query = query.filter_by(username=username)
return query | def user_query(username, email) | Find a user match with username and email
:param username:
:param email:
:returns: | 2.524293 | 2.740474 | 0.921116 |
attr1 = getattr(model[iter1][0], attribute, None)
attr2 = getattr(model[iter2][0], attribute, None)
return cmp(attr1, attr2) | def _attr_sort_func(model, iter1, iter2, attribute) | Internal helper | 1.977977 | 2.301855 | 0.859297 |
self.buffer.insert_with_tags_by_name(
self.buffer.get_start_iter(),
self.empty_text, 'empty-text') | def set_empty_text(self) | Display the empty text | 4.716399 | 4.375328 | 1.077953 |
if self._has_reached_stop_limit():
self.log.info("Remaining bytes in quota (%d) has reached minimum to request stop (%d)",
self._quota.remaining, self._stop_on_remaining)
self.fire(events.TransmissionQuotaReached())
elif not self._fits_in_quota(... | def process_data(self, file_info) | expects FileInfo | 8.241429 | 8.037455 | 1.025378 |
message = multipart.MIMEMultipart('alternative')
for name, value in headers.iteritems():
name = name.title()
if name == "From":
multipart[name] = _encodeAddress(value)
elif name in ["To", "Cc", "Bcc"]:
multipart[name] = _encodeAddresses(value)
else:
... | def buildMessage(headers, parts) | Builds a message from some headers and MIME parts. | 3.094383 | 3.17573 | 0.974385 |
try:
return headerValue.encode('ascii', 'strict')
except UnicodeError:
encoded = headerValue.encode("utf-8")
return header.Header(encoded, "UTF-8").encode() | def _encodeHeader(headerValue) | Encodes a header value.
Returns ASCII if possible, else returns an UTF-8 encoded e-mail header. | 4.479214 | 4.310128 | 1.03923 |
outFile = StringIO()
messageGenerator = generator.Generator(outFile, False)
messageGenerator.flatten(message)
outFile.seek(0, 0)
return outFile | def messageToFile(message) | Flattens a message into a file-like object. | 4.394019 | 3.816025 | 1.151465 |
nmed = qpi["medium index"]
px_m = qpi["pixel size"]
wl_m = qpi["wavelength"]
px_wl = px_m / wl_m
phase = qpi.pha
# determine edge
edge = contour_canny(image=phase,
radius=r0 / px_m,
verbose=False,
**edgekw,
... | def analyze(qpi, r0, edgekw={}, ret_center=False, ret_edge=False) | Determine refractive index and radius using Canny edge detection
Compute the refractive index of a spherical phase object by
detection of an edge in the phase image, a subsequent circle
fit to the edge, and finally a weighted average over the phase
image assuming a parabolic phase profile.
Paramet... | 5.034381 | 4.335659 | 1.161157 |
sx, sy = image.shape
x = np.arange(sx).reshape(-1, 1)
y = np.arange(sy).reshape(1, -1)
discsq = ((x - center[0])**2 + (y - center[1])**2)
root = radius**2 - discsq
# height of the cell for each x and y
h = 2 * np.sqrt(root * (root > 0))
# compute phase density
rho = np.zeros(ima... | def average_sphere(image, center, radius, weighted=True, ret_crop=False) | Compute the weighted average phase from a phase image of a sphere
Parameters
----------
image: 2d ndarray
Quantitative phase image of a sphere
center: tuble (x,y)
Center of the sphere in `image` in ndarray coordinates
radius: float
Radius of the sphere in pixels
weighted... | 3.595063 | 3.315651 | 1.08427 |
sx, sy = edge.shape
x = np.linspace(0, sx, sx, endpoint=False).reshape(-1, 1)
y = np.linspace(0, sy, sy, endpoint=False).reshape(1, -1)
params = lmfit.Parameters()
# initial parameters
sum_edge = np.sum(edge)
params.add("cx", np.sum(x * edge) / sum_edge)
params.add("cy", np.sum(y * ... | def circle_fit(edge, ret_dev=False) | Fit a circle to a boolean edge image
Parameters
----------
edge: 2d boolean ndarray
Edge image
ret_dev: bool
Return the average deviation of the distance from contour to
center of the fitted circle.
Returns
-------
center: tuple of (float, float)
Coordinates... | 2.454283 | 2.53555 | 0.967949 |
cx = params["cx"].value
cy = params["cy"].value
radii = np.sqrt((cx - xedge)**2 + (cy - yedge)**2)
return radii | def circle_radii(params, xedge, yedge) | Compute the distance to the center from cartesian coordinates
This method is used for fitting a circle to a set of contour
points.
Parameters
----------
params: lmfit.Parameters
Must contain the keys:
- "cx": origin of x coordinate [px]
- "cy": origin of y coordinate [px]
... | 2.704872 | 2.87914 | 0.939472 |
radii = circle_radii(params, xedge, yedge)
return radii - np.mean(radii) | def circle_residual(params, xedge, yedge) | Residuals for circle fitting
Parameters
----------
params: lmfit.Parameters
Must contain the keys:
- "cx": origin of x coordinate [px]
- "cy": origin of y coordinate [px]
xedge: 1D np.ndarray
Edge coordinates x [px]
yedge: 1D np.ndarray
Edge coordinates y [p... | 4.372964 | 6.868433 | 0.636676 |
return super(HeaderDict, cls).fromkeys(cls,
[s.title() for s in seq], v) | def fromkeys(cls, seq, v=None) | Override dict.fromkeys() to title-case keys. | 11.552507 | 8.877046 | 1.301391 |
return super(HeaderDict, self).get(k.title(), d) | def get(self, k, d=None) | Override dict.get() to title-case keys. | 9.659464 | 5.856546 | 1.649345 |
return super(HeaderDict, self).setdefault(k.title(), d) | def setdefault(self, k, d=None) | Override dict.setdefault() to title-case keys. | 10.912319 | 6.170647 | 1.768424 |
# Handle e first
if e is not None:
if hasattr(e, 'keys'):
for k in e:
self[k.title()] = e[k]
else:
for (k, v) in e:
self[k.title()] = v
# Now handle f
if len(f):
for k i... | def update(self, e=None, **f) | Override dict.update() to title-case keys. | 2.829857 | 2.349721 | 1.204337 |
path = os.path.expanduser('~/.config/python-bugzilla/bugzillarc')
cfg = SafeConfigParser()
cfg.read(path)
domain = urlparse(url)[1]
if domain not in cfg.sections():
return None
if not cfg.has_option(domain, 'api_key'):
return None
return cfg.get(domain, 'api_key') | def api_key_from_file(url) | Check bugzillarc for an API key for this Bugzilla URL. | 3.027362 | 2.296916 | 1.318012 |
if self.api_key:
payload['Bugzilla_api_key'] = self.api_key
d = self.proxy.callRemote(action, payload)
d.addErrback(self._parse_errback)
return d | def call(self, action, payload) | Make an XML-RPC call to the server. This method will automatically
authenticate the call with self.api_key, if that is set.
returns: deferred that when fired returns a dict with data from this
XML-RPC call. | 4.831074 | 4.067343 | 1.187772 |
payload = {'ids': bugid}
d = self.call('Bug.get', payload)
d.addCallback(self._parse_bug_callback)
return d | def get_bug_simple(self, bugid) | Get a single bug object. Similar to python-bugzilla's getbugsimple().
param bugid: integer, a bug's number.
returns: deferred that when fired returns an AttrDict representing this
bug. | 6.416546 | 5.312317 | 1.207862 |
payload = {'ids': bugids}
d = self.call('Bug.get', payload)
d.addCallback(self._parse_bugs_callback)
return d | def get_bugs_simple(self, bugids) | Get multiple bug objects. Similar to python-bugzilla's getbugssimple().
param bugids: ``list`` of ``int``, bug numbers.
returns: deferred that when fired returns a list of ``AttrDict``s
representing these bugs. | 6.188537 | 5.529893 | 1.119106 |
payload = {'ids': bugids, 'include_fields': ['id', 'summary']}
d = self.call('Bug.get', payload)
d.addCallback(self._parse_bugs_callback)
return d | def get_bugs_summaries(self, bugids) | Get multiple bug objects' summaries only (faster).
param bugids: ``list`` of ``int``, bug numbers.
returns: deferred that when fired returns a list of ``AttrDict``s
representing these bugs. | 5.277446 | 4.899235 | 1.077198 |
payload = {'ids': (bugids,), 'assigned_to': user}
d = self.call('Bug.update', payload)
d.addCallback(self._parse_bug_assigned_callback)
return d | def assign(self, bugids, user) | Assign a bug to a user.
param bugid: ``int``, bug ID number.
param user: ``str``, the login name of the user to whom the bug is
assigned
returns: deferred that when fired returns True if the change succeeded,
False if the change was unnecessary (because the ... | 7.150751 | 6.831382 | 1.04675 |
payload = {
'include_fields': ['id', 'summary', 'status'],
'f1': 'external_bugzilla.url',
'o1': 'substring',
'v1': url,
'f2': 'ext_bz_bug_map.ext_bz_bug_id',
'o2': 'equals',
'v2': id_,
}
d = self.call('B... | def find_by_external_tracker(self, url, id_) | Find a list of bugs by searching an external tracker URL and ID.
param url: ``str``, the external ticket URL, eg
"http://tracker.ceph.com". (Note this is the base URL.)
param id_: ``str``, the external ticket ID, eg "18812".
returns: deferred that when fired returns a list of... | 4.772421 | 4.355139 | 1.095814 |
return list(map(lambda x: self._parse_bug(x), value['bugs'])) | def _parse_bugs_callback(self, value) | Fires when we get bug information back from the XML-RPC server.
param value: dict of data from XML-RPC server. The "bugs" dict element
contains a list of bugs.
returns: ``list`` of ``AttrDict`` | 6.224535 | 7.11048 | 0.875403 |
if isinstance(error.value, IOError):
raise error.value
if hasattr(xmlrpc, 'Fault'): # Python 2:
fault = xmlrpc.Fault
else:
fault = xmlrpc.client.Fault
if isinstance(error.value, fault):
if error.value.faultCode == 101:
... | def _parse_errback(self, error) | Parse an error from an XML-RPC call.
raises: ``IOError`` when the Twisted XML-RPC connection times out.
raises: ``BugzillaNotFoundException``
raises: ``BugzillaNotAuthorizedException``
raises: ``BugzillaException`` if we got a response from the XML-RPC
server but it is n... | 2.820499 | 2.425477 | 1.162863 |
if 'id' in data:
data['weburl'] = self.url.replace('xmlrpc.cgi', str(data['id']))
bug = AttrDict(data)
return bug | def _parse_bug(self, data) | param data: dict of data from XML-RPC server, representing a bug.
returns: AttrDict | 7.519915 | 5.391723 | 1.394715 |
m = re.match(r'Bug #(\d+) does not exist', self.message)
return m.group(1) | def id(self) | Bug ID number that caused this error | 9.201599 | 5.280911 | 1.742426 |
m = re.match(r'You are not authorized to access bug #(\d+)',
self.message)
return m.group(1) | def id(self) | Bug ID number that caused this error | 9.816066 | 5.780435 | 1.698154 |
logger.info(u"onSettingsChange: {}".format(data))
if not plugin_name:
logger.error("Missing plugin name")
return
if not data:
logger.error("Missing data")
return
logger.info(u"Sending data {}".format(data))
reactor.callFrom... | def onSettingsChange(self, plugin_name, data) | The plugin has been changed by the frontend
:param plugin_name: Name of plugin that changed
:type plugin_name: str
:param data: Complete data (changed and unchanged)
:type data: dict
:rtype: None | 2.902059 | 2.998017 | 0.967993 |
logger.info(u"onRefreshPluginData: {}".format(plugin_name))
if not plugin_name:
logger.error("Missing plugin name")
return
reactor.callFromThread(self._sendJSON, {
'msg': "plugin_data_get",
'plugin_name': plugin_name
}) | def onRefreshPluginData(self, plugin_name, data) | Frontend requests a data refresh
:param plugin_name: Name of plugin that changed
:type plugin_name: str
:param data: Additional data
:type data: None
:rtype: None | 4.17362 | 4.35592 | 0.958149 |
if dest.scheme == 'file':
if source.isdir() and dest.isdir():
dest /= source.basename()
return shutil.move(source.path, dest.path)
else:
return super(LocalFileSystem, self).move(source, dest) | def move(self, source, dest) | the semantic should be like unix 'mv' command.
Unfortunatelly, shutil.move does work differently!!!
Consider (all paths point to directories)
mv /a/b /a/c
expected outcome:
case 1.: 'c' does not exist:
b moved over to /a such that /a/c is what was /a/b/ before
c... | 3.552898 | 3.61606 | 0.982533 |
self._state = STATE_CONNECTING
logger.debug("About to connect to {}".format(self.url))
m = re.search('(ws+)://([\w\.]+)(:?:(\d+))?',self.url)
options['subprotocols'] = ['wamp.2.json']
options['enable_multithread'] = True
options.setdefault('timeout',self._loop_... | def connect(self,soft_reset=False,**options) | This just creates the websocket connection | 5.032926 | 4.952702 | 1.016198 |
self._welcome_queue = queue.Queue()
if details is None:
details = {}
if self.authid:
details.setdefault('authid', self.authid)
details.setdefault('agent', u'swampyer-1.0')
details.setdefault('authmethods', self.authmethods or [u'anonymous'])
... | def hello(self,details=None) | Say hello to the server and wait for the welcome
message before proceeding | 5.471826 | 5.326076 | 1.027365 |
if self._state == STATE_DISCONNECTED:
raise Exception("WAMP is currently disconnected!")
options = {
'disclose_me': True
}
uri = self.get_full_uri(uri)
message = self.send_and_await_response(CALL(
options=options,
... | def call(self, uri, *args, **kwargs ) | Sends a RPC request to the WAMP server | 4.833672 | 4.479611 | 1.079038 |
if self._state == STATE_DISCONNECTED:
raise Exception("WAMP is currently disconnected!")
message = message.as_str()
logger.debug("SND>: {}".format(message))
if not self.ws:
raise Exception("WAMP is currently disconnected!")
self.ws.send(message) | def send_message(self,message) | Send awamp message to the server. We don't wait
for a response here. Just fire out a message | 5.412137 | 5.227035 | 1.035413 |
if self._state == STATE_DISCONNECTED:
raise Exception("WAMP is currently disconnected!")
wait_queue = queue.Queue()
request_id = request.request_id
self._requests_pending[request_id] = wait_queue;
self.send_message(request)
try:
return wai... | def send_and_await_response(self,request) | Used by most things. Sends out a request then awaits a response
keyed by the request_id | 3.97693 | 3.876408 | 1.025932 |
# If we are awaiting to login, then we might also get
# an abort message. Handle that here....
if self._state == STATE_AUTHENTICATING:
# If the authentication message is something unexpected,
# we'll just ignore it for now
if result == WAMP_ABORT \
... | def dispatch_to_awaiting(self,result) | Send dat ato the appropriate queues | 5.401869 | 5.389518 | 1.002292 |
self._welcome_queue.put(reason)
self.close()
self.disconnect() | def handle_abort(self, reason) | We're out? | 10.442036 | 9.366044 | 1.114882 |
req_id = message.request_id
reg_id = message.registration_id
if reg_id in self._registered_calls:
handler = self._registered_calls[reg_id][REGISTERED_CALL_CALLBACK]
invoke = WampInvokeWrapper(self,handler,message)
invoke.start()
else:
... | def handle_invocation(self, message) | Passes the invocation request to the appropriate
callback. | 5.35355 | 5.311127 | 1.007988 |
subscription_id = event.subscription_id
if subscription_id in self._subscriptions:
# FIXME: [1] should be a constant
handler = self._subscriptions[subscription_id][SUBSCRIPTION_CALLBACK]
WampSubscriptionWrapper(self,handler,event).start() | def handle_event(self, event) | Send the event to the subclass or simply reject | 8.430388 | 8.334031 | 1.011562 |
full_topic = self.get_full_uri(topic)
result = self.send_and_await_response(SUBSCRIBE(
options=options or {},
topic=full_topic
))
if result == WAMP_SUBSCRIBED:
if not call... | def subscribe(self,topic,callback=None,options=None) | Subscribe to a uri for events from a publisher | 5.247628 | 5.078469 | 1.033309 |
topic = self.get_full_uri(topic)
if options is None:
options = {'acknowledge':True}
if options.get('acknowledge'):
request = PUBLISH(
options=options or {},
topic=topic,
args=args or [],
... | def publish(self,topic,options=None,args=None,kwargs=None) | Publishes a messages to the server | 2.84348 | 2.922415 | 0.97299 |
logger.debug("Disconnecting")
# Close off the websocket
if self.ws:
try:
if self._state == STATE_CONNECTED:
self.handle_leave()
self.send_message(GOODBYE(
details={},
... | def disconnect(self) | Disconnect from the websocket and pause the process
till we reconnect | 5.978324 | 5.951638 | 1.004484 |
self._request_shutdown = True
for i in range(100):
if self._state == STATE_DISCONNECTED:
break
time.sleep(0.1) | def shutdown(self) | Request the system to shutdown the main loop and shutdown the system
This is a one-way trip! Reconnecting requires a new connection
to be made! | 4.396641 | 3.571296 | 1.231105 |
self.connect()
if not self.isAlive():
super(WAMPClient,self).start()
self.hello()
return self | def start(self) | Initialize websockets, say hello, and start listening for events | 8.93375 | 7.223121 | 1.236827 |
while not self._request_shutdown:
# Find out if we have any data pending from the
# server
try:
# If we've been asked to stop running the
# request loop. We'll just sit and wait
# till we get asked to run again
... | def run(self) | Waits and receives messages from the server. This
function somewhat needs to block so is executed in its
own thread until self._request_shutdown is called. | 5.151955 | 4.942672 | 1.042342 |
# Send challenge response
self.send_message(AUTHENTICATE(
signature = self.password,
extra = {}
)) | def handle_challenge(self,data) | Executed when the server requests additional
authentication | 16.423414 | 18.961439 | 0.866148 |
log.info('starting the ``_generate_pyephem_snapshot`` method')
print "generating pyephem database for MJD %(mjd)s" % locals()
global xephemOE
global DEG_TO_RAD_FACTOR
global RAD_TO_DEG_FACTOR
global nside
# THE PYEPHEM OBSERVER
obs = ephem.Observer()
# PYEPHEM WORKS IN DUBLIN... | def _generate_pyephem_snapshot(
mjd,
log,
magLimit) | * generate pyephem snapshot*
**Key Arguments:**
- ``mjd`` -- the mjd to generate the pyephem snapshot database for
- ``xephemOE`` -- a list of xephem database format strings for use with pyephem
**Return:**
- ``pyephemDB`` -- the pyephem solar-system snapshot database | 3.469094 | 3.217269 | 1.078273 |
log.info('starting the ``_match_single_exposure_against_pyephem_db`` function')
global tileSide
global magLimit
global DEG_TO_RAD_FACTOR
global nside
global moversDict
matchedObjects = []
expId = exposure["expname"]
raFc = float(exposure["raDeg"])
decFc = float(exposure["d... | def _match_single_exposure_against_pyephem_db(
exposure,
log) | *summary of function*
**Key Arguments:**
- ``exposure`` -- the atlas expsosure metadata
- ``log`` -- logger
**Return:**
- None
**Usage:**
.. todo::
add usage info
create a sublime snippet for usage
.. code-block:: python
usag... | 3.632997 | 3.698356 | 0.982328 |
self.log.info('starting the ``get`` method')
global xephemOE
global tileSide
global magLimit
# GRAB PARAMETERS FROM SETTINGS FILE
tileSide = float(self.settings["pyephem"]["atlas exposure match side"])
magLimit = float(self.settings["pyephem"]["magnitud... | def get(self, singleSnapshot=False) | *geneate the pyephem positions*
**Key Arguments:**
- ``singleSnapshot`` -- just extract positions for a single pyephem snapshot (used for unit testing)
**Return:**
- ``None`` | 6.094084 | 5.518531 | 1.104295 |
self.log.info(
'starting the ``_get_exposures_requiring_pyephem_positions`` method')
if self.dev_flag == True:
dev_flag = " and dev_flag = 1"
else:
dev_flag = ""
sqlQuery = u % locals()
rows = readquery(
log=self.log,
... | def _get_exposures_requiring_pyephem_positions(
self,
concurrentSnapshots=10) | *get next batch of exposures requiring pyephem positions*
**Key Arguments:**
- ``concurrentSnapshots`` -- number of concurrent PyEphem snapshots to process | 3.232733 | 3.219343 | 1.004159 |
self.log.info(
'starting the ``_add_matched_objects_to_database`` method')
print "Adding the matched sources to the `pyephem_positions` database table"
allMatches = []
for m in matchedObjects:
allMatches += m
dbSettings = self.settings["databas... | def _add_matched_objects_to_database(
self,
matchedObjects) | *add mathced objects to database*
**Key Arguments:**
- ``matchedObjects`` -- these objects matched in the neighbourhood of the ATLAS exposures (list of dictionaries) | 4.996607 | 4.457527 | 1.120937 |
self.log.info('starting the ``_update_database_flag`` method')
allExposures = []
for e in exposures:
allExposures += e
expIds = []
expIds[:] = [e["expname"] for e in allExposures]
expIds = ('","').join(expIds)
sqlQuery = % locals(
... | def _update_database_flag(
self,
exposures) | * update database flag*
**Key Arguments:**
- ``exposures`` -- the atlas exposure to update the database flags for | 3.890599 | 3.713085 | 1.047808 |
self.log.info('starting the ``_get_xephem_orbital_elements`` method')
print "Getting the XEphem orbital element strings from the database"
sqlQuery = u % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.atlasMoversDBCo... | def _get_xephem_orbital_elements(
self) | *get xephem orbital elements*
**Key Arguments:**
- ``xephemOE`` -- a list of xephem database format strings for use with pyephem | 6.03261 | 4.753169 | 1.269177 |
self.log.info(
'starting the ``_match_pyephem_snapshot_to_atlas_exposures`` method')
global DEG_TO_RAD_FACTOR
global RAD_TO_DEG_FACTOR
global moversDict
e = len(exposures)
print "Matching %(e)s ATLAS exposures against the pyephem snapshot for MJD =... | def _match_pyephem_snapshot_to_atlas_exposures(
self,
pyephemDB,
exposures,
mjd) | *match pyephem snapshot to atlas exposures*
**Key Arguments:**
- ``pyephemDB`` -- the pyephem solar-system snapshot database
- ``exposures`` -- the atlas exposures to match against the snapshot
- ``mjd`` -- the MJD of the pyephem snapshot
**Return:**
- `... | 3.806246 | 3.607474 | 1.0551 |
EXTRACT_FIELD = 'field'
extract_params = params
extract_params.update({AccessParams.KEY_TYPE: AccessParams.TYPE_SINGLE})
return __extract(input, params)[params.get(EXTRACT_FIELD)] | def extract(input, **params) | Extract field value from document
:param input:
:param params:
:return: | 10.776406 | 11.25834 | 0.957193 |
PARAM_CFG_EXTRACT = 'extract'
PARAM_CFG_SUBSTITUTE = 'substitute'
PARAM_CFG_AGGREGATE = 'aggregate'
AGGR_FIELD = 'field'
AGGR_FUNC = 'func'
extract_params = params.get(PARAM_CFG_EXTRACT)
extract_params.update({AccessParams.KEY_TYPE: AccessParams.TYPE_MULTI})
dataset = __extract(inp... | def aggregate(input, **params) | Returns aggregate
:param input:
:param params:
:return: | 3.820493 | 3.905796 | 0.97816 |
if to_validate > constraint:
violation_cfg[Check.CFG_KEY_VIOLATION_MSG] = violation_cfg[Check.CFG_KEY_VIOLATION_MSG].format(constraint)
return violation_cfg
else:
return None | def limit_exceed(to_validate, constraint, violation_cfg) | Compares 2 values and returns violation message if validated value bigger than constraint
:param to_validate:
:param constraint:
:param violation_cfg:
:return: | 3.207915 | 3.07065 | 1.044702 |
if len(constraint) == 0 or len(set(constraint).intersection(to_validate)) > 0:
return None
else:
violation_cfg[Check.CFG_KEY_VIOLATION_MSG] = violation_cfg[Check.CFG_KEY_VIOLATION_MSG].format(constraint)
return violation_cfg | def no_intersection(to_validate, constraint, violation_cfg) | Returns violation message if validated and constraint sets have no intersection
:param to_validate:
:param constraint:
:param violation_cfg:
:return: | 3.128681 | 2.969387 | 1.053645 |
res = []
for check in self.__cfg[Validator.__CFG_KEY_CHECKS]:
self.__logger.info('Performing {} validation against {}'.format(check, obj_to_validate))
check_res = Check(self.__cfg[Validator.__CFG_KEY_CHECKS][check]).validate(obj_to_validate, is_substitute)
if... | def validate(self, obj_to_validate, is_substitute=True) | Performs validation
:param obj_to_validate:
:param is_substitute:
:return: list of validation messages or None | 2.90996 | 2.758807 | 1.054789 |
def validate(self, input, is_substitute): # ToDo: apply 'no substitute' for initial load validations
constraint = self.__get_constraint(input)
to_validate = self.__get_to_validate(input)
return self.__compare(to_validate, constraint) | Performs validation
:param input: object to validate
:param is_substitute: will be used for what-if in the future
:return: validation result if violated or None | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.