_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q53800
diff
train
def diff(local_path, remote_path): """Return true if local and remote paths differ in contents""" with hide('commands'): if isinstance(local_path, basestring): with open(local_path) as stream: local_content = stream.read() else: pos = local_path.tell() ...
python
{ "resource": "" }
q53801
md5sum
train
def md5sum(filename, use_sudo=False): """Return md5sum of remote file""" runner = sudo if use_sudo else run with hide('commands'): return runner("md5sum '{}'".format(filename)).split()[0]
python
{ "resource": "" }
q53802
mkdir
train
def mkdir(dirs, user=None, group=None, mode=None, use_sudo=True): """Create directory with sudo and octal mode, then set ownership.""" if isinstance(dirs, basestring): dirs = [dirs] runner = sudo if use_sudo else run if dirs: modearg = '-m {:o}'.format(mode) if mode else '' cmd =...
python
{ "resource": "" }
q53803
rsync
train
def rsync(local_path, remote_path, exclude=None, extra_opts=None): """Helper to rsync submodules across""" if not local_path.endswith('/'): local_path += '/' exclude = exclude or [] exclude.extend(['*.egg-info', '*.pyc', '.git', '.gitignore', '.gitmodules', '/build/', '/dist/...
python
{ "resource": "" }
q53804
tempput
train
def tempput(local_path=None, remote_path=None, use_sudo=False, mirror_local_mode=False, mode=None): """Put a file to remote and remove it afterwards""" import warnings warnings.simplefilter('ignore', RuntimeWarning) if remote_path is None: remote_path = os.tempnam() put(local_pat...
python
{ "resource": "" }
q53805
watch
train
def watch(filenames, callback, use_sudo=False): """Call callback if any of filenames change during the context""" filenames = [filenames] if isinstance(filenames, basestring) else filenames old_md5 = {fn: md5sum(fn, use_sudo) for fn in filenames} yield for filename in filenames: if md5sum(fi...
python
{ "resource": "" }
q53806
install_deb
train
def install_deb(pkgname, url): """Install package from custom deb hosted on S3. Return true if package was installed by this invocation.""" status = run("dpkg-query -W -f='${{Status}}' {p}; true".format(p=pkgname)) if ('installed' not in status) or ('not-installed' in status): deb = url.rpartiti...
python
{ "resource": "" }
q53807
package_ensure_apt
train
def package_ensure_apt(*packages): """Ensure apt packages are installed""" package = " ".join(packages) status = run("dpkg-query -W -f='${{Status}} ' {p}; true".format(p=package)) status = status.lower() if 'no packages found' in status or 'not-installed' in status: sudo("apt-get --yes insta...
python
{ "resource": "" }
q53808
update_apt
train
def update_apt(days=3, upgrade=False): """Update apt index if not update in last N days""" # Check the apt-get update timestamp (works on Ubuntu only) with settings(warn_only=True): last_update = run( "stat -c %Y /var/lib/apt/periodic/update-success-stamp") if ('cannot stat' in last_...
python
{ "resource": "" }
q53809
make_version
train
def make_version(ref=None): """Build git version string for current directory""" cmd = 'git describe --tags --abbrev=6 {}'.format(ref or '') with hide('commands'): version = local(cmd, capture=True).strip() if re.match('^v[0-9]', version): version = version[1:] # replacements to matc...
python
{ "resource": "" }
q53810
rsync_git
train
def rsync_git(local_path, remote_path, exclude=None, extra_opts=None, version_file='version.txt'): """Rsync deploy a git repo. Write and compare version.txt""" with settings(hide('output', 'running'), warn_only=True): print(green('Version On Server: ' + run('cat ' + '{}/{}'.format( ...
python
{ "resource": "" }
q53811
tagversion
train
def tagversion(repo, level='patch', special=''): """Increment and return tagged version in git. Increment levels are patch, minor and major. Using semver.org versioning: {major}.{minor}.{patch}{special} Special must start with a-z and consist of _a-zA-Z0-9. """ prepend = 'v' with lcd(repo):...
python
{ "resource": "" }
q53812
write_version
train
def write_version(path, ref=None): """Update version file using git desribe""" with lcd(dirname(path)): version = make_version(ref) if (env.get('full') or not os.path.exists(path) or version != open(path).read().strip()): with open(path, 'w') as out: out.write(version...
python
{ "resource": "" }
q53813
splunk
train
def splunk(cmd, user='admin', passwd='changeme'): """Authenticated call to splunk""" return sudo('/opt/splunkforwarder/bin/splunk {c} -auth {u}:{p}' .format(c=cmd, u=user, p=passwd))
python
{ "resource": "" }
q53814
HectaneBackend.send_messages
train
def send_messages(self, emails): """ Attempt to send the specified emails. """ num_sent = 0 for e in emails: html = None if isinstance(e, EmailMultiAlternatives): for a in e.alternatives: if a[1] == 'text/html': ...
python
{ "resource": "" }
q53815
Lexer.advance
train
def advance(self): """Increments the cursor position.""" self.cursor += 1 if self.cursor >= len(self.raw): self.char = None else: self.char = self.raw[self.cursor]
python
{ "resource": "" }
q53816
Lexer.peek
train
def peek(self): """Get the next character without moving the cursor.""" peek_cursor = self.cursor + 1 if peek_cursor >= len(self.raw): return None else: return self.raw[peek_cursor]
python
{ "resource": "" }
q53817
Lexer.number
train
def number(self): """Return a multidigit int or float number.""" number = '' while self.char is not None and self.char.isdigit(): number += self.char self.advance() if self.char == '.': number += self.char self.advance() while...
python
{ "resource": "" }
q53818
Lexer._id
train
def _id(self): """Handle identifiers and reserverd keywords.""" result = '' while self.char is not None and (self.char.isalnum() or self.char == '_'): result += self.char self.advance() token = RESERVED_KEYWORDS.get(result, Token(Nature.ID, result)) retur...
python
{ "resource": "" }
q53819
FileConfig.validate
train
def validate(self): """Validate current file configuration :raise ValueError: """ if not self.file.exists(): raise ValueError("File \"%s\" doesn't exists") if not self.search: raise ValueError("Search cannot be empty") if not self.replace: ...
python
{ "resource": "" }
q53820
get_json_feed_content
train
def get_json_feed_content(url, offset=0, limit=None): """ Get the entries in a JSON feed """ end = limit + offset if limit is not None else None response = _get(url) try: content = json.loads(response.text) except Exception as parse_error: logger.warning( 'Fail...
python
{ "resource": "" }
q53821
get_rss_feed_content
train
def get_rss_feed_content(url, offset=0, limit=None, exclude_items_in=None): """ Get the entries from an RSS feed """ end = limit + offset if limit is not None else None response = _get(url) try: feed_data = feedparser.parse(response.text) if not feed_data.feed: log...
python
{ "resource": "" }
q53822
Pystmark._pystmark_call
train
def _pystmark_call(self, method, *args, **kwargs): ''' Wraps a call to the pystmark Simple API, adding configured settings ''' kwargs = self._apply_config(**kwargs) return method(*args, **kwargs)
python
{ "resource": "" }
q53823
PikaDaemon.body
train
def body(self): """ This method just handles AMQP connection details and receive loop. Warning: Don't override this method! """ self.connection = pika.BlockingConnection(self.connection_param) self.channel = self.connection.channel() # receive messag...
python
{ "resource": "" }
q53824
PikaDaemon.onMessageReceived
train
def onMessageReceived(self, method_frame, properties, body): """ Callback which is called every time when message is received. Warning: You SHOULD override this. Note: It is expected, that method returns True, if you want to automatically ack the rec...
python
{ "resource": "" }
q53825
PikaDaemon.sendMessage
train
def sendMessage(self, exchange, routing_key, message, properties=None, UUID=None): """ With this function, you can send message to `exchange`. Args: exchange (str): name of exchange you want to message to be delivered routi...
python
{ "resource": "" }
q53826
PikaDaemon.sendResponse
train
def sendResponse(self, message, UUID, routing_key): """ Send `message` to ``self.output_exchange`` with routing key ``self.output_key``, ``self.content_type`` in ``delivery_mode=2``. Args: message (str): message which will be sent UUID: unique identification of m...
python
{ "resource": "" }
q53827
MarkdownATXCollectorStrategy.get
train
def get(self, file_lines, index): """ Extract the specified AnchorHub tag, as well as the portion of the line that should be converted from the ATX style Markdown header. :param file_lines: List of strings corresponding to lines in a text file :param index: index of file_lines c...
python
{ "resource": "" }
q53828
ReadOnlyFilter.__raise_user_error
train
def __raise_user_error(self, view): """ Raises an error if the given View has been set read only and the user attempted to edit its content. :param view: View. :type view: QWidget """ raise foundations.exceptions.UserError("{0} | Cannot perform action, '{1}' View has be...
python
{ "resource": "" }
q53829
Mixin_AbstractView.__initialize_ui
train
def __initialize_ui(self): """ Initializes the View ui. """ self.viewport().installEventFilter(ReadOnlyFilter(self)) if issubclass(type(self), QListView): super(type(self), self).setUniformItemSizes(True) elif issubclass(type(self), QTreeView): s...
python
{ "resource": "" }
q53830
Mixin_AbstractView.get_nodes
train
def get_nodes(self): """ Returns the View nodes. :return: View nodes. :rtype: list """ return [node for node in foundations.walkers.nodes_walker(self.model().root_node)]
python
{ "resource": "" }
q53831
Mixin_AbstractView.filter_nodes
train
def filter_nodes(self, pattern, attribute, flags=re.IGNORECASE): """ Filters the View Nodes on given attribute using given pattern. :param pattern: Filtering pattern. :type pattern: unicode :param attribute: Filtering attribute. :type attribute: unicode :param fl...
python
{ "resource": "" }
q53832
Mixin_AbstractView.get_view_nodes_from_indexes
train
def get_view_nodes_from_indexes(self, *indexes): """ Returns the View Nodes from given indexes. :param view: View. :type view: QWidget :param \*indexes: Indexes. :type \*indexes: list :return: View nodes. :rtype: dict """ nodes = {} ...
python
{ "resource": "" }
q53833
Mixin_AbstractView.select_view_indexes
train
def select_view_indexes(self, indexes, flags=QItemSelectionModel.Select | QItemSelectionModel.Rows): """ Selects the View given indexes. :param view: View. :type view: QWidget :param indexes: Indexes to select. :type indexes: list :param flags: Selection flags. (...
python
{ "resource": "" }
q53834
Mixin_AbstractView.select_indexes
train
def select_indexes(self, indexes, flags=QItemSelectionModel.Select | QItemSelectionModel.Rows): """ Selects given indexes. :param indexes: Indexes to select. :type indexes: list :param flags: Selection flags. ( QItemSelectionModel.SelectionFlags ) :return: Method success...
python
{ "resource": "" }
q53835
lint
train
def lint(fmt='colorized'): """Run verbose PyLint on source. Optionally specify fmt=html for HTML output.""" if fmt == 'html': outfile = 'pylint_report.html' local('pylint -f %s davies > %s || true' % (fmt, outfile)) local('open %s' % outfile) else: local('pylint -f %s davies ...
python
{ "resource": "" }
q53836
Shot.azm
train
def azm(self): """Corrected azimuth, taking into account backsight, declination, and compass corrections.""" azm1 = self.get('BEARING', None) azm2 = self.get('AZM2', None) if azm1 is None and azm2 is None: return None if azm2 is None: return azm1 + self.de...
python
{ "resource": "" }
q53837
Shot.inc
train
def inc(self): """Corrected inclination, taking into account backsight and clino corrections.""" inc1 = self.get('INC', None) inc2 = self.get('INC2', None) if inc1 is None and inc2 is None: return None if inc2 is None: return inc1 if inc1 is None: ...
python
{ "resource": "" }
q53838
Survey.included_length
train
def included_length(self): """Surveyed length, not including "excluded" shots""" return sum([shot.length for shot in self.shots if shot.is_included])
python
{ "resource": "" }
q53839
Survey.excluded_length
train
def excluded_length(self): """Surveyed length which does not count toward the included total""" return sum([shot.length for shot in self.shots if Exclude.LENGTH in shot.flags or Exclude.TOTAL in shot.flags])
python
{ "resource": "" }
q53840
DatFile.write
train
def write(self, outfname=None): """Write or overwrite a `Survey` to the specified .DAT file""" outfname = outfname or self.filename with codecs.open(outfname, 'wb', 'windows-1252') as outf: for survey in self.surveys: outf.write('\r\n'.join(survey._serialize())) ...
python
{ "resource": "" }
q53841
Project.set_base_location
train
def set_base_location(self, location): """Configure the project's base location""" self.base_location = location self._utm_zone = location.zone self._utm_datum = location.datum self._utm_convergence = location.convergence
python
{ "resource": "" }
q53842
Project.add_linked_station
train
def add_linked_station(self, datfile, station, location=None): """Add a linked or fixed station""" if datfile not in self.fixed_stations: self.fixed_stations[datfile] = {station: location} else: self.fixed_stations[datfile][station] = location if location and not...
python
{ "resource": "" }
q53843
Project.write
train
def write(self, outfilename=None): """Write or overwrite this .MAK file""" outfilename = outfilename or self.filename if not outfilename: raise ValueError('Unable to write MAK file without a filename') with codecs.open(outfilename, 'wb', 'windows-1252') as outf: o...
python
{ "resource": "" }
q53844
VersionFile.read
train
def read(self): """Read version from version file :rtype : Version :return: """ with self._path.open(mode='r') as fh: version = fh.read().strip() return Version(version)
python
{ "resource": "" }
q53845
get_matches
train
def get_matches(pattern, language, max_count=8): """ take a word pattern or a Python regexp and a language name, and return a list of all matching words. """ if str(pattern) == pattern: pattern = compile_pattern(pattern) results = [] if not dicts.exists(language): print("Th...
python
{ "resource": "" }
q53846
TraceUi.trace_modules
train
def trace_modules(self, modules, pattern=r".*", flags=re.IGNORECASE): """ Traces given modules using given filter pattern. :param modules: Modules to trace. :type modules: list :param pattern: Matching pattern. :type pattern: unicode :param flags: Matching regex ...
python
{ "resource": "" }
q53847
TraceUi.untrace_modules
train
def untrace_modules(self, modules): """ Untraces given modules. :param modules: Modules to untrace. :type modules: list :return: Method success. :rtype: bool """ for module in modules: foundations.trace.untrace_module(module) self.__m...
python
{ "resource": "" }
q53848
TraceUi.set_modules
train
def set_modules(self, modules=None): """ Sets the modules Model nodes. :param modules: Modules to set. :type modules: list :return: Method success. :rtype: bool """ node_flags = int(Qt.ItemIsSelectable | Qt.ItemIsEnabled) modules = modules or sel...
python
{ "resource": "" }
q53849
auth_required
train
def auth_required(validator): """Decorate a RequestHandler or method to require that a request is authenticated If decorating a coroutine make sure coroutine decorator is first. eg.:: class Handler(tornado.web.RequestHandler): @auth_required(validator) @coroutine ...
python
{ "resource": "" }
q53850
auth_optional
train
def auth_optional(validator): """Decorate a RequestHandler or method to accept optional authentication token If decorating a coroutine make sure coroutine decorator is first. eg.:: class Handler(tornado.web.RequestHandler): @auth_required(validator) @coroutine ...
python
{ "resource": "" }
q53851
_wrap_class
train
def _wrap_class(request_handler, validator): """Decorate each HTTP verb method to check if the request is authenticated :param request_handler: a tornado.web.RequestHandler instance """ METHODS = ['get', 'post', 'put', 'head', 'options', 'delete', 'patch'] for name in METHODS: method = geta...
python
{ "resource": "" }
q53852
_auth_required
train
def _auth_required(method, validator): """Decorate a HTTP verb method and check the request is authenticated :param method: a tornado.web.RequestHandler method :param validator: a token validation coroutine, that should return True/False depending if token is or is not valid """ @gen.coroutine ...
python
{ "resource": "" }
q53853
authorized
train
def authorized(validator): """Decorate a RequestHandler or method to require that a request is authorized If decorating a coroutine make sure coroutine decorator is first. eg.:: class Handler(tornado.web.RequestHandler): @authorized(validator) @coroutine def ge...
python
{ "resource": "" }
q53854
print_input_output
train
def print_input_output(opts): """ Prints the input and output directories to the console. :param opts: namespace that contains printable 'input' and 'output' fields. """ if opts.is_dir: print("Root input directory:\t" + opts.input) print("Outputting to:\t\t" + opts.output + "\n") ...
python
{ "resource": "" }
q53855
print_files
train
def print_files(opts, file_paths): """ Prints the file paths that will be parsed. :param file_paths: """ print("Parsing the following files:") for file_path in file_paths: print(" " + strip_prefix(file_path, opts.abs_input)) print("--------------------") print(str(len(file_path...
python
{ "resource": "" }
q53856
print_no_files_found
train
def print_no_files_found(opts): """ Prints message that no files were found in the input directory with the given list of extensions. :param opts: Namespace object created from command-line arguments. Must have the attributes 'extensions' and 'input' """ msg = "No files found with [" +', '...
python
{ "resource": "" }
q53857
print_duplicate_anchor_information
train
def print_duplicate_anchor_information(duplicate_tags): """ Prints information about duplicate AnchorHub tags found during collection. :param duplicate_tags: Dictionary mapping string file path keys to a list of tuples. The tuples contain the following information, in order: 1. The string ...
python
{ "resource": "" }
q53858
print_modified_files
train
def print_modified_files(opts, anchors): """ Prints out which files were modified amongst those looked at :param anchors: Dictionary mapping file path strings to dictionaries containing AnchorHub tag/generated header key-value pairs """ print("Files with modifications:") for file_path i...
python
{ "resource": "" }
q53859
print_summary_stats
train
def print_summary_stats(counter): """ Prints summary statistics about which writer strategies were used, and how much they were used. :param counter: A list of lists. The first entry on the inner list is a number count of how many times a WriterStrategy was used, and the second entry is...
python
{ "resource": "" }
q53860
funTransQuadF
train
def funTransQuadF(k, s): """ Focusing quad in X, defocusing in Y :param k: k1, in [T/m] :param s: width, in [m] :return: 2x2 numpy array """ sqrtk = np.sqrt(complex(k)) a = np.cos(sqrtk * s) b = np.sin(sqrtk * s) / sqrtk c = -sqrtk * np.sin(sqrtk * s) d = np.cos(sqrtk * s) r...
python
{ "resource": "" }
q53861
funTransQuadD
train
def funTransQuadD(k, s): """ Defocusing quad in X, focusing in Y :param k: k1, in [T/m] :param s: width, in [m] :return: 2x2 numpy array """ sqrtk = np.sqrt(complex(k)) a = np.cosh(sqrtk * s) b = np.sinh(sqrtk * s) / sqrtk c = sqrtk * np.sinh(sqrtk * s) d = np.cosh(sqrtk * s) ...
python
{ "resource": "" }
q53862
funTransEdgeX
train
def funTransEdgeX(theta, rho): """ Fringe matrix in X :param theta: fringe angle, in [rad] :param rho: bend radius, in [m] :return: 2x2 numpy array """ return np.matrix([[1, 0], [np.tan(theta) / rho, 1]], dtype=np.double)
python
{ "resource": "" }
q53863
funTransEdgeY
train
def funTransEdgeY(theta, rho): """ Fringe matrix in Y :param theta: fringe angle, in [rad] :param rho: bend radius, in [m] :return: 2x2 numpy array """ return np.matrix([[1, 0], [-np.tan(theta) / rho, 1]], dtype=np.double)
python
{ "resource": "" }
q53864
funTransSectX
train
def funTransSectX(theta, rho): """ Sector matrix in X :param theta: bend angle, in [rad] :param rho: bend radius, in [m] :return: 2x2 numpy array """ return np.matrix([[np.cos(theta), rho * np.sin(theta)], [-np.sin(theta) / rho, np.cos(theta)]], dtype=np.double)
python
{ "resource": "" }
q53865
funTransSectY
train
def funTransSectY(theta, rho): """ Sector matrix in Y :param theta: bend angle, in [rad] :param rho: bend radius, in [m] :return: 2x2 numpy array """ return np.matrix([[1, rho * theta], [0, 1]], dtype=np.double)
python
{ "resource": "" }
q53866
funTransChica
train
def funTransChica(imagl, idril, ibfield, gamma0, xoy='x'): """ Chicane matrix, composed of four rbends, seperated by drifts :param imagl: rbend width, in [m] :param idril: drift length between two adjacent rbends, in [m] :param ibfield: rbend magnetic strength, in [T] :param gamma0: electron energy...
python
{ "resource": "" }
q53867
transDrift
train
def transDrift(length=0.0, gamma=None): """ Transport matrix of drift :param length: drift length in [m] :param gamma: electron energy, gamma value :return: 6x6 numpy array """ m = np.eye(6, 6, dtype=np.float64) if length == 0.0: print("warning: 'length' should be a positive float n...
python
{ "resource": "" }
q53868
transQuad
train
def transQuad(length=0.0, k1=0.0, gamma=None): """ Transport matrix of quadrupole :param length: quad width in [m] :param k1: quad k1 strength in [T/m] :param gamma: electron energy, gamma value :return: 6x6 numpy array """ m = np.eye(6, 6, dtype=np.float64) if length == 0.0: pr...
python
{ "resource": "" }
q53869
transSect
train
def transSect(theta=None, rho=None, gamma=None): """ Transport matrix of sector dipole :param theta: bending angle in [RAD] :param rho: bending radius in [m] :param gamma: electron energy, gamma value :return: 6x6 numpy array """ m = np.eye(6, 6, dtype=np.float64) if None in (theta, rho...
python
{ "resource": "" }
q53870
transRbend
train
def transRbend(theta=None, rho=None, gamma=None, incsym=-1): """ Transport matrix of rectangle dipole :param theta: bending angle in [RAD] :param incsym: incident symmetry, -1 by default, available options: * -1: left half symmetry, * 0: full symmetry, * 1: right...
python
{ "resource": "" }
q53871
transFringe
train
def transFringe(beta=None, rho=None): """ Transport matrix of fringe field :param beta: angle of rotation of pole-face in [RAD] :param rho: bending radius in [m] :return: 6x6 numpy array """ m = np.eye(6, 6, dtype=np.float64) if None in (beta, rho): print("warning: 'theta', 'rho' sh...
python
{ "resource": "" }
q53872
transChicane
train
def transChicane(bend_length=None, bend_field=None, drift_length=None, gamma=None): """ Transport matrix of chicane composed of four rbends and three drifts between them :param bend_length: rbend width in [m] :param bend_field: rbend magnetic field in [T] :param drift_length: drift length, list...
python
{ "resource": "" }
q53873
Chicane.setParams
train
def setParams(self, bend_length, bend_field, drift_length, gamma): """ set chicane parameters :param bend_length: bend length, [m] :param bend_field: bend field, [T] :param drift_length: drift length, [m], list :param gamma: electron energy, gamma :return: None "...
python
{ "resource": "" }
q53874
Chicane._setDriftList
train
def _setDriftList(self, drift_length): """ set drift length list of three elements :param drift_length: input drift_length in [m], single float, or list/tuple of float numbers """ if isinstance(drift_length, tuple) or isinstance(drift_length, list): if len(drift_length) == 1...
python
{ "resource": "" }
q53875
Chicane.getMatrix
train
def getMatrix(self): """ get transport matrix with ``mflag`` flag, if ``mflag`` is True, return calculated matrix, else return unity matrix :return: transport matrix """ if self.mflag: m0 = 9.10938215e-31 e0 = 1.602176487e-19 c0 = 299792458.0 ...
python
{ "resource": "" }
q53876
Chicane.getAngle
train
def getAngle(self, mode='deg'): """ return bend angle :param mode: 'deg' or 'rad' :return: deflecting angle in RAD """ if self.refresh is True: self.getMatrix() try: if self.mflag: if mode == 'deg': return self...
python
{ "resource": "" }
q53877
Chicane.setBendLength
train
def setBendLength(self, x): """ set bend length :param x: new bend length to be assigned, [m] :return: None """ if x != self.bend_length: self.bend_length = x self.refresh = True
python
{ "resource": "" }
q53878
Chicane.setBendField
train
def setBendField(self, x): """ set bend magnetic field :param x: new bend field to be assigned, [T] :return: None """ if x != self.bend_field: self.bend_field = x self.refresh = True
python
{ "resource": "" }
q53879
Chicane.setDriftLength
train
def setDriftLength(self, x): """ set lengths for drift sections :param x: single double or list :return: None :Example: >>> import beamline >>> chi = beamline.mathutils.Chicane(bend_length=1,bend_field=0.5,drift_length=1,gamma=1000) >>> chi.getMatrix() ...
python
{ "resource": "" }
q53880
Chicane.setGamma
train
def setGamma(self, x): """ set electron energy, gamma value :param x: new energy, gamma value :return: None """ if x != self.gamma: self.gamma = x self.refresh = True
python
{ "resource": "" }
q53881
_is_valid_extension
train
def _is_valid_extension(extension): """Checks if the file extension is blacklisted in valid_extensions. :param str extension: a file extension to check :returns: flag indicating if the extension is valid based on list of valid extensions. :rtype: bool """ if not cfg.CONF.valid_ext...
python
{ "resource": "" }
q53882
_is_blacklisted_filename
train
def _is_blacklisted_filename(filepath): """Checks if the filename matches filename_blacklist blacklist is a list of filenames(str) and/or file patterns(dict) string, specifying an exact filename to ignore [".DS_Store", "Thumbs.db"] mapping(dict), where each dict contains: 'match' - (if th...
python
{ "resource": "" }
q53883
retrieve_files
train
def retrieve_files(): """Get list of files found in provided locations. Search through the paths provided to find files for processing. :returns: absolute path of filename :rtype: list """ all_files = [] for location in cfg.CONF.locations or []: # if local path then make sure it i...
python
{ "resource": "" }
q53884
NotificationsManager.__offset_notifiers
train
def __offset_notifiers(self, offset): """ Offsets existing notifiers. :param offset: Offset. :type offset: int """ overall_offset = offset for notifier in self.__notifiers: notifier.vertical_offset = overall_offset notifier.refresh_positi...
python
{ "resource": "" }
q53885
NotificationsManager.register_notification
train
def register_notification(self, notification): """ Registers given notification. :param notification: Notification to register. :type notification: Notification :return: Method success. :rtype: bool """ LOGGER.debug("> Registering notification: '{0}'.".f...
python
{ "resource": "" }
q53886
NotificationsManager.format_notification
train
def format_notification(self, notification): """ Formats given notification. :param notification: Notification to format. :type notification: Notification :return: Method success. :rtype: bool """ return "{0} | '{1}'".format(time.ctime(notification.time)...
python
{ "resource": "" }
q53887
NotificationsManager.notify
train
def notify(self, message, duration=3000, notification_clicked_slot=None, message_level="Information", **kwargs): """ Displays an Application notification. :param message: Notification message. :type message: unicode :param duration: Notification display duration. :type d...
python
{ "resource": "" }
q53888
NotificationsManager.warnify
train
def warnify(self, message, duration=3000, notification_clicked_slot=None, **kwargs): """ Displays an Application notification warning. :param message: Notification message. :type message: unicode :param duration: Notification display duration. :type duration: int ...
python
{ "resource": "" }
q53889
has_data
train
def has_data(d, fullname): """Test if any of the `keys` of the `d` dictionary starts with `fullname`. """ fullname = r'%s-' % (fullname, ) for k in d: if not k.startswith(fullname): continue return True return False
python
{ "resource": "" }
q53890
FormSet.get_form
train
def get_form(self, index): """Returns the n-index form, where index is 1-based. the form'll be filled with data if it exists or empty if not """ index = max(1, index) if len(self._forms) >= index: return self._forms[index - 1] return self.get_empty_form(index)
python
{ "resource": "" }
q53891
FormSet._find_new_forms
train
def _find_new_forms(self, forms, num, data, files, locale, tz): """Acknowledge new forms created client-side. """ fullname = self._get_fullname(num) while has_data(data, fullname) or has_data(files, fullname): f = self._form_class( data, files=files, locale=lo...
python
{ "resource": "" }
q53892
get_idxs
train
def get_idxs(exprs): """ Finds sympy.tensor.indexed.Idx instances and returns them. """ idxs = set() for expr in (exprs): for i in expr.find(sympy.Idx): idxs.add(i) return sorted(idxs, key=str)
python
{ "resource": "" }
q53893
_md5sum
train
def _md5sum(file_path): """ Helper function that builds and md5sum from a file in chunks. Args: file_path: The path to the file you want an md5sum for. Returns: A string containing an md5sum. """ md5 = hashlib.md5() with open(file_path, "rb") as md5_file: while True: ...
python
{ "resource": "" }
q53894
Annex.reload
train
def reload(self): """ Reloads modules from the current plugin_dirs. This method will search the plugin_dirs attribute finding new plugin modules, updating plugin modules that have changed, and unloading plugin modules that no longer exist. """ logger.debug("Reloading Pl...
python
{ "resource": "" }
q53895
bind_type
train
def bind_type(python_value): """Return a Gibica type derived from a Python type.""" binding_table = {'bool': Bool, 'int': Int, 'float': Float} if python_value is None: return NoneType() python_type = type(python_value) gibica_type = binding_table.get(python_type.__name__) if gibica_t...
python
{ "resource": "" }
q53896
Int._handle_type
train
def _handle_type(self, other): """Helper to handle the return type.""" if isinstance(other, Int): return Int elif isinstance(other, Float): return Float else: raise TypeError( f"Unsuported operation between `{type(self)}` and `{type(oth...
python
{ "resource": "" }
q53897
dbapi
train
def dbapi(conf=cfg.CONF): """Retrieves an instance of the configured database API. :param oslo_config.cfg.ConfigOpts conf: an instance of the configuration file :return: database API instance :rtype: :class:`~tvrenamer.cache.api.DatabaseAPI` """ globa...
python
{ "resource": "" }
q53898
JsonCache.write
train
def write(self): """ Write contents of cache to disk. """ io.debug("Storing cache '{0}'".format(self.path)) with open(self.path, "w") as file: json.dump(self._data, file, sort_keys=True, indent=2, separators=(',', ': '))
python
{ "resource": "" }
q53899
FSCache.keypath
train
def keypath(self, key): """ Get the filesystem path for a key. Arguments: key: Key. Returns: str: Absolute path. """ return fs.path(self.path, self.escape_key(key))
python
{ "resource": "" }