_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q54200
parse_modeString
train
def parse_modeString(s): """ Parses a modeString like '1024 x 768 @ 60' """ refresh, width, height = None, None, None if '@' in s: s, refresh = s.split('@', 1) refresh = int(refresh) if 'x' in s: width, height = [int(x) if x.strip() else No...
python
{ "resource": "" }
q54201
format_modes
train
def format_modes(modes, full_modes=False, current_mode=None): """ Creates a nice readily printable Table for a list of modes. Used in `displays list' and the candidates list in `displays set'. """ t = table.Table((( '*' if mode == current_mode else '', ...
python
{ "resource": "" }
q54202
ModuleNode.update_node_attributes
train
def update_node_attributes(self, attributes_flags=int(Qt.ItemIsSelectable | Qt.ItemIsEnabled)): """ Updates the Node attributes. :param attributes_flags: Attributes flags. :type attributes_flags: int :return: Method success. :rtype: bool """ self.traced....
python
{ "resource": "" }
q54203
JsonLogFormatter.format
train
def format(self, record): """ Map from Python LogRecord attributes to JSON log format fields * from - https://docs.python.org/3/library/logging.html#logrecord-attributes * to - https://mana.mozilla.org/wiki/pages/viewpage.action?pageId=42895640 """ out = dict( ...
python
{ "resource": "" }
q54204
find_candidate_splays
train
def find_candidate_splays(splays, azm, inc, delta=LRUD_DELTA): """Given a list of splay shots, find candidate LEFT or RIGHT given target AZM and INC""" return [splay for splay in splays if angle_delta(splay['AZM'], azm) <= delta/2 and angle_delta(splay['INC'], inc...
python
{ "resource": "" }
q54205
encode_df
train
def encode_df(df, data_types={}): """ Encode columns so their values are usable in vector operations. Making a few assumptions here, like that datetime should be an integer, and that it's acceptable to fill NaNs with 0. """ numbers = [] categories = [] datetimes = [] for ...
python
{ "resource": "" }
q54206
SMTPSession._add_help_noop_and_quit_transitions
train
def _add_help_noop_and_quit_transitions(self): """HELP, NOOP and QUIT should be possible from everywhere so we need to add these transitions to all states configured so far.""" states = set() for state_name in self.state.known_states(): if state_name not in ['new', 'finished'...
python
{ "resource": "" }
q54207
SMTPSession.get_ehlo_lines
train
def get_ehlo_lines(self): """Return the capabilities to be advertised after EHLO.""" lines = [] if self._authenticator != None: # TODO: Make the authentication pluggable but separate mechanism # from user look-up. lines.append('AUTH PLAIN') if self._po...
python
{ "resource": "" }
q54208
SMTPSession._dispatch_commands
train
def _dispatch_commands(self, from_state, to_state, smtp_command): """This method dispatches a SMTP command to the appropriate handler method. It is called after a new command was received and a valid transition was found.""" #print from_state, ' -> ', to_state, ':', smtp_command ...
python
{ "resource": "" }
q54209
SMTPSession.close_connection
train
def close_connection(self): "Request a connection close from the SMTP session handling instance." if self._is_connected: self._is_connected = False self._command_parser.close_when_done()
python
{ "resource": "" }
q54210
SMTPSession.smtp_greet
train
def smtp_greet(self): """This method handles not a real smtp command. It is called when a new connection was accepted by the server.""" # Policy check was done when accepting the connection so we don't have # to do it here again. primary_hostname = self._command_parser.primary_ho...
python
{ "resource": "" }
q54211
update_project_files
train
def update_project_files(cfg, proj_version): """ Update version string in project files :rtype : dict :param cfg:project configuration :param proj_version:current version :return:dict :raise ValueError: """ counters = {'files': 0, 'changes': 0} for project_file in cfg.files: ...
python
{ "resource": "" }
q54212
save_version_and_update_files
train
def save_version_and_update_files(cfg, version_file, version_to_save): """Save version to version_file and commit changes if required :param cfg: :param version_file: :param version_to_save: :return: """ with vcs.VCS(cfg.vcs_engine) as vcs_handler: if cfg.commit: vcs_han...
python
{ "resource": "" }
q54213
replace_env_vars
train
def replace_env_vars(conf): """Fill `conf` with environment variables, where appropriate. Any value of the from $VAR will be replaced with the environment variable VAR. If there are sub dictionaries, this function will recurse. This will preserve the original dictionary, and return a copy. """ ...
python
{ "resource": "" }
q54214
CertificateManager.verifyCertificate
train
def verifyCertificate(self, name): """Verify a certificate """ certPath = os.path.join(self.basePath, self.DIR_CERTS, '%s.cert.pem' % name) if not os.path.isfile(certPath): raise ValueError('Certificate [%s] not found' % certPath) if subprocess.call([ 'openssl', 'x509...
python
{ "resource": "" }
q54215
CertificateManager.createRootCertificate
train
def createRootCertificate(self, noPass = False, keyLength = 4096): """Create a root certificate """ configPath, keyPath, certPath = \ os.path.join(self.basePath, self.FILE_CONFIG), \ os.path.join(self.basePath, self.DIR_PRIVATE, self.FILE_CA_KEY), \ ...
python
{ "resource": "" }
q54216
CertificateManager.createClientCertificate
train
def createClientCertificate(self, name, noPass = True, keyLength = 2048, days = 375): """Create a client certificate """ if not name: raise ValueError('Require name') configPath, keyPath, csrPath, certPath = \ os.path.join(self.basePath, self.FILE_CONFIG), \ ...
python
{ "resource": "" }
q54217
validate_python_version
train
def validate_python_version(): """Validate python interpreter version. Only 3.3+ allowed.""" python_version = LooseVersion(platform.python_version()) minimal_version = LooseVersion('3.3.0') if python_version < minimal_version: print("Sorry, Python 3.3+ is required") sys.exit(1)
python
{ "resource": "" }
q54218
GDataRow.save
train
def save(self): """Save the row back to the spreadsheet""" if self._sheet.readonly: raise ReadOnlyException if not self._changed: # nothing to save return gd_client = self._sheet.client assert gd_client is not None try: entr...
python
{ "resource": "" }
q54219
GDataRow.delete
train
def delete(self): """Delete the row from the spreadsheet""" if self._sheet.readonly: raise ReadOnlyException gd_client = self._sheet.client assert gd_client is not None return gd_client.DeleteRow(self._entry)
python
{ "resource": "" }
q54220
GSpreadsheet.get_client
train
def get_client(self, email=None, password=None, **__): """Get the google data client.""" if self.client is not None: return self.client return Auth(email, password)
python
{ "resource": "" }
q54221
GSpreadsheet.get_feed
train
def get_feed(self): """Get the gdata spreadsheet feed.""" return self.client.GetListFeed(self.key, self.worksheet, visibility='private' if self.is_authed else 'public', # TODO always use projection='values' ? What does full give me? projection='full' if self.is_authed...
python
{ "resource": "" }
q54222
GSpreadsheet.list_worksheets
train
def list_worksheets(self): """ List what worksheet keys exist Returns a list of tuples of the form: (WORKSHEET_ID, WORKSHEET_NAME) You can then retrieve the specific WORKSHEET_ID in the future by constructing a new GSpreadsheet(worksheet=WORKSHEET_ID, ...) ""...
python
{ "resource": "" }
q54223
GSpreadsheet.next
train
def next(self): """Retrieve the next row.""" # I'm pretty sure this is the completely wrong way to go about this, but # oh well, this works. if not hasattr(self, '_iter'): self._iter = self.readrow_as_dict() return self._iter.next()
python
{ "resource": "" }
q54224
GSpreadsheet.append
train
def append(self, row_dict): """Add a row to the spreadsheet, returns the new row""" # TODO validate row_dict.keys() match # TODO check self.is_authed entry = self.client.InsertRow(row_dict, self.key, self.worksheet) self.feed.entry.append(entry) return GDataRow(entry, she...
python
{ "resource": "" }
q54225
ScheduledJob.reschedule
train
def reschedule(self, date, callable_name=None, content_object=None, expires='7d', args=None, kwargs=None): """Schedule a clone of this job.""" # Resolve date relative to the expected start of the current job. if isinstance(date, basestring): date = parse_timedelta(...
python
{ "resource": "" }
q54226
defaultnamedtuple
train
def defaultnamedtuple(typename, field_names, defaults=()): """ Generates a new subclass of tuple with default values. Parameters ---------- typename : string The name of the class. field_names : str or iterable An iterable of splitable string. defaults : iterable Default...
python
{ "resource": "" }
q54227
convert_filename
train
def convert_filename(txtfilename, outdir='.'): """Convert a .TXT filename to a Therion .TH filename""" return os.path.join(outdir, os.path.basename(txtfilename)).rsplit('.', 1)[0] + '.th'
python
{ "resource": "" }
q54228
thconfig
train
def thconfig(txtfiles, cavename='cave'): """Write `thconfig` file for the Therion project""" fmts_model = ['lox', '3d', 'dxf', 'kml', 'plt', 'vrml'] outfilename = 'thconfig' with open(outfilename, 'w') as outfile: for txtfilename in txtfiles: print >> outfile, 'source "%s"' % conver...
python
{ "resource": "" }
q54229
wrap_around_re
train
def wrap_around_re(aClass, wildcard, advice): """ Same as wrap_around but works with regular expression based wildcards to map which methods are going to be used. """ matcher = re.compile(wildcard) for aMember in dir(aClass): realMember = getattr(aClass, aMember) if callable(real...
python
{ "resource": "" }
q54230
_with_wrap
train
def _with_wrap(advice, method, instances=[]): """ with_wrap wraps the execution of method inside given generator. When the method is called, the generator is invoked with the parameters the method call contains. If the generator yields, the yielded values define the new parameters to the method....
python
{ "resource": "" }
q54231
wrap_count
train
def wrap_count(method): """ Returns number of wraps around given method. """ number = 0 while hasattr(method, '__aspects_orig'): number += 1 method = method.__aspects_orig return number
python
{ "resource": "" }
q54232
DatabaseAPI.update
train
def update(self, instance, condition): """Update the instance to the database :param instance: an instance of modeled data object :param condition: condition evaluated to determine record(s) to update :returns: record id updated or None :rtype: int """ item = sel...
python
{ "resource": "" }
q54233
Node.setShape
train
def setShape(self, shape): """Set the shape of the node. Shape must be a list containing x,y,z coords as numbers to represent the shape of the node. """ for pp in shape: if len(pp) != 3: raise ValueError('shape point must consist of x,y,z') se...
python
{ "resource": "" }
q54234
Connection.load
train
def load(self, args): """ Load a simulation from the given arguments. """ self._queue.append(tc.CMD_LOAD) self._string += struct.pack("!BiB", 0, 1 + 4 + 1 + 1 + 4 + sum(map(len, args)) + 4 * len(args), tc.CMD_LOAD) self._packStringList(args) self._sendExact()
python
{ "resource": "" }
q54235
Plugin._excepthook
train
def _excepthook(self, etype, evalue, trace): """ internal exception hook """ if etype == ArgumentParserError: self.exit(code=CRITICAL, message='error: {0}'.format(evalue), extdata=self.parser.format_usage()) else: ...
python
{ "resource": "" }
q54236
Plugin._timeout_handler
train
def _timeout_handler(self, signum, frame): """ internal timeout handler """ msgfmt = 'plugin timed out after {0} seconds' self.exit(code=self._timeout_code, message=msgfmt.format(self._timeout_delay))
python
{ "resource": "" }
q54237
Plugin.set_timeout
train
def set_timeout(self, timeout=None, code=None): """ set the timeout for plugin operations when timeout is reached, exit properly with nagios-compliant output arguments: timeout: timeout in seconds code: exit status code """ if timeout is None: ...
python
{ "resource": "" }
q54238
Plugin.exit
train
def exit(self, code=None, message=None, perfdata=None, extdata=None): """ manual exit from the plugin arguments: code: exit status code message: a short, one-line message to display perfdata: perfdata, if any extdata: multi-line message to give mo...
python
{ "resource": "" }
q54239
Plugin.finish
train
def finish(self, code=None, message=None, perfdata=None, extdata=None): """ exit when using internal function to add results automatically generates output, but each parameter can be overriden all parameters are optional arguments: code: exit status code ...
python
{ "resource": "" }
q54240
Plugin.parse_args
train
def parse_args(self, arguments=None): """ parses the arguments from command-line arguments: optional argument list to parse returns: a dictionnary containing the arguments """ self._args = self.parser.parse_args(arguments) return self.arg...
python
{ "resource": "" }
q54241
Plugin.add_result
train
def add_result(self, code, message=None): """ add a result to the internal result list arguments: same arguments as for Result() """ self._results.append(Result(code, message))
python
{ "resource": "" }
q54242
Plugin.get_code
train
def get_code(self): """ the final code for multi-checks arguments: the worst-case code from all added results, or UNKNOWN if none were added """ code = UNKNOWN for result in self._results: if code == UNKNOWN or (result.code < UNKNOWN ...
python
{ "resource": "" }
q54243
Plugin.get_message
train
def get_message(self, msglevels=None, joiner=None): """ the final message for mult-checks arguments: msglevels: an array of all desired levels (ex: [CRITICAL, WARNING]) joiner: string used to join all messages (default: ', ') returns: one-line messag...
python
{ "resource": "" }
q54244
Plugin.add_perfdata
train
def add_perfdata(self, *args, **kwargs): """ add a perfdata to the internal perfdata list arguments: the same arguments as for Perfdata() """ self._perfdata.append(Perfdata(*args, **kwargs))
python
{ "resource": "" }
q54245
Threshold._parse
train
def _parse(self, threshold): """ internal threshold string parser arguments: threshold: string describing the threshold """ match = re.search(r'^(@?)((~|\d*):)?(\d*)$', threshold) if not match: raise ValueError('Error parsing Threshold: {0}'.form...
python
{ "resource": "" }
q54246
Threshold.check
train
def check(self, value): """ check if a value is correct according to threshold arguments: value: the value to check """ if self._inclusive: return False if self._min <= value <= self._max else True else: return False if value > self._m...
python
{ "resource": "" }
q54247
merge
train
def merge(d, *dicts): """ Recursively merges dictionaries """ for d_update in dicts: if not isinstance(d, dict): raise TypeError("{0} is not a dict".format(d)) dict_merge_pair(d, d_update) return d
python
{ "resource": "" }
q54248
dict_merge_pair
train
def dict_merge_pair(d1, d2): """ Recursively merges values from d2 into d1. """ for key in d2: if key in d1 and isinstance(d1[key], dict) and \ isinstance(d2[key], dict): dict_merge_pair(d1[key], d2[key]) else: d1[key] = d2[key] return d1
python
{ "resource": "" }
q54249
Python.get_all_objects
train
def get_all_objects(self): "Return pointers to all GC tracked objects" for i, generation in enumerate(self.gc_generations): generation_head_ptr = pygc_head_ptr = generation.head.get_pointer() generation_head_addr = generation_head_ptr._value while True: ...
python
{ "resource": "" }
q54250
connect
train
def connect(port=8813, numRetries=10, host="localhost", proc=None): """ Establish a connection to a TraCI-Server and return the connection object. The connection is not saved in the pool and not accessible via traci.switch. It should be safe to use different connections established by this method in...
python
{ "resource": "" }
q54251
init
train
def init(port=8813, numRetries=10, host="localhost", label="default"): """ Establish a connection to a TraCI-Server and store it under the given label. This method is not thread-safe. It accesses the connection pool concurrently. """ _connections[label] = connect(port, numRetries, host) swit...
python
{ "resource": "" }
q54252
start
train
def start(cmd, port=None, numRetries=10, label="default"): """ Start a sumo server using cmd, establish a connection to it and store it under the given label. This method is not thread-safe. """ if port is None: port = sumolib.miscutils.getFreeSocketPort() sumoProcess = subprocess.Popen(...
python
{ "resource": "" }
q54253
interface_direct_class
train
def interface_direct_class(data_class): """help to direct to the correct interface interacting with DB by class name only""" if data_class in ASSET: interface = AssetsInterface() elif data_class in PARTY: interface = PartiesInterface() elif data_class in BOOK: interface = BooksIn...
python
{ "resource": "" }
q54254
interface_direct_csvpath
train
def interface_direct_csvpath(csvpath): """help to direct to the correct interface interacting with DB by csvfile path""" with open(csvpath) as csvfile: reader = csv.DictReader(csvfile) for row in reader: data_class = row.pop('amaasclass', '') return interface_direct_class...
python
{ "resource": "" }
q54255
process_normal
train
def process_normal(_dict): """ this method process the _dict to correct dict to be called by class constructor this method will be imported and called by main csv uploader function """ cooked_dict = group_raw_to_formatted_string_dict(_dict) data_class = cooked_dict.pop('amaasclass', '') chil...
python
{ "resource": "" }
q54256
alti_data.track_list
train
def track_list(self,*args): ''' return the list of tracks contained if the dataset ''' noargs = len(args) == 0 return np.unique(self.track) if noargs else np.unique(self.track.compress(args[0]))
python
{ "resource": "" }
q54257
alti_data.cycle_list
train
def cycle_list(self,*args): ''' return the list of cycles contained if the dataset ''' noargs = len(args) == 0 return np.unique(self.cycle) if noargs else np.unique(self.cycle.compress(args[0]))
python
{ "resource": "" }
q54258
parse_location
train
def parse_location(data): """ Parses given location data. :param data: Exception. :type data: Exception :return: Location object. :rtype: Location """ tokens = data.split(",") location = Location(directories=[], files=[], filters_in=[], filters_out=[], targets=[]) if not tokens...
python
{ "resource": "" }
q54259
get_resource_path
train
def get_resource_path(name, raise_exception=False): """ Returns the resource file path matching the given name. :param name: Resource name. :type name: unicode :param raise_exception: Raise the exception. :type raise_exception: bool :return: Resource path. :rtype: unicode """ i...
python
{ "resource": "" }
q54260
get_sections_file_parser
train
def get_sections_file_parser(file): """ Returns a sections file parser. :param file: File. :type file: unicode :return: Parser. :rtype: SectionsFileParser """ if not foundations.common.path_exists(file): raise foundations.exceptions.FileExistsError( "{0} | '{1}' sec...
python
{ "resource": "" }
q54261
store_last_browsed_path
train
def store_last_browsed_path(data): """ Defines a wrapper method used to store the last browsed path. :param data: Path data. :type data: QString or QList :return: Last browsed path. :rtype: unicode """ if type(data) in (tuple, list, QStringList): data = [foundations.strings.to_...
python
{ "resource": "" }
q54262
signals_blocker
train
def signals_blocker(instance, attribute, *args, **kwargs): """ Blocks given instance signals before calling the given attribute with \ given arguments and then unblocks the signals. :param instance: Instance object. :type instance: QObject :param attribute: Attribute to call. :type attribut...
python
{ "resource": "" }
q54263
show_wait_cursor
train
def show_wait_cursor(object): """ Shows a wait cursor while processing. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def show_wait_cursorWrapper(*args, **kwargs): """ Shows a wait cursor while p...
python
{ "resource": "" }
q54264
set_toolBox_height
train
def set_toolBox_height(tool_box, height=32): """ Sets given height to given QToolBox widget. :param toolbox: ToolBox. :type toolbox: QToolBox :param height: Height. :type height: int :return: Definition success. :rtype: bool """ for button in tool_box.findChildren(QAbstractButt...
python
{ "resource": "" }
q54265
set_children_padding
train
def set_children_padding(widget, types, height=None, width=None): """ Sets given Widget children padding. :param widget: Widget to sets the children padding. :type widget: QWidget :param types: Children types. :type types: tuple or list :param height: Height padding. :type height: int ...
python
{ "resource": "" }
q54266
PostgresPool.cursor
train
def cursor(self, autocommit=True): ''' When a connection exits the with block, - the tx is committed if no errors were encountered - the tx is rolled back if errors When a cursor exits its with block it is closed, without affecting the state of the transaction. ...
python
{ "resource": "" }
q54267
Cipher.sign
train
def sign(self, msg): """sign a message""" signature = SHA256.new() signature.update(self._mackey1) signature.update(msg) signature.update(self._mackey2) return signature.digest()
python
{ "resource": "" }
q54268
Cipher.encrypt
train
def encrypt(self, msg): """encrypts a message""" iv = self.random_bytes(AES.block_size) ctr = Counter.new(AES.block_size * 8, initial_value=self.bin2long(iv)) cipher = AES.AESCipher(self._cipherkey, AES.MODE_CTR, counter=ctr) cipher_text = cipher.encrypt(msg) intermediate...
python
{ "resource": "" }
q54269
Cipher.decrypt
train
def decrypt(self, msg): """decrypt a message""" error = False signature = msg[0:SHA256.digest_size] iv = msg[SHA256.digest_size:SHA256.digest_size + AES.block_size] cipher_text = msg[SHA256.digest_size + AES.block_size:] if self.sign(iv + cipher_text) != signature: ...
python
{ "resource": "" }
q54270
PatchesManager.get
train
def get(self, patch, default=None): """ Returns given patch value. :param patch: Patch name. :type patch: unicode :param default: Default value if patch is not found. :type default: object :return: Action. :rtype: QAction """ try: ...
python
{ "resource": "" }
q54271
PatchesManager.register_patch
train
def register_patch(self, name, path): """ Registers given patch. :param name: Patch name. :type name: unicode :param path: Patch path. :type path: unicode :return: Method success. :rtype: bool """ patch = foundations.strings.get_splitext_...
python
{ "resource": "" }
q54272
PatchesManager.register_patches
train
def register_patches(self): """ Registers the patches. :return: Method success. :rtype: bool """ if not self.__paths: return False unregistered_patches = [] for path in self.paths: for file in foundations.walkers.files_walker(pat...
python
{ "resource": "" }
q54273
PatchesManager.apply_patch
train
def apply_patch(self, patch): """ Applies given patch. :param patch: Patch. :type patch: Patch :return: Method success. :rtype: bool """ history_file = File(self.__history_file) patches_history = history_file.cache() and [line.strip() for line in...
python
{ "resource": "" }
q54274
PatchesManager.apply_patches
train
def apply_patches(self): """ Applies the patches. :return: Method success. :rtype: bool """ success = True for name, patch in sorted(self): success = self.apply_patch(patch) return success
python
{ "resource": "" }
q54275
PatchesManager.get_patch_from_uid
train
def get_patch_from_uid(self, uid): """ Returns the patch with given uid. :param uid: Patch uid. :type uid: unicode :return: Patch. :rtype: Patch """ for name, patch in self: if patch.uid == uid: return patch
python
{ "resource": "" }
q54276
help
train
def help(*args): """Prints help.""" from . import commands parser = argparse.ArgumentParser(prog="%s %s" % (__package__, help.__name__), description=help.__doc__) parser.add_argument('COMMAND', help="command to show help for", nargs="?", choices=__all__) args = parser.parse_args(args) if args.CO...
python
{ "resource": "" }
q54277
fcd2dri
train
def fcd2dri(inpFCD, outSTRM, ignored): """ Reformats the contents of the given fcd-output file into a .dri file, readable by PHEM. The fcd-output "fcd" must be a valid file name of an fcd-output. The following may be a matter of changes: - the engine torque is not given """ # print >> outST...
python
{ "resource": "" }
q54278
net2str
train
def net2str(net, outSTRM): """ Writes the network object given as "inpNET" as a .str file readable by PHEM. Returns a map from the SUMO-road id to the generated numerical id used by PHEM. The following may be a matter of changes: - currently, only the positions of the start and the end nodes are wr...
python
{ "resource": "" }
q54279
fcd2fzp
train
def fcd2fzp(inpFCD, outSTRM, further): """ Reformats the contents of the given fcd-output file into a .fzp file, readable by PHEM. The fcd-output "fcd" must be a valid file name of an fcd-output. The "sIDm" parameter must be a map from SUMO-edge ids to their numerical representation as generated by...
python
{ "resource": "" }
q54280
vehicleTypes2flt
train
def vehicleTypes2flt(outSTRM, vtIDm): """ Currently, rather a stub than an implementation. Writes the vehicle ids stored in the given "vtIDm" map formatted as a .flt file readable by PHEM. The following may be a matter of changes: - A default map is assigned to all vehicle types with the same proba...
python
{ "resource": "" }
q54281
normalize_hex
train
def normalize_hex(hex_color): """Transform a xxx hex color to xxxxxx. """ hex_color = hex_color.replace('#', '').lower() length = len(hex_color) if length in (6, 8): return '#' + hex_color if length not in (3, 4): return None strhex = u'#%s%s%s' % ( hex_color[0] * 2, ...
python
{ "resource": "" }
q54282
MRSData.inherit
train
def inherit(self, new_array): """ Converts a generic numpy ndarray into an MRSData instance by copying its own MRS specific parameters. This is useful when performing some processing on the MRSData object gives a bare NDArray result. :param new_array: the ndarray to be converted...
python
{ "resource": "" }
q54283
MRSData.spectrum
train
def spectrum(self): """ Returns the Fourier transformed and shifted data :return: """ return numpy.fft.fftshift(numpy.fft.fft(self, axis=-1), axes=-1)
python
{ "resource": "" }
q54284
MRSData.time_axis
train
def time_axis(self): """ Returns an array of the sample times in seconds for each point in the FID. :return: an array of the sample times in seconds for each point in the FID. """ return numpy.arange(0.0, self.dt * self.np, self.dt)
python
{ "resource": "" }
q54285
MRSData.frequency_axis_ppm
train
def frequency_axis_ppm(self): """ Returns an array of frequencies in PPM. :return: """ return numpy.linspace(self.hertz_to_ppm(-self.sw / 2.0), self.hertz_to_ppm(self.sw / 2.0), self.np, endpoint=False)
python
{ "resource": "" }
q54286
MRSData.to_scanner
train
def to_scanner(self, x, y, z): """ Converts a 3d position in MRSData space to the scanner reference frame :param x: :param y: :param z: :return: """ if self.transform is None: raise ValueError("No transform set for MRSData object {}".format(se...
python
{ "resource": "" }
q54287
MRSData.from_scanner
train
def from_scanner(self, x, y, z): """ Converts a 3d position in the scanner reference frame to the MRSData space :param x: :param y: :param z: :return: """ if self.transform is None: raise ValueError("No transform set for MRSData object {}".for...
python
{ "resource": "" }
q54288
_oai_to_xml
train
def _oai_to_xml(marc_oai): # TODO: move this to MARC XML parser? """ Convert OAI to MARC XML. Args: marc_oai (str): String with either OAI or MARC XML. Returns: str: String with MARC XML. """ record = MARCXMLRecord(marc_oai) record.oai_marc = False return record.to_XM...
python
{ "resource": "" }
q54289
_add_namespace
train
def _add_namespace(marc_xml): """ Add proper XML namespace to the `marc_xml` record. Args: marc_xml (str): String representation of the XML record. Returns: str: XML with namespace. """ dom = marc_xml if isinstance(dom, basestring): dom = dhtmlparser.parseString(ma...
python
{ "resource": "" }
q54290
_read_content_or_path
train
def _read_content_or_path(content_or_path): """ If `content_or_path` contains ``\\n``, return it. Else assume, that it is path and read file at that path. Args: content_or_path (str): Content or path to the file. Returns: str: Content. Raises: IOError: whhen the file i...
python
{ "resource": "" }
q54291
_read_marcxml
train
def _read_marcxml(xml): """ Read MARC XML or OAI file, convert, add namespace and return XML in required format with all necessities. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. Returns: obj: Required XML parsed with ``lxml.etr...
python
{ "resource": "" }
q54292
_read_template
train
def _read_template(template): """ Read XSLT template. Args: template (str): Filename or XML string. Don't use ``\\n`` in case of filename. Returns: obj: Required XML parsed with ``lxml.etree``. """ template = _read_content_or_path(template) file_obj ...
python
{ "resource": "" }
q54293
xslt_transformation
train
def xslt_transformation(xml, template): """ Transform `xml` using XSLT `template`. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. template (str): Filename or XML string. Don't use ``\\n`` in case of filename. R...
python
{ "resource": "" }
q54294
value_check
train
def value_check(arg_name, pos, allowed_values): """ allows value checking at runtime for args or kwargs """ def decorator(fn): # brevity compromised in favour of readability def logic(*args, **kwargs): arg_count = len(args) if arg_count: if pos <...
python
{ "resource": "" }
q54295
type_check
train
def type_check(arg_name, pos, reqd_type): """ allows type checking at runtime for args or kwargs """ def decorator(fn): # brevity compromised in favour of readability def logic(*args, **kwargs): arg_count = len(args) if arg_count: if pos < arg_co...
python
{ "resource": "" }
q54296
SearchResults_QTreeView.__set_default_ui_state
train
def __set_default_ui_state(self, *args): """ Sets the Widget default ui state. :param \*args: Arguments. :type \*args: \* """ LOGGER.debug("> Setting default View state!") if not self.model(): return self.expandAll() for column in ...
python
{ "resource": "" }
q54297
SearchInFiles.__format_occurence
train
def __format_occurence(self, occurence): """ Formats the given occurence and returns the matching rich html text. :param occurence: Occurence to format. :type occurence: Occurence :return: Rich text. :rtype: unicode """ color = "rgb({0}, {1}, {2})" ...
python
{ "resource": "" }
q54298
SearchInFiles.__format_replace_metrics
train
def __format_replace_metrics(self, file, metrics): """ Formats the given replace metrics and returns the matching rich html text. :param file: File. :type file: unicode :param metrics: Replace metrics to format. :type metrics: unicode :return: Rich text. ...
python
{ "resource": "" }
q54299
SearchInFiles.__highlight_occurence
train
def __highlight_occurence(self, file, occurence): """ Highlights given file occurence. :param file: File containing the occurence. :type file: unicode :param occurence: Occurence to highlight. :type occurence: Occurence or SearchOccurenceNode """ if not ...
python
{ "resource": "" }