code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
import sys,os,math,re import pyfits import MOPfiles obj=MOPfiles.read(obj_file) ### The mapping obj['hdu2sql']={'MAX_INT': 'peak', 'FLUX': 'flux', 'MAG': 'mag', 'MERR': 'merr', 'SKY': 'sky', 'ELON':...
def objIngest(obj_file)
The SQL description of the source table +-------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------+------+-----+---------+----------------+ | sourceID | int(11) | | PRI | NULL | auto_increment | ...
8.143363
7.359339
1.106535
import ephem,string,math if file is None: import tkFileDialog try: file=tkFileDialog.askopenfilename() except: return if file is None or file == '': return f=open(file) lines=f.readlines() f.close() for line in lines: p=line.spli...
def load_edbfile(file=None)
Load the targets from a file
3.628696
3.580649
1.013418
import ephem,string if dir is None: import tkFileDialog try: dir=tkFileDialog.askdirectory() except: return if dir is None: return None from glob import glob files=glob(dir+"/*.abg") import os for f in files: (name,ext)=os.path.s...
def load_abgfiles(dir=None)
Load the targets from a file
3.213074
3.22107
0.997518
import re, pyfits, wcsutil for file in fnames: if re.match(filter,file): fh=pyfits.open(file) for ext in fh: obj=ext.header.get('OBJECT',file) dx=ext.header.get('NAXIS1',None) dy=ext.header.get('NAXIS2',None) wc...
def fits_list(filter,root,fnames)
Get a list of files matching filter in directory root
4.211268
4.191018
1.004832
if dir is None: import tkFileDialog try: dir=tkFileDialog.askdirectory() except: return if dir is None: return None from os.path import walk walk(dir,fits_list,"*.fits")
def load_fis(dir=None)
Load fits images in a directory
6.115583
5.425609
1.12717
import orbfit, ephem, math import re re_string=w.FilterVar.get() vlist=[] for name in kbos: if not re.search(re_string,name): continue vlist.append(name) if type(kbos[name])==type(ephem.EllipticalBody()): kbos[name].compute(w.date.get()) ra=kbos[na...
def do_objs(kbos)
Draw the actual plot
3.874469
3.81304
1.01611
import tkFileDialog,tkMessageBox filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps']) if filename is None: return self.postscript(file=filename)
def eps(self)
Print the canvas to a postscript file
10.75725
7.464289
1.441162
return((p[0]-self.canvasx(self.cx1),p[1]-self.canvasy(self.cy1)))
def c2s(self,p=[0,0])
Convert from canvas to screen coordinates
6.023329
4.903806
1.228297
import math,ephem ra2=math.pi*2 ra1=0 dec1=-1*math.pi/2.0 dec2=math.pi/2.0 ## grid space choices ## ra space in hours ra_grids=["06:00:00", "03:00:00", "01:00:00", "00:30:00", ...
def coord_grid(self)
Draw a grid of RA/DEC on Canvas.
2.385475
2.313644
1.031047
(xc,yc)=self.p2c([x,y]) return self.create_text(xc-offset[0],yc-offset[1],text=label)
def label(self,x,y,label,offset=[0,0])
Write label at plot coordinates (x,y)
3.858992
3.745168
1.030392
import math self.x1=x1 self.x2=x2 self.y1=y1 self.y2=y2 self.xscale=(self.cx2-self.cx1)/(self.x2-self.x1) self.yscale=(self.cy2-self.cy1)/(self.y2-self.y1) ra1=self.x1 ra2=self.x2 dec1=self.y1 dec2=self.y2 (sx1,sy2)=self.p2c((ra1,dec1)) ...
def limits(self,x1,x2,y1,y2)
Set the coordinate boundaries of plot
2.432896
2.419392
1.005582
import ephem, MOPcoord sun=ephem.Sun() sun.compute(self.date.get()) self.sun=MOPcoord.coord((sun.ra,sun.dec)) doplot(kbos) self.plot_pointings()
def reset(self)
Expand to the full scale
21.322247
20.082493
1.061733
name=w.objList.get("active") w.SearchVar.set(name) w.ObjInfo.set(objInfoDict[name]) return
def updateObj(self,event)
Put this object in the search box
11.814819
9.638607
1.225781
name=self.SearchVar.get() if kbos.has_key(name): import orbfit,ephem,math jdate=ephem.julian_date(w.date.get()) try: (ra,dec,a,b,ang)=orbfit.predict(kbos[name],jdate,568) except: return ra=math.radians(ra) dec=math.radians(dec) elif mpc_objs.has_key(...
def relocate(self)
Move to the postion of self.SearchVar
6.69252
6.027555
1.110321
import Tkinter,math ## compute the x,y of the center of the screen sx1=self.cx1+(self.cx2-self.cx1+1.0)/2.0 sy1=self.cy1+(self.cy2-self.cy1+1.0)/2.0 #print sx1,sy1 if not event is None: sx1=event.x sy1=event.y #print sx1,sy1 ## translate that into a canvas locati...
def __zoom(self,event,scale=2.0)
Zoom in
4.798174
4.856913
0.987906
import math e1=[] e2=[] ang=ang-math.radians(90) for i in range(0,int(resolution)+1): x=(-1*a+2*a*float(i)/resolution) y=1-(x/a)**2 if y < 1E-6: y=1E-6 y=math.sqrt(y)*b ptv=self.p2c((x*math.cos(...
def create_ellipse(self,xcen,ycen,a,b,ang,resolution=40.0)
Plot ellipse at x,y with size a,b and orientation ang
2.706962
2.726766
0.992737
import MOPdbaccess,ephem,math import tkSimpleDialog result = tkSimpleDialog.askstring("Block Load", "Which Block do you want to plot?") db = MOPdbaccess.connect('bucket','cfhls',dbSystem='MYSQL') SQL = % (result) points=[] c = db.cursor() r = c.execute(SQL) rows=c.fetchall...
def get_pointings(self)
Query for some pointings, given a block name
5.918337
5.733663
1.032209
import os,re,ephem import tkFileDialog,tkMessageBox filename=tkFileDialog.askopenfilename() if filename is None: return f=open(filename) lines=f.readlines() f.close() points=[] if lines[0][0:5]=="<?xml": ### assume astrores format ### with <DATA at st...
def load_pointings(self)
Load some pointings
4.210781
4.172271
1.00923
import math (ra,dec)=self.c2p((self.canvasx(event.x), self.canvasy(event.y))) this_camera=camera(camera=self.camera.get()) ccds=this_camera.getGeometry(ra,dec) items=[] for ccd in ccds: (x1,y1)=self.p2c((ccd[0],ccd[1])) ...
def create_pointing(self,event)
Plot the sky coverage of pointing at event.x,event.y on the canavas
3.586432
3.5699
1.004631
if pointings is None: pointings=self.pointings i=0 for pointing in pointings: items=[] i=i+1 label={} label['text']=pointing['label']['text'] for ccd in pointing["camera"].getGeometry(): (x1,y1)=self.p2c((ccd[0],ccd[1])) ...
def plot_pointings(self,pointings=None)
Plot pointings on canavs
4.055913
4.061988
0.998504
self.pointings[self.current]['label']['text']=w.plabel.get() self.reset()
def set_pointing_label(self)
Let the label of the current pointing to the value in the plabel box
22.463446
19.114006
1.175235
import tkFileDialog f=tkFileDialog.asksaveasfile() i=0 if self.pointing_format.get()=='CFHT PH': f.write() if self.pointing_format.get()=='Palomar': f.write("index\n") for pointing in self.pointings: i=i+1 name=pointing["label"...
def save_pointings(self)
Print the currently defined FOVs
3.333016
3.299119
1.010274
import math,ephem ccds=[] if ra is None: ra=self.ra if dec is None: dec=self.dec self.ra=ephem.hours(ra) self.dec=ephem.degrees(dec) for geo in self.geometry[self.camera]: ycen=math.radians(geo["dec"])+dec ...
def getGeometry(self,ra=None,dec=None)
Return an array of rectangles that represent the 'ra,dec' corners of the FOV
3.030164
2.830003
1.070728
import ephem return ephem.separation((self.ra,self.dec),(ra,dec))
def separation(self,ra,dec)
Compute the separation between self and (ra,dec)
4.595101
4.623599
0.993836
h = np.random.binomial(1, 0.5, (x.shape[0], 1024)) packed = np.packbits(h, axis=-1).view(np.uint64) return zounds.ArrayWithUnits( packed, [x.dimensions[0], zounds.IdentityDimension()])
def produce_fake_hash(x)
Produce random, binary features, totally irrespective of the content of x, but in the same shape as x.
4.30708
4.123223
1.044591
bytes_list = [int(x, base=16) for x in raw_bytes.split()] return bytes_list[0], bytes_list[1], bytes_list[2:]
def _parse_raw_bytes(raw_bytes)
Convert a string of hexadecimal values to decimal values parameters Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to: 46, 241, [128, 40, 0, 26, 1, 0] :param raw_bytes: string of hexadecimal values :returns: 3 decimal values
3.164576
3.197809
0.989607
netfn, command, data = _parse_raw_bytes(raw_bytes) response = ipmicmd.raw_command(netfn, command, data=data) return response
def _send_raw_command(ipmicmd, raw_bytes)
Use IPMI command object to send raw ipmi command to BMC :param ipmicmd: IPMI command object :param raw_bytes: string of hexadecimal values. This is commonly used for certain vendor specific commands. :returns: dict -- The response from IPMI device
4.223202
4.01872
1.050882
# note: # Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0' # # $ ipmitool raw 0x2E 0xF5 0x80 0x28 0x00 0x81 0xC0 # # Raw response: # 80 28 00 C0 C0: True # 80 28 00 -- --: False (other values than 'C0 C0') ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'], ...
def get_tpm_status(d_info)
Get the TPM support status. Get the TPM support status of the node. :param d_info: the list of ipmitool parameters for accessing a node. :returns: TPM support status
4.373674
4.274234
1.023265
for i in range(1, 0xff + 1): try: res = _send_raw_command(ipmicmd, GET_PCI % hex(i)) yield i, res except ipmi_exception.IpmiException as e: raise IPMIFailure( "IPMI operation '%(operation)s' failed: %(error)s" % {'operation': "...
def _pci_seq(ipmicmd)
Get output of ipmiraw command and the ordinal numbers. :param ipmicmd: IPMI command object. :returns: List of tuple contain ordinal number and output of ipmiraw command.
4.611489
4.876615
0.945633
# note: # Get quantity of PCI devices: # ipmi cmd '0xF1' # # $ ipmitool raw 0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00 # # Raw response: # 80 28 00 00 00 05 data1 data2 34 17 76 11 00 04 # 01 # data1: 2 octet of VendorID # data2: 2 octet of DeviceID ipmicmd = ipmi_co...
def get_pci_device(d_info, pci_device_ids)
Get quantity of PCI devices. Get quantity of PCI devices of the node. :param d_info: the list of ipmitool parameters for accessing a node. :param pci_device_ids: the list contains pairs of <vendorID>/<deviceID> for PCI devices. :returns: the number of PCI devices.
5.50748
4.908249
1.122086
r for data in args: for key, value in data.items(): current.setdefault(key, value) return current
def defaults(current: dict, *args: AnyMapping) -> dict
r"""Override current dict with defaults values. :param current: Current dict. :param \*args: Sequence with default data dicts.
5.224561
5.568864
0.938174
def validate_func(schema: AnyMapping, pure_data: AnyMapping) -> AnyMapping: return validator_class(schema).validate(pure_data) return validate_func
def validate_func_factory(validator_class: Any) -> ValidateFunc
Provide default function for Schema validation. :param validator_class: JSONSchema suitable validator class.
5.310183
6.646203
0.79898
import cfhtCutout cdata={'ra_deg': ra, 'dec_deg': dec, 'radius_deg': 0.2} inter=cfhtCutout.find_images(cdata,0.2)
def moreData(ra,dec,box)
Search the CFHT archive for more images of this location
10.159318
7.786296
1.304769
import os f=os.popen('xpaaccess ds9') l=f.readline() f.close() if l.strip()!='yes': logger.debug("\t Can't get ds9 access, xpaccess said: %s" % ( l.strip())) return (False) return(True)
def xpacheck()
Check if xpa is running
8.314507
7.704184
1.07922
if label is not None: os.system("xpaset -p ds9 regions color red ") cmd="echo 'image; text %d %d # text={%s}' | xpaset ds9 regions " % ( x,y,label) else: os.system("xpaset -p ds9 regions color blue") cmd="echo 'image; circle %d %d 10 ' | xpaset ds9 regions " % (x,y) os.system(cmd) return
def mark(x,y,label=None)
Mark a circle on the current image
5.24538
5.101876
1.028128
import os oscmd="curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'" % (url) logger.debug(oscmd) os.system(oscmd+' | xpaset ds9 fits') return
def display(url)
Display a file in ds9
17.555443
14.101508
1.244934
self.x, self.y = self.y, self.x self._x_, self._y_ = self._y_, self._x_ self.xfac, self.yfac = 1 / self.yfac, 1 / self.xfac self._xfac_, self._yfac_ = 1 / self._yfac_, 1 / self._xfac_ self._u = 1 / self._u.conj()
def inv(self)
Invert the transform. After calling this method, calling the instance will do the inverse transform. Calling this twice return the instance to the original transform.
2.878785
2.766393
1.040628
v = np.fft.hfft(self._u, n=self.N) / self.N idx = sum(np.ogrid[0:self.N, -self.N:0]) C = v[idx] # follow scipy.linalg.{circulant,toeplitz,hankel} if keeppads: a = self._yfac_.copy() b = self._xfac_.copy() else: a = self.yfac.copy() ...
def matrix(self, full=False, keeppads=True)
Return matrix form of the integral transform. Parameters ---------- full : bool, optional when False return two vector factors and convolution matrix separately, otherwise return full transformation matrix keeppads : bool, optional whether to keep the...
4.866907
3.67424
1.324602
assert a.shape[axis] == self.Nin axis %= a.ndim # to fix the indexing below with axis+1 to_axis = [1] * a.ndim to_axis[axis] = -1 Npad = self.N - self.Nin if out: _Npad, Npad_ = Npad - Npad//2, Npad//2 else: _Npad, Npad_ = Npa...
def _pad(self, a, axis, extrap, out)
Add padding to an array. Parameters ---------- a : (..., Nin, ...) ndarray array to be padded to size `N` axis : int axis along which to pad extrap : {bool, 'const'} or 2-tuple Method to extrapolate `a`. For a 2-tuple, the two elem...
2.506686
2.283355
1.097808
assert a.shape[axis] == self.N Npad = self.N - self.Nin if out: _Npad, Npad_ = Npad - Npad//2, Npad//2 else: _Npad, Npad_ = Npad//2, Npad - Npad//2 return np.take(a, range(_Npad, self.N - Npad_), axis=axis)
def _unpad(self, a, axis, out)
Undo padding in an array. Parameters ---------- a : (..., N, ...) ndarray array to be trimmed to size `Nin` axis : int axis along which to unpad out : bool trim the output if True, otherwise the input; the two cases have their left...
4.013535
3.260242
1.231054
assert F.ndim == 1, "checker only supports 1D" f = self.xfac * F fabs = np.abs(f) iQ1, iQ3 = np.searchsorted(fabs.cumsum(), np.array([0.25, 0.75]) * fabs.sum()) assert 0 != iQ1 != iQ3 != self.Nin, "checker giving up" fabs_l = fabs[:iQ1].mean() fabs_m =...
def check(self, F)
Rough sanity checks on the input function.
2.645282
2.638059
1.002738
if padding_samples > 0: padded = np.concatenate( [x, np.zeros((len(x), padding_samples), dtype=x.dtype)], axis=axis) else: padded = x transformed = np.fft.rfft(padded, axis=axis, norm='ortho') sr = audio_sample_rate(int(Seconds(1) / x.dimensions[axis].frequ...
def fft(x, axis=-1, padding_samples=0)
Apply an FFT along the given dimension, and with the specified amount of zero-padding Args: x (ArrayWithUnits): an :class:`~zounds.core.ArrayWithUnits` instance which has one or more :class:`~zounds.timeseries.TimeDimension` axes axis (int): The axis along which the fft ...
3.888681
3.838169
1.01316
basis_size = len(scale) basis = np.zeros((basis_size, kernel_size), dtype=np.complex128) try: if len(scaling_factor) != len(scale): raise ValueError('scaling factor must have same length as scale') except TypeError: scaling_factor = np.repeat(float(scaling_factor), len(...
def morlet_filter_bank( samplerate, kernel_size, scale, scaling_factor, normalize=True)
Create a :class:`~zounds.core.ArrayWithUnits` instance with a :class:`~zounds.timeseries.TimeDimension` and a :class:`~zounds.spectral.FrequencyDimension` representing a bank of morlet wavelets centered on the sub-bands of the scale. Args: samplerate (SampleRate): the samplerate of the input si...
3.476493
3.121667
1.113665
self.x_offset += (bias - self._bias) self._bias = bias self._build_cdict()
def set_bias(self, bias)
Adjusts the image bias. Bias determines where the color changes start. At low bias, low intensities (i.e., low pixel values) will have non-zero color differences, while at high bias only high pixel values will have non-zero differences Args: bias: float A...
12.096552
13.85684
0.872966
self._contrast = contrast self.x_spread = 2 * (1.0 - contrast) self.y_spread = 2.0 - 2 * (1.0 - contrast) self._build_cdict()
def set_contrast(self, contrast)
Adjusts the image contrast. Contrast refers to the rate of change of color with color level. At low contrast, color changes gradually over many intensity levels, while at high contrast it can change rapidly within a few levels Args: contrast: float A numbe...
5.031468
5.946755
0.846086
# If both storage: Tries to perform same storage direct copy if src_is_storage and dst_is_storage: system_src = get_instance(src) system_dst = get_instance(dst) # Same storage copy if system_src is system_dst: # Checks if same file if system_src.rel...
def _copy(src, dst, src_is_storage, dst_is_storage)
Copies file from source to destination Args: src (str or file-like object): Source file. dst (str or file-like object): Destination file. src_is_storage (bool): Source is storage. dst_is_storage (bool): Destination is storage.
3.716361
3.710874
1.001479
# Handles path-like objects and checks if storage src, src_is_storage = format_and_is_storage(src) dst, dst_is_storage = format_and_is_storage(dst) # Local files: Redirects to "shutil.copy" if not src_is_storage and not dst_is_storage: return shutil_copy(src, dst) with handle_os_e...
def copy(src, dst)
Copies a source file to a destination file or directory. Equivalent to "shutil.copy". Source and destination can also be binary opened file-like objects. Args: src (path-like object or file-like object): Source file. dst (path-like object or file-like object): Destination file...
5.780417
5.945294
0.972268
# Handles path-like objects and checks if storage src, src_is_storage = format_and_is_storage(src) dst, dst_is_storage = format_and_is_storage(dst) # Local files: Redirects to "shutil.copyfile" if not src_is_storage and not dst_is_storage: return shutil_copyfile(src, dst, follow_symlin...
def copyfile(src, dst, follow_symlinks=True)
Copies a source file to a destination file. Equivalent to "shutil.copyfile". Source and destination can also be binary opened file-like objects. Args: src (path-like object or file-like object): Source file. dst (path-like object or file-like object): Destination file. follow_syml...
5.54837
5.685246
0.975924
try: yield except _ClientError as exception: error = exception.response['Error'] if error['Code'] in _ERROR_CODES: raise _ERROR_CODES[error['Code']](error['Message']) raise
def _handle_client_error()
Handle boto exception and convert to class IO exceptions Raises: OSError subclasses: IO error.
3.73575
4.21294
0.886732
copy_source = self.get_client_kwargs(src) copy_destination = self.get_client_kwargs(dst) with _handle_client_error(): self.client.copy_object(CopySource=copy_source, **copy_destination)
def copy(self, src, dst, other_system=None)
Copy object of the same storage. Args: src (str): Path or URL. dst (str): Path or URL. other_system (pycosio._core.io_system.SystemBase subclass): Unused.
4.099216
4.84552
0.845981
bucket_name, key = self.split_locator(path) kwargs = dict(Bucket=bucket_name) if key: kwargs['Key'] = key return kwargs
def get_client_kwargs(self, path)
Get base keyword arguments for client for a specific path. Args: path (str): Absolute path or URL. Returns: dict: client args
3.934592
6.288302
0.6257
if self._session is None: self._session = _boto3.session.Session( **self._storage_parameters.get('session', dict())) return self._session
def _get_session(self)
S3 Boto3 Session. Returns: boto3.session.Session: session
5.377629
5.018084
1.07165
client_kwargs = self._storage_parameters.get('client', dict()) # Handles unsecure mode if self._unsecure: client_kwargs = client_kwargs.copy() client_kwargs['use_ssl'] = False return self._get_session().client("s3", **client_kwargs)
def _get_client(self)
S3 Boto3 client Returns: boto3.session.Session.client: client
5.162094
5.166266
0.999192
region = self._get_session().region_name or r'[\w-]+' return ( # S3 scheme # - s3://<bucket>/<key> 's3://', # Virtual-hosted–style URL # - http://<bucket>.s3.amazonaws.com/<key> # - https://<bucket>...
def _get_roots(self)
Return URL roots for this storage. Returns: tuple of str or re.Pattern: URL roots
2.08578
1.991066
1.04757
for key in keys: try: return _to_timestamp(header.pop(key)) except KeyError: continue raise _UnsupportedOperation(name)
def _get_time(header, keys, name)
Get time from header Args: header (dict): Object header. keys (tuple of str): Header keys. name (str): Method name. Returns: float: The number of seconds since the epoch
6.315199
9.315823
0.6779
with _handle_client_error(): # Object if 'Key' in client_kwargs: header = self.client.head_object(**client_kwargs) # Bucket else: header = self.client.head_bucket(**client_kwargs) # Clean up HTTP request informati...
def _head(self, client_kwargs)
Returns object or bucket HTTP header. Args: client_kwargs (dict): Client arguments. Returns: dict: HTTP header.
5.161803
4.700316
1.098182
with _handle_client_error(): # Object if 'Key' in client_kwargs: return self.client.put_object(Body=b'', **client_kwargs) # Bucket return self.client.create_bucket( Bucket=client_kwargs['Bucket'], CreateBuc...
def _make_dir(self, client_kwargs)
Make a directory. args: client_kwargs (dict): Client arguments.
4.35389
4.319382
1.007989
with _handle_client_error(): # Object if 'Key' in client_kwargs: return self.client.delete_object(**client_kwargs) # Bucket return self.client.delete_bucket(Bucket=client_kwargs['Bucket'])
def _remove(self, client_kwargs)
Remove an object. args: client_kwargs (dict): Client arguments.
4.468579
4.349246
1.027438
with _handle_client_error(): response = self.client.list_buckets() for bucket in response['Buckets']: yield bucket.pop('Name'), bucket
def _list_locators(self)
Lists locators. Returns: generator of tuple: locator name str, locator header dict
8.677674
13.586735
0.638687
client_kwargs = client_kwargs.copy() if max_request_entries: client_kwargs['MaxKeys'] = max_request_entries while True: with _handle_client_error(): response = self.client.list_objects_v2( Prefix=path, **client_kwargs) ...
def _list_objects(self, client_kwargs, path, max_request_entries)
Lists objects. args: client_kwargs (dict): Client arguments. path (str): Path relative to current locator. max_request_entries (int): If specified, maximum entries returned by request. Returns: generator of tuple: object name str, object ...
3.107695
3.237643
0.959863
# Get object part from S3 try: with _handle_client_error(): response = self._client.get_object( Range=self._http_range(start, end), **self._client_kwargs) # Check for end of file except _ClientError as exception: if ex...
def _read_range(self, start, end=0)
Read a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. Returns: bytes: number of bytes read
5.044974
5.337108
0.945264
with _handle_client_error(): self._client.put_object( Body=buffer.tobytes(), **self._client_kwargs)
def _flush(self, buffer)
Flush the write buffers of the stream if applicable. Args: buffer (memoryview): Buffer content.
9.977675
10.224414
0.975868
# Initialize multi-part upload if 'UploadId' not in self._upload_args: with _handle_client_error(): self._upload_args[ 'UploadId'] = self._client.create_multipart_upload( **self._client_kwargs)['UploadId'] # Upload par...
def _flush(self)
Flush the write buffers of the stream.
5.559695
5.306532
1.047708
# Wait parts upload completion for part in self._write_futures: part['ETag'] = part.pop('response').result()['ETag'] # Complete multipart upload with _handle_client_error(): try: self._client.complete_multipart_upload( ...
def _close_writable(self)
Close the object in write mode.
4.302166
4.35596
0.98765
try: yield except _AzureHttpError as exception: if exception.status_code in _ERROR_CODES: raise _ERROR_CODES[exception.status_code](str(exception)) raise
def _handle_azure_exception()
Handles Azure exception and convert to class IO exceptions Raises: OSError subclasses: IO error.
4.381563
4.820616
0.908922
result = {} for attr in properties.__dict__: value = getattr(properties, attr) if hasattr(value, '__module__') and 'models' in value.__module__: value = _properties_model_to_dict(value) if not (value is None or (isinstance(value, dict) and not value)): resu...
def _properties_model_to_dict(properties)
Convert properties model to dict. Args: properties: Properties model. Returns: dict: Converted model.
2.948125
2.828891
1.042148
storage_parameters = self._storage_parameters or dict() account_name = storage_parameters.get('account_name') if not account_name: raise ValueError('"account_name" is required for Azure storage') suffix = storage_parameters.get( 'endpoint_suffix', 'core...
def _get_endpoint(self, sub_domain)
Get endpoint information from storage parameters. Update system with endpoint information and return information required to define roots. Args: self (pycosio._core.io_system.SystemBase subclass): System. sub_domain (str): Azure storage sub-domain. Returns: ...
3.597636
2.940608
1.223433
parameters = self._storage_parameters or dict() # Handles unsecure mode if self._unsecure: parameters = parameters.copy() parameters['protocol'] = 'http' return parameters
def _secured_storage_parameters(self)
Updates storage parameters with unsecure mode. Returns: dict: Updated storage_parameters.
7.126314
6.674596
1.067677
path = '%s/%s' % (self._endpoint, self.relpath(path)) # If SAS token available, use it to give cross account copy access. if caller_system is not self: try: path = '%s?%s' % (path, self._storage_parameters['sas_token']) except KeyError: ...
def _format_src_url(self, path, caller_system)
Ensure path is absolute and use the correct URL format for use with cross Azure storage account copy function. Args: path (str): Path or URL. caller_system (pycosio.storage.azure._AzureBaseSystem subclass): System calling this method (Can be another Azure system)...
6.978405
6.692028
1.042794
client_kwargs = client_kwargs.copy() if max_request_entries: client_kwargs['num_results'] = max_request_entries return client_kwargs
def _update_listing_client_kwargs(client_kwargs, max_request_entries)
Updates client kwargs for listing functions. Args: client_kwargs (dict): Client arguments. max_request_entries (int): If specified, maximum entries returned by request. Returns: dict: Updated client_kwargs
2.746239
3.357493
0.817943
result = _properties_model_to_dict(obj.properties) for attribute in ('metadata', 'snapshot'): try: value = getattr(obj, attribute) except AttributeError: continue if value: result[attribute] = value retu...
def _model_to_dict(obj)
Convert object model to dict. Args: obj: Object model. Returns: dict: Converted model.
4.426735
5.514429
0.802755
stream = _BytesIO() try: with _handle_azure_exception(): self._get_to_stream( stream=stream, start_range=start, end_range=(end - 1) if end else None, **self._client_kwargs) # Check for end of file except _Azure...
def _read_range(self, start, end=0)
Read a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. Returns: bytes: number of bytes read
5.118161
5.623396
0.910155
stream = _BytesIO() with _handle_azure_exception(): self._get_to_stream(stream=stream, **self._client_kwargs) return stream.getvalue()
def _readall(self)
Read and return all the bytes from the stream until EOF. Returns: bytes: Object content
9.315041
12.12924
0.767982
if self._content_length: # Adjust size if content length specified with _handle_azure_exception(): self._resize( content_length=self._content_length, **self._client_kwargs) self._reset_head() # Make initial seek positi...
def _init_append(self)
Initializes file on 'a' mode.
12.370673
11.895159
1.039975
# Create new file with _handle_azure_exception(): self._create_from_size( content_length=self._content_length, **self._client_kwargs)
def _create(self)
Create the file if not exists.
12.671321
11.400772
1.111444
buffer_size = len(buffer) if not buffer_size: return # Write range normally with self._size_lock: if end > self._size: # Require to resize the blob if note enough space with _handle_azure_exception(): s...
def _flush(self, buffer, start, end)
Flush the write buffer of the stream if applicable. Args: buffer (memoryview): Buffer content. start (int): Start of buffer position to flush. Supported only with page blobs. end (int): End of buffer position to flush. Supported only with page...
3.836339
3.881124
0.988461
method_name = method.__name__ @wraps(method) def patched(self, *args, **kwargs): # Gets value from cache try: return self._cache[method_name] # Evaluates and cache value except KeyError: result = self._cache[method_name] = method( ...
def memoizedmethod(method)
Decorator that caches method result. Args: method (function): Method Returns: function: Memoized method. Notes: Target method class needs as "_cache" attribute (dict). It is the case of "ObjectIOBase" and all its subclasses.
2.97322
3.863798
0.769507
first_value_future = self._workers.submit(next, generator) def get_first_element(future=first_value_future): try: yield future.result() except StopIteration: return return chain(get_first_element(), generator)
def _generate_async(self, generator)
Return the previous generator object after having run the first element evaluation as a background task. Args: generator (iterable): A generator function. Returns: iterable: The generator function with first element evaluated in background.
5.375625
6.430908
0.835904
try: yield except _ClientException as exception: if exception.http_status in _ERROR_CODES: raise _ERROR_CODES[exception.http_status]( exception.http_reason) raise
def _handle_client_exception()
Handle Swift exception and convert to class IO exceptions Raises: OSError subclasses: IO error.
5.289746
5.637932
0.938242
container, obj = self.split_locator(src) with _handle_client_exception(): self.client.copy_object( container=container, obj=obj, destination=self.relpath(dst))
def copy(self, src, dst, other_system=None)
Copy object of the same storage. Args: src (str): Path or URL. dst (str): Path or URL. other_system (pycosio._core.io_system.SystemBase subclass): Unused.
8.043926
8.584548
0.937024
container, obj = self.split_locator(path) kwargs = dict(container=container) if obj: kwargs['obj'] = obj return kwargs
def get_client_kwargs(self, path)
Get base keyword arguments for client for a specific path. Args: path (str): Absolute path or URL. Returns: dict: client args
4.842161
6.853688
0.706504
kwargs = self._storage_parameters # Handles unsecure mode if self._unsecure: kwargs = kwargs.copy() kwargs['ssl_compression'] = False return _swift.client.Connection(**kwargs)
def _get_client(self)
Swift client Returns: swiftclient.client.Connection: client
9.449109
10.049424
0.940264
with _handle_client_exception(): # Object if 'obj' in client_kwargs: return self.client.head_object(**client_kwargs) # Container return self.client.head_container(**client_kwargs)
def _head(self, client_kwargs)
Returns object HTTP header. Args: client_kwargs (dict): Client arguments. Returns: dict: HTTP header.
4.443507
5.097645
0.871678
with _handle_client_exception(): # Object if 'obj' in client_kwargs: return self.client.put_object( client_kwargs['container'], client_kwargs['obj'], b'') # Container return self.client.put_container(client_kwargs['con...
def _make_dir(self, client_kwargs)
Make a directory. args: client_kwargs (dict): Client arguments.
4.544744
4.177721
1.087852
with _handle_client_exception(): # Object if 'obj' in client_kwargs: return self.client.delete_object( client_kwargs['container'], client_kwargs['obj']) # Container return self.client.delete_container(client_kwargs['co...
def _remove(self, client_kwargs)
Remove an object. args: client_kwargs (dict): Client arguments.
3.82452
3.564941
1.072814
with _handle_client_exception(): response = self.client.get_account() for container in response[1]: yield container.pop('name'), container
def _list_locators(self)
Lists locators. Returns: generator of tuple: locator name str, locator header dict
12.386404
17.404657
0.711672
kwargs = dict(prefix=path) if max_request_entries: kwargs['limit'] = max_request_entries else: kwargs['full_listing'] = True with _handle_client_exception(): response = self.client.get_container( client_kwargs['container'], **...
def _list_objects(self, client_kwargs, path, max_request_entries)
Lists objects. args: client_kwargs (dict): Client arguments. path (str): Path relative to current locator. max_request_entries (int): If specified, maximum entries returned by request. Returns: generator of tuple: object name str, object ...
3.695099
4.03041
0.916805
try: with _handle_client_exception(): return self._client.get_object(*self._client_args, headers=dict( Range=self._http_range(start, end)))[1] except _ClientException as exception: if exception.http_status == 416: # EO...
def _read_range(self, start, end=0)
Read a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. Returns: bytes: number of bytes read
5.664978
5.963356
0.949965
container, obj = self._client_args with _handle_client_exception(): self._client.put_object(container, obj, buffer)
def _flush(self, buffer)
Flush the write buffers of the stream if applicable. Args: buffer (memoryview): Buffer content.
10.425368
14.609532
0.7136
# Upload segment with workers name = self._segment_name % self._seek response = self._workers.submit( self._client.put_object, self._container, name, self._get_buffer()) # Save segment information in manifest self._write_futures.append(dict( ...
def _flush(self)
Flush the write buffers of the stream.
11.183324
10.955122
1.020831
# Wait segments upload completion for segment in self._write_futures: segment['etag'] = segment['etag'].result() # Upload manifest file with _handle_client_exception(): self._client.put_object(self._container, self._object_name, _dumps( s...
def _close_writable(self)
Close the object in write mode.
9.545252
9.487965
1.006038
# Require to load the full file content in buffer self._write_buffer[:] = self._readall() # Make initial seek position to current end of file self._seek = self._size
def _init_append(self)
Initializes file on 'a' mode.
21.191856
19.212551
1.103021
if self._writable and not self._is_raw_of_buffered and not self._closed: self._closed = True if self._write_buffer: self.flush()
def close(self)
Flush the write buffers of the stream if applicable and close the object.
8.170746
6.579456
1.241857
with self._seek_lock: seek = self._seek with handle_os_exceptions(): return self._read_range(seek, seek + size)
def _peek(self, size=-1)
Return bytes from the stream without advancing the position. Args: size (int): Number of bytes to read. -1 to read the full stream. Returns: bytes: bytes read
10.105008
15.67071
0.644834
if not self._readable: raise UnsupportedOperation('read') with self._seek_lock: # Get data starting from seek with handle_os_exceptions(): if self._seek and self._seekable: data = self._read_range(self._seek) ...
def readall(self)
Read and return all the bytes from the stream until EOF. Returns: bytes: Object content
6.321383
6.885581
0.918061
if not self._readable: raise UnsupportedOperation('read') # Get and update stream positions size = len(b) with self._seek_lock: start = self._seek end = start + size self._seek = end # Read data range with handle_...
def readinto(self, b)
Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. Args: b (bytes-like object): buffer. Returns: int: number of bytes read
3.931169
3.976227
0.988668
if not self._seekable: raise UnsupportedOperation('seek') seek = self._update_seek(offset, whence) # If seek move out of file, add padding until new seek position. if self._writable: size = len(self._write_buffer) if seek > size: ...
def seek(self, offset, whence=SEEK_SET)
Change the stream position to the given byte offset. Args: offset (int): Offset is interpreted relative to the position indicated by whence. whence (int): The default value for whence is SEEK_SET. Values for whence are: SEEK_SET or 0 – sta...
5.337446
5.949823
0.897076
with self._seek_lock: if whence == SEEK_SET: self._seek = offset elif whence == SEEK_CUR: self._seek += offset elif whence == SEEK_END: self._seek = offset + self._size else: raise ValueError...
def _update_seek(self, offset, whence)
Update seek value. Args: offset (int): Offset. whence (int): Whence. Returns: int: Seek position.
2.217873
2.366207
0.937312
if not self._writable: raise UnsupportedOperation('write') # This function write data in a buffer # "flush()" need to be called to really write content on # Cloud Storage size = len(b) with self._seek_lock: start = self._seek ...
def write(self, b)
Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. Args: b (bytes-like object): Bytes to write. Returns: int: The number of bytes written.
6.98967
7.126952
0.980738
code = response.status_code if 200 <= code < 400: return response elif code in (403, 404): raise {403: _ObjectPermissionError, 404: _ObjectNotFoundError}[code](response.reason) response.raise_for_status()
def _handle_http_errors(response)
Check for HTTP errors and raise OSError if relevant. Args: response (requests.Response): Returns: requests.Response: response
3.801938
3.99135
0.952544