INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Search for the episode with the requested experience Id: return:
def episode_info(self): """ Search for the episode with the requested experience Id :return: """ if self.show_info: for season in self.show_info["seasons"]: for episode in season["episodes"]: for lang in episode["languages"].values(...
Get the sources for a given experience_id which is tied to a specific language: param experience_id: int ; video content id: return: sources dict
def sources(self): """ Get the sources for a given experience_id, which is tied to a specific language :param experience_id: int; video content id :return: sources dict """ api_url = self.sources_api_url.format(experience_id=self.experience_id) res = self.get(api_...
Get the RSA key for the user and encrypt the users password: param email: steam account: param password: password for account: return: encrypted password
def encrypt_password(self, email, password): """ Get the RSA key for the user and encrypt the users password :param email: steam account :param password: password for account :return: encrypted password """ res = self.session.http.get(self._get_rsa_key_url, params...
Logs in to Steam
def dologin(self, email, password, emailauth="", emailsteamid="", captchagid="-1", captcha_text="", twofactorcode=""): """ Logs in to Steam """ epassword, rsatimestamp = self.encrypt_password(email, password) login_data = { 'username': email, "password":...
Returns the stream_id contained in the HTML.
def get_stream_id(self, html): """Returns the stream_id contained in the HTML.""" stream_id = stream_id_pattern.search(html) if not stream_id: self.logger.error("Failed to extract stream_id.") return stream_id.group("stream_id")
Returns a nested list of different stream options.
def get_stream_info(self, html): """ Returns a nested list of different stream options. Each entry in the list will contain a stream_url and stream_quality_name for each stream occurrence that was found in the JS. """ stream_info = stream_info_pattern.findall(html) ...
login and update cached cookies
def _login(self, username, password): '''login and update cached cookies''' self.logger.debug('login ...') res = self.session.http.get(self.login_url) input_list = self._input_re.findall(res.text) if not input_list: raise PluginError('Missing input data on login webs...
Creates a key - function mapping.
def map(self, key, func, *args, **kwargs): """Creates a key-function mapping. The return value from the function should be either - A tuple containing a name and stream - A iterator of tuples containing a name and stream Any extra arguments will be passed to the function. ...
Takes ISO 8601 format ( string ) and converts into a utc datetime ( naive )
def parse_timestamp(ts): """Takes ISO 8601 format(string) and converts into a utc datetime(naive)""" return ( datetime.datetime.strptime(ts[:-7], "%Y-%m-%dT%H:%M:%S") + datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:])) * int(ts[-6:-5] + "1") )
Makes a call against the api.
def _api_call(self, entrypoint, params=None, schema=None): """Makes a call against the api. :param entrypoint: API method to call. :param params: parameters to include in the request data. :param schema: schema to use to validate the data """ url = self._api_url.format(e...
Starts a session against Crunchyroll s server. Is recommended that you call this method before making any other calls to make sure you have a valid session against the server.
def start_session(self): """ Starts a session against Crunchyroll's server. Is recommended that you call this method before making any other calls to make sure you have a valid session against the server. """ params = {} if self.auth: param...
Authenticates the session to be able to access restricted data from the server ( e. g. premium restricted videos ).
def login(self, username, password): """ Authenticates the session to be able to access restricted data from the server (e.g. premium restricted videos). """ params = { "account": username, "password": password } login = self._api_...
Returns the data for a certain media item.
def get_info(self, media_id, fields=None, schema=None): """ Returns the data for a certain media item. :param media_id: id that identifies the media item to be accessed. :param fields: list of the media"s field to be returned. By default the API returns some fiel...
Creates a new CrunchyrollAPI object initiates it s session and tries to authenticate it either by using saved credentials or the user s username and password.
def _create_api(self): """Creates a new CrunchyrollAPI object, initiates it's session and tries to authenticate it either by using saved credentials or the user's username and password. """ if self.options.get("purge_credentials"): self.cache.set("session_id", None, 0...
Compress a byte string.
def compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0): """Compress a byte string. Args: string (bytes): The input data. mode (int, optional): The compression mode can be MODE_GENERIC (default), MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). qua...
Return the specified standard input output or errors stream as a raw buffer object suitable for reading/ writing binary data from/ to it.
def get_binary_stdio(stream): """ Return the specified standard input, output or errors stream as a 'raw' buffer object suitable for reading/writing binary data from/to it. """ assert stream in ['stdin', 'stdout', 'stderr'], 'invalid stream name' stdio = getattr(sys, stream) if sys.version_info[...
Show character in readable format
def outputCharFormatter(c): """Show character in readable format """ #TODO 2: allow hex only output if 32<c<127: return chr(c) elif c==10: return '\\n' elif c==13: return '\\r' elif c==32: return '" "' else: return '\\x{:02x}'.format(c)
Show string or char.
def outputFormatter(s): """Show string or char. """ result = '' def formatSubString(s): for c in s: if c==32: yield ' ' else: yield outputCharFormatter(c) if len(result)<200: return ''.join(formatSubString(s)) else: return ''.join(formatSubString(s[:100]))...
Read n bits from the stream and return as an integer. Produces zero bits beyond the stream. >>> olleke. data [ 0 ] == 27 True >>> olleke. read ( 5 ) 27
def read(self, n): """Read n bits from the stream and return as an integer. Produces zero bits beyond the stream. >>> olleke.data[0]==27 True >>> olleke.read(5) 27 >>> olleke BitStream(pos=0:5) """ value = self.peek(n) self.pos += ...
Peek an n bit integer from the stream without updating the pointer. It is not an error to read beyond the end of the stream. >>> olleke. data [: 2 ] == b \ x1b \ x2e and 0x2e1b == 11803 True >>> olleke. peek ( 15 ) 11803 >>> hex ( olleke. peek ( 32 )) 0x2e1b
def peek(self, n): """Peek an n bit integer from the stream without updating the pointer. It is not an error to read beyond the end of the stream. >>> olleke.data[:2]==b'\x1b\x2e' and 0x2e1b==11803 True >>> olleke.peek(15) 11803 >>> hex(olleke.peek(32)) '0...
Read n bytes from the stream on a byte boundary.
def readBytes(self, n): """Read n bytes from the stream on a byte boundary. """ if self.pos&7: raise ValueError('readBytes: need byte boundary') result = self.data[self.pos>>3:(self.pos>>3)+n] self.pos += 8*n return result
The value used for processing. Can be a tuple. with optional extra bits
def value(self, extra=None): """The value used for processing. Can be a tuple. with optional extra bits """ if isinstance(self.code, WithExtra): if not 0<=extra<1<<self.extraBits(): raise ValueError("value: extra value doesn't fit in extraBits") re...
Long explanation of the value from the numeric value with optional extra bits Used by Layout. verboseRead when printing the value
def explanation(self, extra=None): """Long explanation of the value from the numeric value with optional extra bits Used by Layout.verboseRead when printing the value """ if isinstance(self.code, WithExtra): return self.code.callback(self, extra) return self.c...
Find which symbol index matches the given data ( from peek as a number ) and return the number of bits decoded. Can also be used to figure out length of a symbol.
def decodePeek(self, data): """Find which symbol index matches the given data (from peek, as a number) and return the number of bits decoded. Can also be used to figure out length of a symbol. """ return self.maxLength, Symbol(self, data&(1<<self.maxLength)-1)
Find which symbol index matches the given data ( from peek as a number ) and return the number of bits decoded. Can also be used to figure out length of a symbol.
def decodePeek(self, data): """Find which symbol index matches the given data (from peek, as a number) and return the number of bits decoded. Can also be used to figure out length of a symbol. """ #do binary search for word length #invariant: lo<=length<=hi lo, hi...
Store decodeTable and compute lengthTable minLength maxLength from encodings.
def setDecode(self, decodeTable): """Store decodeTable, and compute lengthTable, minLength, maxLength from encodings. """ self.decodeTable = decodeTable #set of symbols with unknown length todo = set(decodeTable) #bit size under investigation maskLength = ...
Given the bit pattern lengths for symbols given in lengthTable set decodeTable minLength maxLength
def setLength(self, lengthTable): """Given the bit pattern lengths for symbols given in lengthTable, set decodeTable, minLength, maxLength """ self.lengthTable = lengthTable self.minLength = min(lengthTable.values()) self.maxLength = max(lengthTable.values()) #com...
Long explanation of the value from the numeric value This is a default routine. You can customize in three ways: - set description to add some text - override to get more control - set callback to make it dependent on you local variables
def explanation(self, index): """Long explanation of the value from the numeric value This is a default routine. You can customize in three ways: - set description to add some text - override to get more control - set callback to make it dependent on you local variables ...
Show all words of the code in a nice format.
def showCode(self, width=80): """Show all words of the code in a nice format. """ #make table of all symbols with binary strings symbolStrings = [ (self.bitPattern(s.index), self.mnemonic(s.index)) for s in self ] #determine column widths the w...
Read symbol from stream. Returns symbol length.
def readTuple(self, stream): """Read symbol from stream. Returns symbol, length. """ length, symbol = self.decodePeek(stream.peek(self.maxLength)) stream.pos += length return length, symbol
Read symbol and extrabits from stream. Returns symbol length symbol extraBits extra >>> olleke. pos = 6 >>> MetablockLengthAlphabet (). readTupleAndExtra ( olleke ) ( 2 Symbol ( MLEN 4 ) 16 46 )
def readTupleAndExtra(self, stream): """Read symbol and extrabits from stream. Returns symbol length, symbol, extraBits, extra >>> olleke.pos = 6 >>> MetablockLengthAlphabet().readTupleAndExtra(olleke) (2, Symbol(MLEN, 4), 16, 46) """ length, symbol = self.decodeP...
Expanded version of Code. explanation supporting extra bits. If you don t supply extra it is not mentioned.
def explanation(self, index, extra=None): """Expanded version of Code.explanation supporting extra bits. If you don't supply extra, it is not mentioned. """ extraBits = 0 if extra is None else self.extraBits(index) if not hasattr(self, 'extraTable'): formatString = '{...
Override if you don t define value0 and extraTable
def value(self, index, extra): """Override if you don't define value0 and extraTable """ lower, upper = self.span(index) value = lower+(extra or 0) if value>upper: raise ValueError('value: extra out of range') return value
Give the range of possible values in a tuple Useful for mnemonic and explanation
def span(self, index): """Give the range of possible values in a tuple Useful for mnemonic and explanation """ lower = self.value0+sum(1<<x for x in self.extraTable[:index]) upper = lower+(1<<self.extraTable[index]) return lower, upper-1
Returns ( Simple #codewords ) or ( Complex HSKIP )
def value(self, index, extra): """Returns ('Simple', #codewords) or ('Complex', HSKIP) """ if index==1: if extra>3: raise ValueError('value: extra out of range') return 'Simple', extra+1 if extra: raise ValueError('value: extra out of r...
Give count and value.
def value(self, index, extra): """Give count and value.""" index = index if index==0: return 1, 0 if index<=self.RLEMAX: return (1<<index)+extra, 0 return 1, index-self.RLEMAX
Give relevant values for computations: ( insertSymbol copySymbol dist0flag )
def splitSymbol(self, index): """Give relevant values for computations: (insertSymbol, copySymbol, dist0flag) """ #determine insert and copy upper bits from table row = [0,0,1,1,2,2,1,3,2,3,3][index>>6] col = [0,1,0,1,0,1,2,0,2,1,2][index>>6] #determine inserts an...
Make a nice mnemonic
def mnemonic(self, index): """Make a nice mnemonic """ i,c,d0 = self.splitSymbol(index) iLower, _ = i.code.span(i.index) iExtra = i.extraBits() cLower, _ = c.code.span(c.index) cExtra = c.extraBits() return 'I{}{}{}C{}{}{}{}'.format( iLower, ...
Indicate how many extra bits are needed to interpret symbol >>> d = DistanceAlphabet ( D NPOSTFIX = 2 NDIRECT = 10 ) >>> [ d [ i ]. extraBits () for i in range ( 26 ) ] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ] >>> [ d [ i ]. extraBits () for i in range ( 26 36 ) ] [ 1 1 1 1 1 1 1 1 2 2 ]
def extraBits(self, index): """Indicate how many extra bits are needed to interpret symbol >>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10) >>> [d[i].extraBits() for i in range(26)] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> [d[i].extr...
Decode value of symbol together with the extra bits. >>> d = DistanceAlphabet ( D NPOSTFIX = 2 NDIRECT = 10 ) >>> d [ 34 ]. value ( 2 ) ( 0 35 )
def value(self, dcode, dextra): """Decode value of symbol together with the extra bits. >>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10) >>> d[34].value(2) (0, 35) """ if dcode<16: return [(1,0),(2,0),(3,0),(4,0), (1,-1),(1,+1),(1,-2),...
Give mnemonic representation of meaning. verbose compresses strings of x s
def mnemonic(self, index, verbose=False): """Give mnemonic representation of meaning. verbose compresses strings of x's """ if index<16: return ['last', '2last', '3last', '4last', 'last-1', 'last+1', 'last-2', 'last+2', 'last-3', 'last+3', '2la...
>>> d = DistanceAlphabet ( D NPOSTFIX = 2 NDIRECT = 10 ) >>> d [ 55 ]. explanation ( 13 ) 11 [ 1101 ] 01 - 5: [ 0 ] + 240
def explanation(self, index, extra): """ >>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10) >>> d[55].explanation(13) '11[1101]01-5: [0]+240' """ extraBits = self.extraBits(index) extraString = '[{:0{}b}]'.format(extra, extraBits) return '{0}: [{1[0]}]{...
Get word
def word(self, size, dist): """Get word """ #split dist in index and action ndbits = self.NDBITS[size] index = dist&(1<<ndbits)-1 action = dist>>ndbits #compute position in file position = sum(n<<self.NDBITS[n] for n in range(4,size))+size*index se...
Build the action table from the text above
def compileActions(self): """Build the action table from the text above """ import re self.actionList = actions = [None]*121 #Action 73, which is too long, looks like this when expanded: actions[73] = "b' the '+w+b' of the '" #find out what the columns are ...
Perform the proper action
def doAction(self, w, action): """Perform the proper action """ #set environment for the UpperCaseFirst U = self.upperCase1 return eval(self.actionList[action], locals())
Produce hex dump of all data containing the bits from pos to stream. pos
def makeHexData(self, pos): """Produce hex dump of all data containing the bits from pos to stream.pos """ firstAddress = pos+7>>3 lastAddress = self.stream.pos+7>>3 return ''.join(map('{:02x} '.format, self.stream.data[firstAddress:lastAddress]))
Show formatted bit data: Bytes are separated by commas whole bytes are displayed in hex >>> Layout ( olleke ). formatBitData ( 6 2 16 ) |00h|2Eh |00 >>> Layout ( olleke ). formatBitData ( 4 1 0 ) 1
def formatBitData(self, pos, width1, width2=0): """Show formatted bit data: Bytes are separated by commas whole bytes are displayed in hex >>> Layout(olleke).formatBitData(6, 2, 16) '|00h|2Eh,|00' >>> Layout(olleke).formatBitData(4, 1, 0) '1' """ r...
give alphabet the prefix code that is read from the stream Called for the following alphabets in this order: The alphabet in question must have a logical order otherwise the assignment of symbols doesn t work.
def readPrefixCode(self, alphabet): """give alphabet the prefix code that is read from the stream Called for the following alphabets, in this order: The alphabet in question must have a "logical" order, otherwise the assignment of symbols doesn't work. """ mode, numberOfS...
Read complex code
def readComplexCode(self, hskip, alphabet): """Read complex code""" stream = self.stream #read the lengths for the length code lengths = [1,2,3,4,0,5,17,6,16,7,8,9,10,11,12,13,14,15][hskip:] codeLengths = {} total = 0 lol = LengthOfLengthAlphabet('##'+alphabet.nam...
Process a brotli stream.
def processStream(self): """Process a brotli stream. """ print('addr hex{:{}s}binary context explanation'.format( '', self.width-10)) print('Stream header'.center(60, '-')) self.windowSize = self.verboseRead(WindowSizeAlphabet()) print('Metablock header'.cent...
Read symbol and extra from stream and explain what happens. Returns the value of the symbol >>> olleke. pos = 0 >>> l = Layout ( olleke ) >>> l. verboseRead ( WindowSizeAlphabet () ) 0000 1b 1011 WSIZE windowsize = ( 1<<22 ) - 16 = 4194288 4194288
def verboseRead(self, alphabet, context='', skipExtra=False): """Read symbol and extra from stream and explain what happens. Returns the value of the symbol >>> olleke.pos = 0 >>> l = Layout(olleke) >>> l.verboseRead(WindowSizeAlphabet()) 0000 1b 1011 W...
Read MNIBBLES and meta block length ; if empty block skip block and return true.
def metablockLength(self): """Read MNIBBLES and meta block length; if empty block, skip block and return true. """ self.MLEN = self.verboseRead(MetablockLengthAlphabet()) if self.MLEN: return False #empty block; skip and return False self.verboseRead(R...
If true handle uncompressed data
def uncompressed(self): """If true, handle uncompressed data """ ISUNCOMPRESSED = self.verboseRead( BoolCode('UNCMPR', description='Is uncompressed?')) if ISUNCOMPRESSED: self.verboseRead(FillerAlphabet(streamPos=self.stream.pos)) print('Uncompressed d...
Read block type switch descriptor for given kind of blockType.
def blockType(self, kind): """Read block type switch descriptor for given kind of blockType.""" NBLTYPES = self.verboseRead(TypeCountAlphabet( 'BT#'+kind[0].upper(), description='{} block types'.format(kind), )) self.numberOfBlockTypes[kind] = NBLTYPES ...
Read literal context modes. LSB6: lower 6 bits of last char MSB6: upper 6 bits of last char UTF8: rougly dependent on categories: upper 4 bits depend on category of last char: control/ whitespace/ space/ punctuation/ quote/ %/ open/ close/ comma/ period/ =/ digits/ VOWEL/ CONSONANT/ vowel/ consonant lower 2 bits depend...
def readLiteralContextModes(self): """Read literal context modes. LSB6: lower 6 bits of last char MSB6: upper 6 bits of last char UTF8: rougly dependent on categories: upper 4 bits depend on category of last char: control/whitespace/space/ punctuation/quote/%/...
Read context maps Returns the number of differnt values on the context map ( In other words the number of prefix trees )
def contextMap(self, kind): """Read context maps Returns the number of differnt values on the context map (In other words, the number of prefix trees) """ NTREES = self.verboseRead(TypeCountAlphabet( kind[0].upper()+'T#', description='{} prefix trees'.form...
In place inverse move to front transform.
def IMTF(v): """In place inverse move to front transform. """ #mtf is initialized virtually with range(infinity) mtf = [] for i, vi in enumerate(v): #get old value from mtf. If never seen, take virtual value try: value = mtf.pop(vi) except Inde...
Read prefix code array
def readPrefixArray(self, kind, numberOfTrees): """Read prefix code array""" prefixes = [] for i in range(numberOfTrees): if kind==L: alphabet = LiteralAlphabet(i) elif kind==I: alphabet = InsertAndCopyAlphabet(i) elif kind==D: alphabet = DistanceAlphabet( ...
Process the data. Relevant variables of self: numberOfBlockTypes [ kind ]: number of block types currentBlockTypes [ kind ]: current block types ( = 0 ) literalContextModes: the context modes for the literal block types currentBlockCounts [ kind ]: counters for block types blockTypeCodes [ kind ]: code for block type b...
def metablock(self): """Process the data. Relevant variables of self: numberOfBlockTypes[kind]: number of block types currentBlockTypes[kind]: current block types (=0) literalContextModes: the context modes for the literal block types currentBlockCounts[kind]: counters fo...
Return BROTLI_VERSION string as defined in common/ version. h file.
def get_version(): """ Return BROTLI_VERSION string as defined in 'common/version.h' file. """ version_file_path = os.path.join(CURR_DIR, 'c', 'common', 'version.h') version = 0 with open(version_file_path, 'r') as f: for line in f: m = re.match(r'#define\sBROTLI_VERSION\s+0x([0-9a-f...
Turns a intensity array to a monochrome image by replacing each intensity by a scaled color
def monochrome(I, color, vmin=None, vmax=None): """Turns a intensity array to a monochrome 'image' by replacing each intensity by a scaled 'color' Values in I between vmin and vmax get scaled between 0 and 1, and values outside this range are clipped to this. Example >>> I = np.arange(16.).reshape(4,...
Similar to monochrome but now do it for multiple colors
def polychrome(I, colors, vmin=None, vmax=None, axis=-1): """Similar to monochrome, but now do it for multiple colors Example >>> I = np.arange(32.).reshape(4,4,2) >>> colors = [(0, 0, 1), (0, 1, 0)] # red and green >>> rgb = vx.image.polychrome(I, colors) # shape is (4,4,3) :param I: ndarray ...
Function decorater that executes the function in parallel Usage::
def parallelize(cores=None, fork=True, flatten=False, info=False, infoclass=InfoThreadProgressBar, init=None, *args, **kwargs): """Function decorater that executes the function in parallel Usage:: @parallelize(cores=10, info=True) def f(x): return x**2 x = numpy.arange(0, 100, 0.1) y = f(x) # this ge...
: param DatasetLocal dataset: dataset to export: param str path: path for file: param lis [ str ] column_names: list of column names to export or None for all columns: param str byteorder: = for native < for little endian and > for big endian: param bool shuffle: export rows in random order: param bool selection: expor...
def export_hdf5(dataset, path, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True): """ :param DatasetLocal dataset: dataset to export :param str path: path for file :param lis[str] column_names: list of column names to export or None...
Implementation of Dataset. to_arrow_table
def arrow_table_from_vaex_df(ds, column_names=None, selection=None, strings=True, virtual=False): """Implementation of Dataset.to_arrow_table""" names = [] arrays = [] for name, array in ds.to_items(column_names=column_names, selection=selection, strings=strings, virtual=virtual): names.append(n...
Adds method f to the Dataset class
def patch(f): '''Adds method f to the Dataset class''' name = f.__name__ Dataset.__hidden__[name] = f return f
Add ecliptic coordates ( long_out lat_out ) from equatorial coordinates.
def add_virtual_columns_eq2ecl(self, long_in="ra", lat_in="dec", long_out="lambda_", lat_out="beta", name_prefix="__celestial_eq2ecl", radians=False): """Add ecliptic coordates (long_out, lat_out) from equatorial coordinates. :param long_in: Name/expression for right ascension :param lat_in: Name/expressio...
Convert parallax to distance ( i. e. 1/ parallax )
def add_virtual_columns_distance_from_parallax(self, parallax="parallax", distance_name="distance", parallax_uncertainty=None, uncertainty_postfix="_uncertainty"): """Convert parallax to distance (i.e. 1/parallax) :param parallax: expression for the parallax, e.g. "parallax" :param distance_name: name for ...
Concert velocities from a cartesian system to proper motions and radial velocities
def add_virtual_columns_cartesian_velocities_to_pmvr(self, x="x", y="y", z="z", vx="vx", vy="vy", vz="vz", vr="vr", pm_long="pm_long", pm_lat="pm_lat", distance=None): """Concert velocities from a cartesian system to proper motions and radial velocities TODO: errors :param x: name of x column (input) ...
Transform/ rotate proper motions from equatorial to galactic coordinates
def add_virtual_columns_proper_motion_eq2gal(self, long_in="ra", lat_in="dec", pm_long="pm_ra", pm_lat="pm_dec", pm_long_out="pm_l", pm_lat_out="pm_b", name_prefix="__proper_motion_eq2gal", right_ascension_galactic_pole=192.85, ...
Transform/ rotate proper motions from galactic to equatorial coordinates.
def add_virtual_columns_proper_motion_gal2eq(self, long_in="ra", lat_in="dec", pm_long="pm_l", pm_lat="pm_b", pm_long_out="pm_ra", pm_lat_out="pm_dec", name_prefix="__proper_motion_gal2eq", right_ascension_galactic_pole=192.85, ...
Convert radial velocity and galactic proper motions ( and positions ) to cartesian velocities wrt the center_v
def add_virtual_columns_lbrvr_proper_motion2vcartesian(self, long_in="l", lat_in="b", distance="distance", pm_long="pm_l", pm_lat="pm_b", vr="vr", vx="vx", vy="vy", vz="vz", center_v=(0, 0, 0), ...
From http:// arxiv. org/ pdf/ 1306. 2945v2. pdf
def add_virtual_columns_equatorial_to_galactic_cartesian(self, alpha, delta, distance, xname, yname, zname, radians=True, alpha_gp=np.radians(192.85948), delta_gp=np.radians(27.12825), l_omega=np.radians(32.93192)): """From http://arxiv.org/pdf/1306.2945v2.pdf""" if not radians: alpha = "pi/180.*%s" % a...
Convert proper motion to perpendicular velocities.
def add_virtual_columns_proper_motion2vperpendicular(self, distance="distance", pm_long="pm_l", pm_lat="pm_b", vl="vl", vb="vb", propagate_uncertainties=False, r...
Calculate the angular momentum components provided Cartesian positions and velocities. Be mindful of the point of origin: ex. if considering Galactic dynamics and positions and velocities should be as seen from the Galactic centre.
def add_virtual_columns_cartesian_angular_momenta(self, x='x', y='y', z='z', vx='vx', vy='vy', vz='vz', Lx='Lx', Ly='Ly', Lz='Lz', propagate_uncertainties=False): """...
NOTE: This cannot be called until after this has been added to an Axes otherwise unit conversion will fail. This maxes it very important to call the accessor method and not directly access the transformation member variable.
def _recompute_transform(self): """NOTE: This cannot be called until after this has been added to an Axes, otherwise unit conversion will fail. This maxes it very important to call the accessor method and not directly access the transformation member variable. """ center = (self.convert_xunits(self...
Return a graph containing the dependencies of this expression Structure is: [ <string expression > <function name if callable > <function object if callable > [ subgraph/ dependencies.... ]]
def _graph(self): """"Return a graph containing the dependencies of this expression Structure is: [<string expression>, <function name if callable>, <function object if callable>, [subgraph/dependencies, ....]] """ expression = self.expression def walk(node): ...
Return a graphviz. Digraph object with a graph of the expression
def _graphviz(self, dot=None): """Return a graphviz.Digraph object with a graph of the expression""" from graphviz import Graph, Digraph node = self._graph() dot = dot or Digraph(comment=self.expression) def walk(node): if isinstance(node, six.string_types): ...
Shortcut for ds. min ( expression... ) see Dataset. min
def min(self, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): '''Shortcut for ds.min(expression, ...), see `Dataset.min`''' kwargs = dict(locals()) del kwargs['self'] kwargs['expression'] = self.expression return self.ds.min(**kwargs)
Computes counts of unique values.
def value_counts(self, dropna=False, dropnull=True, ascending=False, progress=False): """Computes counts of unique values. WARNING: * If the expression/column is not categorical, it will be converted on the fly * dropna is False by default, it is True by default in pandas ...
Map values of an expression or in memory column accoring to an input dictionary or a custom callable function.
def map(self, mapper, nan_mapping=None, null_mapping=None): """Map values of an expression or in memory column accoring to an input dictionary or a custom callable function. Example: >>> import vaex >>> df = vaex.from_arrays(color=['red', 'red', 'blue', 'red', 'green']) ...
Create a vaex app the QApplication mainloop must be started.
def app(*args, **kwargs): """Create a vaex app, the QApplication mainloop must be started. In ipython notebook/jupyter do the following: >>> import vaex.ui.main # this causes the qt api level to be set properly >>> import vaex Next cell: >>> %gui qt Next cell: >>> app = vaex.app() ...
Convert a filename ( or list of ) to a filename with. hdf5 and optionally a - shuffle suffix
def _convert_name(filenames, shuffle=False): '''Convert a filename (or list of) to a filename with .hdf5 and optionally a -shuffle suffix''' if not isinstance(filenames, (list, tuple)): filenames = [filenames] base = filenames[0] if shuffle: base += '-shuffle' if len(filenames) > 1: ...
Open a DataFrame from file given by path.
def open(path, convert=False, shuffle=False, copy_index=True, *args, **kwargs): """Open a DataFrame from file given by path. Example: >>> ds = vaex.open('sometable.hdf5') >>> ds = vaex.open('somedata*.csv', convert='bigdata.hdf5') :param str path: local or absolute path to file, or glob string ...
Open a list of filenames and return a DataFrame with all DataFrames cocatenated.
def open_many(filenames): """Open a list of filenames, and return a DataFrame with all DataFrames cocatenated. :param list[str] filenames: list of filenames/paths :rtype: DataFrame """ dfs = [] for filename in filenames: filename = filename.strip() if filename and filename[0] !=...
Connect to a SAMP Hub and wait for a single table load event disconnect download the table and return the DataFrame.
def from_samp(username=None, password=None): """Connect to a SAMP Hub and wait for a single table load event, disconnect, download the table and return the DataFrame. Useful if you want to send a single table from say TOPCAT to vaex in a python console or notebook. """ print("Waiting for SAMP message.....
Create a vaex DataFrame from an Astropy Table.
def from_astropy_table(table): """Create a vaex DataFrame from an Astropy Table.""" import vaex.file.other return vaex.file.other.DatasetAstropyTable(table=table)
Create an in memory DataFrame from numpy arrays in contrast to from_arrays this keeps the order of columns intact ( for Python < 3. 6 ).
def from_items(*items): """Create an in memory DataFrame from numpy arrays, in contrast to from_arrays this keeps the order of columns intact (for Python < 3.6). Example >>> import vaex, numpy as np >>> x = np.arange(5) >>> y = x ** 2 >>> vaex.from_items(('x', x), ('y', y)) # x y ...
Create an in memory DataFrame from numpy arrays.
def from_arrays(**arrays): """Create an in memory DataFrame from numpy arrays. Example >>> import vaex, numpy as np >>> x = np.arange(5) >>> y = x ** 2 >>> vaex.from_arrays(x=x, y=y) # x y 0 0 0 1 1 1 2 2 4 3 3 9 4 4 16 ...
Similar to from_arrays but convenient for a DataFrame of length 1.
def from_scalars(**kwargs): """Similar to from_arrays, but convenient for a DataFrame of length 1. Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) :rtype: DataFrame """ import numpy as np return from_arrays(**{k: np.array([v]) for k, v in kwargs.items()})
Create an in memory DataFrame from a pandas DataFrame.
def from_pandas(df, name="pandas", copy_index=True, index_name="index"): """Create an in memory DataFrame from a pandas DataFrame. :param: pandas.DataFrame df: Pandas DataFrame :param: name: unique for the DataFrame >>> import vaex, pandas as pd >>> df_pandas = pd.from_csv('test.csv') >>> df =...
Create an in memory DataFrame from an ascii file ( whitespace seperated by default ).
def from_ascii(path, seperator=None, names=True, skip_lines=0, skip_after=0, **kwargs): """ Create an in memory DataFrame from an ascii file (whitespace seperated by default). >>> ds = vx.from_ascii("table.asc") >>> ds = vx.from_ascii("table.csv", seperator=",", names=["x", "y", "z"]) :param path:...
Shortcut to read a csv file using pandas and convert to a DataFrame directly.
def from_csv(filename_or_buffer, copy_index=True, **kwargs): """Shortcut to read a csv file using pandas and convert to a DataFrame directly. :rtype: DataFrame """ import pandas as pd return from_pandas(pd.read_csv(filename_or_buffer, **kwargs), copy_index=copy_index)
Convert a path ( or glob pattern ) to a single hdf5 file will open the hdf5 file if exists.
def read_csv_and_convert(path, shuffle=False, copy_index=True, **kwargs): '''Convert a path (or glob pattern) to a single hdf5 file, will open the hdf5 file if exists. Example: >>> vaex.read_csv_and_convert('test-*.csv', shuffle=True) # this may take a while >>> vaex.read_csv_and_conve...
Connect to hostname supporting the vaex web api.
def server(url, **kwargs): """Connect to hostname supporting the vaex web api. :param str hostname: hostname or ip address of server :return vaex.dataframe.ServerRest: returns a server object, note that it does not connect to the server yet, so this will always succeed :rtype: ServerRest """ fr...
Returns an example DataFrame which comes with vaex for testing/ learning purposes.
def example(download=True): """Returns an example DataFrame which comes with vaex for testing/learning purposes. :rtype: DataFrame """ from . import utils path = utils.get_data_file("helmi-dezeeuw-2000-10p.hdf5") if path is None and download: return vaex.datasets.helmi_de_zeeuw_10percen...
Creates a zeldovich DataFrame.
def zeldovich(dim=2, N=256, n=-2.5, t=None, scale=1, seed=None): """Creates a zeldovich DataFrame. """ import vaex.file return vaex.file.other.Zeldovich(dim=dim, N=N, n=n, t=t, scale=scale)
Concatenate a list of DataFrames.
def concat(dfs): '''Concatenate a list of DataFrames. :rtype: DataFrame ''' ds = reduce((lambda x, y: x.concat(y)), dfs) return ds
Creates a virtual column which is the equivalent of numpy. arange but uses 0 memory
def vrange(start, stop, step=1, dtype='f8'): """Creates a virtual column which is the equivalent of numpy.arange, but uses 0 memory""" from .column import ColumnVirtualRange return ColumnVirtualRange(start, stop, step, dtype)
if 1: # app = guisupport. get_app_qt4 () print_process_id ()
def main(argv=sys.argv[1:]): global main_thread global vaex global app global kernel global ipython_console global current vaex.set_log_level_warning() if app is None: app = QtGui.QApplication(argv) if not (frozen and darwin): # osx app has its own icon file ...