_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q249600
DataAbstract.plot_svd
train
def plot_svd(self, lapack_driver='gesdd', modes=None, key=None, Bck=True, Lplot='In', cmap=None, vmin=None, vmax=None, cmap_topos=None, vmin_topos=None, vmax_topos=None, ntMax=None, nchMax=None, ms=4, inct=[1,10], incX=[1,5], incm=[1,5], ...
python
{ "resource": "" }
q249601
DataSpectro.plot
train
def plot(self, key=None, invert=None, plotmethod='imshow', cmap=plt.cm.gray, ms=4, Max=None, fs=None, dmargin=None, wintit=None, draw=True, connect=True): """ Plot the data content in a predefined figure """ dax, KH = _plot.Data_plot(self, key=key, invert=invert, ...
python
{ "resource": "" }
q249602
LOS_PRMin
train
def LOS_PRMin(Ds, dus, kPOut=None, Eps=1.e-12, Test=True): """ Compute the point on the LOS where the major radius is minimum """ if Test: assert Ds.ndim in [1,2] and 3 in Ds.shape and Ds.shape==dus.shape assert kPOut is None or (Ds.ndim==1 and not hasattr(kPOut,'__iter__')) or (Ds.ndim==2 and ...
python
{ "resource": "" }
q249603
LOS_get_sample
train
def LOS_get_sample(D, u, dL, DL=None, dLMode='abs', method='sum', Test=True): """ Return the sampled line, with the specified method 'linspace': return the N+1 edges, including the first and last point 'sum' : return the N middle of the segments 'simps': return the N+1 egdes, where N has to be even (sc...
python
{ "resource": "" }
q249604
Struct.isInside
train
def isInside(self, pts, In='(X,Y,Z)'): """ Return an array of booleans indicating whether each point lies inside the Struct volume Tests for each point whether it lies inside the Struct object. The points coordinates can be provided in 2D or 3D You must specify which coordinate ...
python
{ "resource": "" }
q249605
Struct.get_InsideConvexPoly
train
def get_InsideConvexPoly(self, RelOff=_def.TorRelOff, ZLim='Def', Spline=True, Splprms=_def.TorSplprms, NP=_def.TorInsideNP, Plot=False, Test=True): """ Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the d...
python
{ "resource": "" }
q249606
Struct.get_sampleEdge
train
def get_sampleEdge(self, res, DS=None, resMode='abs', offsetIn=0.): """ Sample the polygon edges, with resolution res Sample each segment of the 2D polygon Sampling can be limited to a subdomain defined by DS """ pts, dlr, ind = _comp._Ves_get_sampleEdge(self.Poly, res, DS=DS, ...
python
{ "resource": "" }
q249607
Struct.get_sampleCross
train
def get_sampleCross(self, res, DS=None, resMode='abs', ind=None): """ Sample, with resolution res, the 2D cross-section The sampling domain can be limited by DS or ind """ args = [self.Poly,
python
{ "resource": "" }
q249608
Struct.get_sampleS
train
def get_sampleS(self, res, DS=None, resMode='abs', ind=None, offsetIn=0., Out='(X,Y,Z)', Ind=None): """ Sample, with resolution res, the surface defined by DS or ind An optionnal offset perpendicular to the surface can be used (offsetIn>0 => inwards) Parameters ...
python
{ "resource": "" }
q249609
Struct.get_sampleV
train
def get_sampleV(self, res, DV=None, resMode='abs', ind=None, Out='(X,Y,Z)'): """ Sample, with resolution res, the volume defined by DV or ind """ args = [self.Poly, self.dgeom['P1Min'][0], self.dgeom['P1Max'][0], self.dgeom['P2Min'][1], self.dgeom['P2Max'][1], res] kwdargs = dic...
python
{ "resource": "" }
q249610
Struct.plot
train
def plot(self, lax=None, proj='all', element='PIBsBvV', dP=None, dI=_def.TorId, dBs=_def.TorBsd, dBv=_def.TorBvd, dVect=_def.TorVind, dIHor=_def.TorITord, dBsHor=_def.TorBsTord, dBvHor=_def.TorBvTord, Lim=None, Nstep=_def.TorNTheta, dLeg=_def.TorLegd, indices=False, ...
python
{ "resource": "" }
q249611
Struct.plot_sino
train
def plot_sino(self, ax=None, Ang=_def.LOSImpAng, AngUnit=_def.LOSImpAngUnit, Sketch=True, dP=None, dLeg=_def.TorLegd, draw=True, fs=None, wintit=None, Test=True): """ Plot the sinogram of the vessel polygon, by computing its envelopp in a cross-section, can ...
python
{ "resource": "" }
q249612
Config.lStruct
train
def lStruct(self): """ Return the list of Struct that was used for creation As tofu objects or SavePath+SaveNames (according to strip status) """ lStruct = [] for k in self._dStruct['lorder']:
python
{ "resource": "" }
q249613
Config.lStructIn
train
def lStructIn(self): """ Return the list of StructIn contained in self.lStruct As tofu objects or SavePath+SaveNames (according to strip status) """ lStruct = [] for k in self._dStruct['lorder']: k0, k1 = k.split('_') if type(self._dStruct['dObj'][k0][k1]...
python
{ "resource": "" }
q249614
Config.get_summary
train
def get_summary(self, verb=False, max_columns=100, width=1000): """ Summary description of the object content as a pandas DataFrame """ # Make sure the data is accessible msg = "The data is not accessible because self.strip(2) was used !" assert self._dstrip['strip']<2, msg # Bu...
python
{ "resource": "" }
q249615
Config.isInside
train
def isInside(self, pts, In='(X,Y,Z)', log='any'): """ Return a 2D array of bool Equivalent to applying isInside to each Struct Check self.lStruct[0].isInside? for details Arg log determines how Struct with multiple Limits are treated - 'all' : True only if pts belong to all...
python
{ "resource": "" }
q249616
Rays.get_sample
train
def get_sample(self, res, resMode='abs', DL=None, method='sum', ind=None, compact=False): """ Return a linear sampling of the LOS The LOS is sampled into a series a points and segments lengths The resolution (segments length) is <= res The sampling can be done accordin...
python
{ "resource": "" }
q249617
Rays.calc_kInkOut_IsoFlux
train
def calc_kInkOut_IsoFlux(self, lPoly, lVIn=None, Lim=None, kInOut=True): """ Calculate the intersection points of each ray with each isoflux The isofluxes are provided as a list of 2D closed polygons The intersections are the inward and outward intersections ...
python
{ "resource": "" }
q249618
Rays.get_touch_dict
train
def get_touch_dict(self, ind=None, out=bool): """ Get a dictionnary of Cls_Name struct with indices of Rays touching Only includes Struct object with compute = True (as returned by self.lStruct__computeInOut_computeInOut) Also return the associated colors If in is not None, ...
python
{ "resource": "" }
q249619
merge_urls_data_to
train
def merge_urls_data_to(to, food={}): """Merge urls data""" if not to: to.update(food)
python
{ "resource": "" }
q249620
merge_requests_data_to
train
def merge_requests_data_to(to, food={}): """Merge a small analyzed result to a big one, this function will modify the original ``to``""" if not to: to.update(food) to['requests_counter']['normal'] += food['requests_counter']['normal'] to['requests_counter']['slow'] += food['requests_counte...
python
{ "resource": "" }
q249621
format_data
train
def format_data(raw_data, limit_per_url_group=LIMIT_PER_URL_GROUP, limit_url_groups=LIMIT_URL_GROUPS): """Fomat data from LogAnalyzer for render purpose""" data = copy.deepcopy(raw_data) for k, v in list(data['data_details'].items()): # Only reserve first ``limit_per_url_group`` items v['url...
python
{ "resource": "" }
q249622
URLClassifier.classify
train
def classify(self, url_path): """Classify an url""" for dict_api_url in self.user_defined_rules: api_url = dict_api_url['str'] re_api_url = dict_api_url['re']
python
{ "resource": "" }
q249623
ValidationResult.annotate_rule_violation
train
def annotate_rule_violation(self, rule: ValidationRule) -> None: """ Takes note of a rule validation failure by collecting its error message. :param rule: Rule that failed validation. :type rule: ValidationRule :return: None """
python
{ "resource": "" }
q249624
get_PolyFromPolyFileObj
train
def get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units='m', comments='#', skiprows=0, shape0=2): """ Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units Useful for :meth:`tofu.plugins.AUG.Ves._create()` Parameters ---------- PolyFileO...
python
{ "resource": "" }
q249625
CheckSameObj
train
def CheckSameObj(obj0, obj1, LFields=None): """ Check if two variables are the same instance of a ToFu class Checks a list of attributes, provided by LField Parameters ---------- obj0 : tofu object A variable refering to a ToFu object of any class obj1 : tofu object A...
python
{ "resource": "" }
q249626
Save_Generic
train
def Save_Generic(obj, SaveName=None, Path='./', Mode='npz', compressed=False, Print=True): """ Save a ToFu object under file name SaveName, in folder Path ToFu provides built-in saving and loading functions for ToFu objects. There is now only one saving mode: - 'npz': saves a dict ...
python
{ "resource": "" }
q249627
Open
train
def Open(pathfileext=None, shot=None, t=None, Dt=None, Mesh=None, Deg=None, Deriv=None, Sep=True, Pos=True, OutPath=None, ReplacePath=None, Ves=None, out='full', Verb=False, Print=True): """ Open a ToFu object saved file This generic open function identifies the required loading rout...
python
{ "resource": "" }
q249628
ID.set_LObj
train
def set_LObj(self,LObj=None): """ Set the LObj attribute, storing objects the instance depends on For example: A Detect object depends on a vessel and some apertures That link between should be stored somewhere (for saving/loading). LObj does this: it stores the ID (as dict) of ...
python
{ "resource": "" }
q249629
ID.set_USRdict
train
def set_USRdict(self,USRdict={}): """ Set the USRdict, containing user-defined info about the instance Useful for arbitrary info (e.g.: manufacturing date, material...) Parameters ---------- USRdict : dict
python
{ "resource": "" }
q249630
create_config
train
def create_config(case=None, Exp='Dummy', Type='Tor', Lim=None, Bump_posextent=[np.pi/4., np.pi/4], R=2.4, r=1., elong=0., Dshape=0., divlow=True, divup=True, nP=200, out='object', SavePath='./'): """ Create easily a tofu.geom.Config object ...
python
{ "resource": "" }
q249631
analyze_log
train
def analyze_log(fp, configs, url_rules): """Analyze log file""" url_classifier = URLClassifier(url_rules)
python
{ "resource": "" }
q249632
_spectrogram_scipy_fourier
train
def _spectrogram_scipy_fourier(data, fs, nt, nch, fmin=None, window=('tukey', 0.25), deg=False, nperseg=None, noverlap=None, detrend='linear', stft=False, boundary='constant', padded=True, warn=Tr...
python
{ "resource": "" }
q249633
filter_svd
train
def filter_svd(data, lapack_driver='gesdd', modes=[]): """ Return the svd-filtered signal using only the selected mode Provide the indices of the modes desired """ # Check input modes = np.asarray(modes,dtype=int) assert modes.ndim==1 assert modes.size>=1, "No modes selected !"
python
{ "resource": "" }
q249634
HTMLRender.render_requests_data_to_html
train
def render_requests_data_to_html(self, data, file_name, context={}): """Render to HTML file""" file_path = os.path.join(self.html_dir, file_name) logger.info('Rendering HTML file
python
{ "resource": "" }
q249635
get_figuresize
train
def get_figuresize(fs, fsdef=(12,6), orient='landscape', method='xrandr'): """ Generic function to return figure size in inches Useful for str-based flags such as: - 'a4' : use orient='portrait' or 'landscape' - 'full': to get screen size use meth...
python
{ "resource": "" }
q249636
_set_arrayorder
train
def _set_arrayorder(obj, arrayorder='C'): """ Set the memory order of all np.ndarrays in a tofu object """ msg = "Arg arrayorder must be in ['C','F']" assert arrayorder in ['C','F'], msg d = obj.to_dict(strip=-1) account = {'Success':[], 'Failed':[]} for k, v in d.items(): if type(v) is...
python
{ "resource": "" }
q249637
save
train
def save(obj, path=None, name=None, sep=_sep, deep=False, mode='npz', strip=None, compressed=False, verb=True, return_pfe=False): """ Save the ToFu object ToFu provides built-in saving and loading functions for ToFu objects. Specifying saving path ad name is optional (defaults recommended) The...
python
{ "resource": "" }
q249638
load
train
def load(name, path=None, strip=None, verb=True): """ Load a tofu object file Can load from .npz or .txt files In future versions, will also load from .mat The file must have been saved with tofu (i.e.: must be tofu-formatted) The associated tofu object will be created and returned Pa...
python
{ "resource": "" }
q249639
ToFuObjectBase.to_dict
train
def to_dict(self, strip=None, sep=_sep, deep='ref'): """ Return a flat dict view of the object's attributes Useful for: * displaying all attributes * saving to file * exchaning data with non-tofu libraries Parameters ---------- strip : in...
python
{ "resource": "" }
q249640
ToFuObjectBase.from_dict
train
def from_dict(self, fd, sep=_sep, strip=None): """ Populate the instances attributes using an input dict The input dict must be properly formatted In practice it should be the return output of a similar class to_dict() Parameters ---------- fd : dict The ...
python
{ "resource": "" }
q249641
ToFuObjectBase.copy
train
def copy(self, strip=None, deep='ref'): """ Return another instance of the object, with the same attributes
python
{ "resource": "" }
q249642
ID.set_lObj
train
def set_lObj(self, lObj=None): """ Set the lObj attribute, storing objects the instance depends on For example: A Detect object depends on a vessel and some apertures That link between should be stored somewhere (for saving/loading). lObj does this: it stores the ID (as dict) of...
python
{ "resource": "" }
q249643
Tailer.seek_line_forward
train
def seek_line_forward(self): """\ Searches forward from the current file position for a line terminator and seeks to the charachter after it. """ pos = start_pos = self.file.tell() bytes_read, read_str = self.read(self.read_size) start = 0 if bytes_read ...
python
{ "resource": "" }
q249644
Tailer.seek_line
train
def seek_line(self): """\ Searches backwards from the current file position for a line terminator and seeks to the charachter after it. """ pos = end_pos = self.file.tell() read_size = self.read_size if pos > read_size: pos -= read_size else: ...
python
{ "resource": "" }
q249645
Tailer.tail
train
def tail(self, lines=10): """\ Return the last lines of the file. """ self.seek_end() end_pos = self.file.tell() for i in range(lines): if not self.seek_line():
python
{ "resource": "" }
q249646
Tailer.head
train
def head(self, lines=10): """\ Return the top lines of the file. """ self.seek(0) for i in range(lines): if not self.seek_line_forward(): break end_pos = self.file.tell()
python
{ "resource": "" }
q249647
get_html_tree
train
def get_html_tree(filename_url_or_filelike): """From some file path, input stream, or URL, construct and return an HTML tree. """ try: handler = ( HTTPSHandler if filename_url_or_filelike.lower().startswith('https') else HTTPHandler ) ...
python
{ "resource": "" }
q249648
calc_across_paths_textnodes
train
def calc_across_paths_textnodes(paths_nodes, dbg=False): """Given a list of parent paths tupled with children textnodes, plus initialized feature values, we calculate the total and average string length of the parent's children textnodes. """ # for (path, [textnodes], # num. of...
python
{ "resource": "" }
q249649
extract
train
def extract(filename_url_or_filelike): """A more precise algorithm over the original eatiht algorithm """ pars_tnodes = get_parent_xpaths_and_textnodes(filename_url_or_filelike) #[iterable, cardinality, ttl across iterable, avg across iterable.]) calc_across_paths_textnodes(pars_tnodes) ...
python
{ "resource": "" }
q249650
extract
train
def extract(filename_url_filelike_or_htmlstring): """An "improved" algorithm over the original eatiht algorithm """ html_tree = get_html_tree(filename_url_filelike_or_htmlstring) subtrees = get_textnode_subtrees(html_tree) #[iterable, cardinality, ttl across iterable, avg across iterable.]) ...
python
{ "resource": "" }
q249651
TextNodeSubTree.__learn_oneself
train
def __learn_oneself(self): """calculate cardinality, total and average string length""" if not self.__parent_path or not self.__text_nodes: raise Exception("This error occurred because the step constructor\ had insufficient textnodes or it had empty string\ ...
python
{ "resource": "" }
q249652
TextNodeTree.__make_tree
train
def __make_tree(self): """Build a tree using lxml.html.builder and our subtrees""" # create div with "container" class div = E.DIV(E.CLASS("container")) # append header with title div.append(E.H2(self.__title))
python
{ "resource": "" }
q249653
TextNodeTree.get_html
train
def get_html(self): """Generates if need be and returns a simpler html document with text""" if self.__htmltree is not None:
python
{ "resource": "" }
q249654
TextNodeTree.get_html_string
train
def get_html_string(self): """Generates if need be and returns a simpler html string with extracted text""" if self.__htmltree is not None:
python
{ "resource": "" }
q249655
TextNodeTree.get_text
train
def get_text(self): """Return all joined text from each subtree""" if self.__fulltext: return self.__fulltext
python
{ "resource": "" }
q249656
TextNodeTree.bootstrapify
train
def bootstrapify(self): """Add bootstrap cdn to headers of html""" if self.__htmltree is None: #raise Exception("HtmlTree has not been made yet") self.__make_tree() # add bootstrap cdn to head self.__htmltree.find('head').append( E.LINK(rel="s...
python
{ "resource": "" }
q249657
rar3_type
train
def rar3_type(btype): """RAR3 type code as string.""" if btype < rf.RAR_BLOCK_MARK or btype > rf.RAR_BLOCK_ENDARC:
python
{ "resource": "" }
q249658
xprint
train
def xprint(m, *args): """Print string to stdout. Format unicode safely. """ if sys.hexversion < 0x3000000: m = m.decode('utf8') if args: m = m % args if sys.hexversion
python
{ "resource": "" }
q249659
render_flags
train
def render_flags(flags, bit_list): """Show bit names. """ res = [] known = 0 for bit in bit_list: known = known | bit[0] if flags & bit[0]: res.append(bit[1]) unknown = flags & ~known n = 0 while unknown:
python
{ "resource": "" }
q249660
get_file_flags
train
def get_file_flags(flags): """Show flag names and handle dict size. """ res = render_flags(flags & ~rf.RAR_FILE_DICTMASK, file_bits) xf
python
{ "resource": "" }
q249661
show_item_v3
train
def show_item_v3(h): """Show any RAR3 record. """ st = rar3_type(h.type) xprint("%s: hdrlen=%d datlen=%d", st, h.header_size, h.add_size) if h.type in (rf.RAR_BLOCK_FILE, rf.RAR_BLOCK_SUB): if h.host_os == rf.RAR_OS_UNIX: s_mode = "0%o" % h.mode else: s_mode =...
python
{ "resource": "" }
q249662
check_crc
train
def check_crc(f, inf, desc): """Compare result crc to expected value. """ exp = inf._md_expect if exp is None: return
python
{ "resource": "" }
q249663
load_vint
train
def load_vint(buf, pos): """Load variable-size int.""" limit = min(pos + 11, len(buf)) res = ofs = 0 while pos < limit: b = _byte_code(buf[pos]) res += ((b & 0x7F) << ofs) pos +=
python
{ "resource": "" }
q249664
load_byte
train
def load_byte(buf, pos): """Load single byte""" end = pos + 1 if end > len(buf):
python
{ "resource": "" }
q249665
load_le32
train
def load_le32(buf, pos): """Load little-endian 32-bit integer""" end = pos + 4 if end > len(buf):
python
{ "resource": "" }
q249666
load_bytes
train
def load_bytes(buf, num, pos): """Load sequence of bytes""" end = pos + num if end > len(buf):
python
{ "resource": "" }
q249667
load_vstr
train
def load_vstr(buf, pos): """Load bytes prefixed by vint length""" slen, pos = load_vint(buf,
python
{ "resource": "" }
q249668
load_dostime
train
def load_dostime(buf, pos): """Load LE32 dos timestamp""" stamp, pos = load_le32(buf, pos)
python
{ "resource": "" }
q249669
load_unixtime
train
def load_unixtime(buf, pos): """Load LE32 unix timestamp""" secs, pos = load_le32(buf, pos)
python
{ "resource": "" }
q249670
load_windowstime
train
def load_windowstime(buf, pos): """Load LE64 windows timestamp""" # unix epoch (1970) in seconds from windows epoch (1601) unix_epoch = 11644473600 val1, pos = load_le32(buf, pos) val2, pos = load_le32(buf, pos)
python
{ "resource": "" }
q249671
is_filelike
train
def is_filelike(obj): """Filename or file object? """ if isinstance(obj, (bytes, unicode)): return False res = True for a in ('read', 'tell', 'seek'):
python
{ "resource": "" }
q249672
rar3_s2k
train
def rar3_s2k(psw, salt): """String-to-key hash for RAR3. """ if not isinstance(psw, unicode): psw = psw.decode('utf8') seed = bytearray(psw.encode('utf-16le') + salt) h = Rar3Sha1(rarbug=True) iv = EMPTY
python
{ "resource": "" }
q249673
rar3_decompress
train
def rar3_decompress(vers, meth, data, declen=0, flags=0, crc=0, psw=None, salt=None): """Decompress blob of compressed data. Used for data with non-standard header - eg. comments. """ # already uncompressed? if meth == RAR_M0 and (flags & RAR_FILE_PASSWORD) == 0: return data # take onl...
python
{ "resource": "" }
q249674
to_datetime
train
def to_datetime(t): """Convert 6-part time tuple into datetime object. """ if t is None: return None # extract values year, mon, day, h, m, s = t # assume the values are valid try: return datetime(year, mon, day, h, m, s) except ValueError: pass # sanitize ...
python
{ "resource": "" }
q249675
parse_dos_time
train
def parse_dos_time(stamp): """Parse standard 32-bit DOS timestamp. """ sec, stamp = stamp & 0x1F, stamp >> 5 mn, stamp = stamp & 0x3F, stamp
python
{ "resource": "" }
q249676
custom_popen
train
def custom_popen(cmd): """Disconnect cmd from parent fds, read only from stdout. """ # needed for py2exe creationflags = 0 if sys.platform == 'win32': creationflags = 0x08000000 # CREATE_NO_WINDOW # run command try: p = Popen(cmd, bufsize=0, stdout=PIPE, stdin=PIPE, stderr...
python
{ "resource": "" }
q249677
custom_check
train
def custom_check(cmd, ignore_retcode=False): """Run command, collect output, raise error if needed. """ p = custom_popen(cmd) out, _ = p.communicate()
python
{ "resource": "" }
q249678
check_returncode
train
def check_returncode(p, out): """Raise exception according to unrar exit code. """ code = p.returncode if code == 0: return # map return code to exception class, codes from rar.txt errmap = [None, RarWarning, RarFatalError, RarCRCError, RarLockedArchiveError, # 1..4 ...
python
{ "resource": "" }
q249679
membuf_tempfile
train
def membuf_tempfile(memfile): """Write in-memory file object to real file.""" memfile.seek(0, 0) tmpfd, tmpname = mkstemp(suffix='.rar') tmpf = os.fdopen(tmpfd, "wb") try: while True: buf = memfile.read(BSIZE) if not buf: break
python
{ "resource": "" }
q249680
RarInfo.isdir
train
def isdir(self): """Returns True if entry is a directory. """ if self.type == RAR_BLOCK_FILE: return (self.flags
python
{ "resource": "" }
q249681
RarFile.setpassword
train
def setpassword(self, password): """Sets the password to use when extracting. """ self._password = password if self._file_parser: if self._file_parser.has_header_encryption(): self._file_parser = None
python
{ "resource": "" }
q249682
RarFile.read
train
def read(self, fname, psw=None): """Return uncompressed data for archive entry. For longer files using :meth:`RarFile.open` may be better idea. Parameters: fname filename or RarInfo instance psw
python
{ "resource": "" }
q249683
RarFile.extract
train
def extract(self, member, path=None, pwd=None): """Extract single file into current directory. Parameters: member filename or :class:`RarInfo` instance path optional destination path pwd optional password to use ...
python
{ "resource": "" }
q249684
RarFile.extractall
train
def extractall(self, path=None, members=None, pwd=None): """Extract all files into current directory. Parameters: path optional destination path members optional filename or :class:`RarInfo` instance list to extract pwd ...
python
{ "resource": "" }
q249685
CommonParser.has_header_encryption
train
def has_header_encryption(self): """Returns True if headers are encrypted """ if self._hdrenc_main: return True if self._main:
python
{ "resource": "" }
q249686
CommonParser.getinfo
train
def getinfo(self, member): """Return RarInfo for filename """ if isinstance(member, RarInfo): fname = member.filename else: fname = member # accept both ways here if PATH_SEP == '/':
python
{ "resource": "" }
q249687
CommonParser.parse
train
def parse(self): """Process file.""" self._fd = None try: self._parse_real() finally:
python
{ "resource": "" }
q249688
CommonParser.open
train
def open(self, inf, psw): """Return stream object for file data.""" if inf.file_redir: # cannot leave to unrar as it expects copied file to exist if inf.file_redir[0] in (RAR5_XREDIR_FILE_COPY, RAR5_XREDIR_HARD_LINK): inf = self.getinfo(inf.file_redir[2]) ...
python
{ "resource": "" }
q249689
UnicodeFilename.enc_byte
train
def enc_byte(self): """Copy encoded byte.""" try: c = self.encdata[self.encpos]
python
{ "resource": "" }
q249690
UnicodeFilename.std_byte
train
def std_byte(self): """Copy byte from 8-bit representation.""" try: return self.std_name[self.pos]
python
{ "resource": "" }
q249691
UnicodeFilename.put
train
def put(self, lo, hi): """Copy 16-bit value to result."""
python
{ "resource": "" }
q249692
UnicodeFilename.decode
train
def decode(self): """Decompress compressed UTF16 value.""" hi = self.enc_byte() flagbits = 0 while self.encpos < len(self.encdata): if flagbits == 0: flags = self.enc_byte() flagbits = 8 flagbits -= 2 t = (flags >> flagb...
python
{ "resource": "" }
q249693
RarExtFile.read
train
def read(self, cnt=None): """Read all or specified amount of data from archive entry.""" # sanitize cnt if cnt is None or cnt < 0: cnt = self._remain elif cnt > self._remain: cnt = self._remain if cnt == 0: return EMPTY # actual read ...
python
{ "resource": "" }
q249694
RarExtFile._check
train
def _check(self): """Check final CRC.""" final = self._md_context.digest() exp = self._inf._md_expect if exp is None: return if final is None: return if self._returncode: check_returncode(self, '') if self._remain != 0:
python
{ "resource": "" }
q249695
RarExtFile.seek
train
def seek(self, ofs, whence=0): """Seek in data. On uncompressed files, the seeking works by actual seeks so it's fast. On compresses files its slow - forward seeking happends by reading ahead, backwards by re-opening and decompressing from the start. """ # disa...
python
{ "resource": "" }
q249696
RarExtFile._skip
train
def _skip(self, cnt): """Read and discard data""" while cnt > 0: if cnt > 8192: buf = self.read(8192) else:
python
{ "resource": "" }
q249697
PipeReader._read
train
def _read(self, cnt): """Read from pipe.""" # normal read is usually enough data = self._fd.read(cnt) if len(data) == cnt or not data: return data # short read, try looping buf = [data] cnt -= len(data)
python
{ "resource": "" }
q249698
DirectReader._skip
train
def _skip(self, cnt): """RAR Seek, skipping through rar files to get to correct position """ while cnt > 0: # next vol needed? if self._cur_avail == 0: if not self._open_next(): break # fd is in read pos, do the read ...
python
{ "resource": "" }
q249699
DirectReader._read
train
def _read(self, cnt): """Read from potentially multi-volume archive.""" buf = [] while cnt > 0: # next vol needed? if self._cur_avail == 0: if not self._open_next(): break # fd is in read pos, do the read if cn...
python
{ "resource": "" }