code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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)
# Determine the limits of the canvas
(cx1, cy1) = self.p2c((0, -math.pi / 2.0... | def limits(self, x1, x2, y1, y2) | Set the coordinate boundaries of plot | 2.816185 | 2.775496 | 1.01466 |
sun = ephem.Sun()
this_time = Time(self.date.get(), scale='utc')
sun.compute(this_time.iso)
self.sun = Coord((sun.ra, sun.dec))
self.doplot()
self.plot_pointings() | def reset(self) | Expand to the full scale | 8.672181 | 8.177075 | 1.060548 |
name = self.objList.get("active")
self.SearchVar.set(name)
self.object_info.set(str(self.kbos.get(name, '')))
return | def updateObj(self, event) | Put this object in the search box | 11.670616 | 9.623916 | 1.212668 |
name = self.SearchVar.get()
if self.kbos.has_key(name):
kbo = self.kbos[name]
assert isinstance(kbo, orbfit.Orbfit)
this_time = Time(self.date.get(), scale='utc')
try:
kbo.predict(this_time)
self.recenter(kbo.coord... | def relocate(self) | Move to the position of self.SearchVar | 5.419281 | 4.877209 | 1.111144 |
# compute the x,y of the center of the screen
sx1 = (self.cx1 + self.cx2) / 2.0
sy1 = (self.cy1 + self.cy2) / 2.0
if not event is None:
logging.debug("EVENT: {},{}".format(event.x, event.y))
sx1 = event.x
sy1 = event.y
(x, y) = self... | def zoom(self, event=None, scale=2.0) | Zoom in | 3.473765 | 3.537332 | 0.98203 |
if fill is None:
fill = color
(x, y) = self.p2c((xcen, ycen))
x1 = x - size
x2 = x + size
y1 = y - size
y2 = y + size
self.create_rectangle(x1, y1, x2, y2, fill=fill, outline=color) | def create_point(self, xcen, ycen, size=10, color='red', fill=None) | Plot a circle of size at this x,y location | 1.91907 | 1.976672 | 0.970859 |
if self.current is not None:
for item in self.pointings[self.current]['items']:
self.itemconfigure(item, outline="black")
self.current = index
for item in self.pointings[self.current]['items']:
self.itemconfigure(item, outline="blue") | def current_pointing(self, index) | set the color of the currently selected pointing to 'blue | 3.086676 | 2.835929 | 1.088418 |
if self.current is None:
return
for item in self.pointings[self.current]['items']:
self.delete(item)
self.delete(self.pointings[self.current]['label']['id'])
del (self.pointings[self.current])
self.current = None | def delete_pointing(self, event) | Delete the currently active pointing | 3.921705 | 3.834788 | 1.022666 |
filename = ( filename is None and tkFileDialog.askopenfilename() or filename)
if filename is None:
return
f = storage.open_vos_or_local(filename)
lines = f.readlines()
f.close()
points = []
if lines[0][0:5] == "<?xml":
# ## assu... | def load_pointings(self, filename=None) | Load some pointings | 4.040499 | 4.035861 | 1.001149 |
x = self.canvasx(event.x)
y = self.canvasy(event.y)
(ra, dec) = self.c2p((x, y))
this_camera = Camera(ra=float(ra) * units.radian, dec=float(dec)*units.radian, camera=self.camera.get())
ccds = numpy.radians(numpy.array(this_camera.geometry))
items = []
f... | def create_pointing(self, event, label_text=None) | Plot the sky coverage of pointing at event.x,event.y on the canvas. | 2.417315 | 2.387494 | 1.01249 |
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 numpy.radians(pointing["camera"].geometry):
... | def plot_pointings(self, pointings=None) | Plot pointings on canavs | 2.68838 | 2.661077 | 1.01026 |
current = self.current
pointing = self.pointings[current]
self.delete_pointing(None)
pointing["label"]['text'] = self.plabel.get()
self.pointings.append(pointing)
self.plot_pointings([pointing])
self.current = current | def set_pointing_label(self) | Let the label of the current pointing to the value in the plabel box | 6.192593 | 4.888901 | 1.266664 |
(ra, dec) = self.c2p((self.canvasx(event.x),
self.canvasy(event.y)))
closest = None
this_pointing = None
this_index = -1
index = -1
for pointing in self.pointings:
index = index + 1
# Find the camera we click... | def move_pointing(self, event) | Grab nearest pointing to event.x,event.y and with cursor | 2.792099 | 2.766335 | 1.009313 |
match = re.match('(\d+)\D(\d+)', self.expnum.get())
if match is not None:
expnum = int(match.group(1))
ccd = int(match.group(2))
x = 2112 / 2.0
y = 4644 / 2.0
else:
expnum = int(str(self.expnum.get()))
ccd = 22
... | def ossos_pointings(self) | plot an OSSOS observation on the OSSOS plot. | 4.170372 | 3.995201 | 1.043846 |
self.camera.set("MEGACAM_40")
(ra1, dec1) = self.c2p((self.canvasx(1), self.canvasy(1)))
(ra2, dec2) = self.c2p((self.canvasx(480 * 2), self.canvasy(360 * 2)))
ra_cen = math.degrees((ra2 + ra1) / 2.0)
dec_cen = math.degrees((dec2 + dec1) / 2.0)
# width = math.de... | def get_pointings(self) | Retrieve the MEGACAM pointings that overlap with the current FOV and plot.
@return: None | 3.620697 | 3.419088 | 1.058966 |
w = self
w.delete(ALL)
w.coord_grid()
w.objList.delete(0, END)
self._plot() | def doplot(self) | Clear the plot and then redraw it. | 13.746072 | 9.992271 | 1.37567 |
w = self
kbos = self.kbos
re_string = w.FilterVar.get()
vlist = []
for name in kbos:
if not re.search(re_string, name):
continue
vlist.append(name)
fill = None
is_colossos_target = False
for cna... | def _plot(self) | Draw the actual plot. | 4.173421 | 4.125725 | 1.011561 |
found_pos = []
detections = fk_candidate_observations.get_sources()
for detection in detections:
reading = detection.get_reading(0)
# create a list of positions, to be used later by match_lists
found_pos.append([reading.x, reading.y])
# The match_list method expects a list... | def planted(fk_candidate_observations, planted_objects, tolerance=10) | Using the fk_candidate_observations as input get the Object.planted file from VOSpace and match
planted sources with found sources.
The Object.planted list is pulled from VOSpace based on the standard file-layout and name of the
first exposure as read from the .astrom file.
:param fk_candidate_observa... | 5.45606 | 5.495401 | 0.992841 |
D2PI= 6.2831853071795864769252867665590057683943387987502
DS2R= 7.2722052166430399038487115353692196393452995355905e-5
tu = (mjd-51544.5)/36525.0;
st = fmod(mjd,1.0) * D2PI + ( 24110.54841 + ( 8640184.812866 + ( 0.093104 - 6.2e-6 * tu ) * tu ) * tu ) * DS2R
w = fmod(st,D2PI... | def mjd2gmst(mjd) | Convert Modfied Juian Date (JD = 2400000.5) to GMST
Take from P.T. Walace routines | 3.83276 | 3.830719 | 1.000533 |
import math
#from numpy.matlib import sin, cos, arcsin, arctan2
from math import sin, cos
from math import asin as arcsin
from math import atan2 as arctan2
from math import acos as arccos
eb=self.eb
el=self.el
ob=math.radians(23.... | def ec2eq(self) | Convert ecliptic coordinates to equatorial coordinates | 3.819245 | 3.608037 | 1.058538 |
x = np.genfromtxt(fname, unpack=True)
axes.plot(x[0], x[1], ltype) | def plot_line(axes, fname, ltype) | plot the ecliptic plane line on the given axes. | 2.957628 | 2.883285 | 1.025784 |
d_observer = 1. # 1 AU
# approximate object's distance d_heliocentric and d_geocentric as the same, d, because TNO
m_r = H + 2.5 * math.log10((d ** 4) / (phi * d_observer ** 4))
print("m_r = {:2.2f} for a H = {} TNO at {} AU at opposition.".format(
m_r, H, d))
return m_r | def apmag_at_absmag(H, d, phi=1) | Calculate the apparent magnitude of a TNO given its absolute magnitude H, for a given distance.
:param H: TNO absolute magnitude (unitless)
:param d: barycentric distance (AU)
:param phi: phase angle (0-1, always v close to 1 for TNOs)
:return: apparent magnitude of TNO | 9.50272 | 9.087502 | 1.045691 |
''' Summary format:
object mag stdev dist ..E nobs time av_xres av_yres max_x max_y
a ..E e ..E i ..E node ..E argperi ..E M ..E ra_dis dec_dis
'''
if not summaryLine:
raise ValueError('No summary line given')
if versi... | def from_summary_line(cls, summaryLine, version=4, existing_object=None) | Summary format:
object mag stdev dist ..E nobs time av_xres av_yres max_x max_y
a ..E e ..E i ..E node ..E argperi ..E M ..E ra_dis dec_dis | 6.457736 | 2.652921 | 2.434198 |
'''
Class format:
class wrt n m security object mag stdev F H_sur dist ..E nobs time av_xres av_yres max_x max_y
a ..E e ..E i ..E node ..E argperi ..E time_peri ..E rate
'''
if not classLine:
raise Val... | def from_class_line(cls, classLine, version=4, existing_object=None) | Class format:
class wrt n m security object mag stdev F H_sur dist ..E nobs time av_xres av_yres max_x max_y
a ..E e ..E i ..E node ..E argperi ..E time_peri ..E rate | 8.031229 | 3.618315 | 2.219605 |
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise SCCIInval... | def scci_cmd(host, userid, password, cmd, port=443, auth_method='basic',
client_timeout=60, do_async=True, **kwargs) | execute SCCI command
This function calls SCCI server modules
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param cmd: SCCI command
:param port: port number of iRMC
:param auth_method: irmc_username
... | 2.497119 | 2.416096 | 1.033535 |
return functools.partial(scci_cmd, host, userid, password,
port=port, auth_method=auth_method,
client_timeout=client_timeout, **kwargs) | def get_client(host, userid, password, port=443, auth_method='basic',
client_timeout=60, **kwargs) | get SCCI command partial function
This function returns SCCI command partial function
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param port: port number of iRMC
:param auth_method: irmc_username
:par... | 3.499905 | 2.56872 | 1.362509 |
cmd = _VIRTUAL_MEDIA_CD_SETTINGS % (
remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_deploy_iso,
remote_image_username,
remote_image_user_password)
return cmd | def get_virtual_cd_set_params_cmd(remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_deploy_iso,
... | get Virtual CD Media Set Parameters Command
This function returns Virtual CD Media Set Parameters Command
:param remote_image_server: remote image server name or IP
:param remote_image_user_domain: domain name of remote image server
:param remote_image_share_type: share type of ShareType
:param rem... | 2.01757 | 2.2534 | 0.895345 |
cmd = _VIRTUAL_MEDIA_FD_SETTINGS % (
remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_floppy_fat,
remote_image_username,
remote_image_user_password)
return cmd | def get_virtual_fd_set_params_cmd(remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_floppy_fat,
... | get Virtual FD Media Set Parameters Command
This function returns Virtual FD Media Set Parameters Command
:param remote_image_server: remote image server name or IP
:param remote_image_user_domain: domain name of remote image server
:param remote_image_share_type: share type of ShareType
:param rem... | 2.04012 | 2.363178 | 0.863295 |
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise SCCIInva... | def get_report(host, userid, password,
port=443, auth_method='basic', client_timeout=60) | get iRMC report
This function returns iRMC report in XML format
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: tim... | 2.515963 | 2.274771 | 1.106029 |
v = {}
v['memory_mb'] = int(report.find('./System/Memory/Installed').text)
v['local_gb'] = sum(
[int(int(size.text) / 1024)
for size in report.findall('.//PhysicalDrive/ConfigurableSize')])
v['cpus'] = sum([int(cpu.find('./CoreNumber').text)
for cpu in report.f... | def get_essential_properties(report, prop_keys) | get essential properties
This function returns a dictionary which contains keys as in
prop_keys and its values from the report.
:param report: SCCI report element
:param prop_keys: a list of keys for essential properties
:returns: a dictionary which contains keys as in
prop_keys and ... | 3.634988 | 3.697716 | 0.983036 |
snmp_client = snmp.SNMPClient(d_info['irmc_address'],
d_info['irmc_snmp_port'],
d_info['irmc_snmp_version'],
d_info['irmc_snmp_community'],
d_info['irmc_snmp_security'])
... | def get_capabilities_properties(d_info,
capa_keys,
gpu_ids,
fpga_ids=None,
**kwargs) | get capabilities properties
This function returns a dictionary which contains keys
and their values from the report.
:param d_info: the dictionary of ipmitool parameters for accessing a node.
:param capa_keys: a list of keys for additional capabilities properties.
:param gpu_ids: the list of stri... | 2.882925 | 2.764589 | 1.042804 |
session_expiration = time.time() + session_timeout
while time.time() < session_expiration:
try:
# Get session status to check
session = get_firmware_upgrade_status(irmc_info, upgrade_type)
except SCCIClientError:
# Ignore checking during rebooted server
... | def process_session_status(irmc_info, session_timeout, upgrade_type) | process session for Bios config backup/restore or RAID config operation
:param irmc_info: node info
:param session_timeout: session timeout
:param upgrade_type: flag to check upgrade with bios or irmc
:return: a dict with following values:
{
'upgrade_message': <Message of firmware u... | 4.934203 | 4.894021 | 1.00821 |
fgi_status = {}
raid_path = "./Software/ServerView/ServerViewRaid"
if not report.find(raid_path):
raise SCCIInvalidInputError(
"ServerView RAID not available in Bare metal Server")
if not report.find(raid_path + "/amEMSV/System/Adapter/LogicalDrive"):
raise SCCIRAIDNotR... | def get_raid_fgi_status(report) | Gather fgi(foreground initialization) information of raid configuration
This function returns a fgi status which contains activity status
and its values from the report.
:param report: SCCI report information
:returns: dict of fgi status of logical_drives, such as Initializing (10%)
or I... | 6.35959 | 4.732227 | 1.343889 |
host = irmc_info.get('irmc_address')
userid = irmc_info.get('irmc_username')
password = irmc_info.get('irmc_password')
port = irmc_info.get('irmc_port', 443)
auth_method = irmc_info.get('irmc_auth_method', 'digest')
client_timeout = irmc_info.get('irmc_client_timeout', 60)
auth_obj = ... | def get_firmware_upgrade_status(irmc_info, upgrade_type) | get firmware upgrade status of bios or irmc
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default is 443,
'irmc_auth_method': 'basic' or '... | 2.369036 | 1.990625 | 1.190096 |
_median = 0*ma[0].filled(fill_value=0)
for i in range(ma.shape[-1]):
t=xmedian(ma[:,:,i])
_median[:,i]=t
t=None
return _median | def median(ma) | do it row by row, to save memory.... | 6.781035 | 6.574239 | 1.031456 |
import numpy
_medianIndex = numpy.floor(ma.count(axis=0)/2.0)
_sortIndex = ma.argsort(kind='heapsort',axis=0)
_median = ma[0].filled(fill_value=0)*0
for idx in range(len(_sortIndex)):
_median = _median+_sortIndex[idx]*(_medianIndex==idx)
_medianIndex=_median
_median=0*_median
... | def xmedian(ma) | Given a masked numpy array (build using numpy.ma class) return
the median value of the array. | 3.635994 | 3.761077 | 0.966743 |
while True:
ef = get_epoch_field(astrom_header, fits_header)
epoch_field = ef[0] + ef[1]
count = storage.increment_object_counter(storage.MEASURE3, epoch_field)
try:
q.put(ef[1] + count)
except:
break | def _generate_provisional_name(q, astrom_header, fits_header) | Generates a name for an object given the information in its astrom
observation header and FITS header.
:param q: a queue of provisional names to return.
:type q: Queue
:param astrom_header:
:param fits_header: | 8.472601 | 8.941372 | 0.947573 |
if self.autoplay_manager.is_running():
self.autoplay_manager.stop_autoplay()
self.view.set_autoplay(False)
else:
self.autoplay_manager.start_autoplay()
self.view.set_autoplay(True) | def on_toggle_autoplay_key(self) | The user has pressed the keybind for toggling autoplay. | 2.30957 | 2.227943 | 1.036638 |
# Just extract the character code from the notes, not the
# full description
note1_code = note1.split(" ")[0]
note2_code = note2.split(" ")[0]
self.view.close_accept_source_dialog()
self.model.set_current_source_name(provisional_name)
source_cutout = se... | def on_do_accept(self,
minor_planet_number,
provisional_name,
note1,
note2,
date_of_obs,
ra,
dec,
obs_mag,
obs_mag_err,
... | After a source has been mark for acceptance create an MPC Observation record.
@param minor_planet_number: The MPC Number associated with the object
@param provisional_name: A provisional name associated with the object
@param note1: The observational quality note
@param note2: The obser... | 4.220786 | 4.181978 | 1.00928 |
self.view.close_vetting_accept_source_dialog()
# Set to None if blank
if len(comment.strip()) == 0:
comment = None
writer = self.model.get_writer()
writer.write_source(self.model.get_current_source(), comment=comment, reject=False)
self.model.accep... | def on_do_accept(self, comment) | WARNING WARNING: THIS IS ACUTALLY on_do_accept BUT HACKED.
TODO: Make it so that we have a short 'vetting' accept dialogue. Current accept dialogue too heavy for
this part of process, thus the hack.
Process the rejection of a vetting candidate, includes writing a comment to file.
@p... | 6.183288 | 6.67752 | 0.925986 |
cutout = self.model.get_current_cutout()
if research:
cutout.comparison_image_index = None
comparison_image = cutout.comparison_image
if comparison_image is None:
print "Failed to load comparison image: {}".format(cutout.comparison_image_list[cutout.comp... | def on_load_comparison(self, research=False) | Display the comparison image
@param research: find a new comparison image even if one already known? | 5.13802 | 4.864009 | 1.056334 |
wcs_dict = {}
for expnum in expnums:
try:
# TODO This assumes that the image is already N/E flipped.
# If compute_trans is called after the image is retrieved from archive then we get the disk version.
filename = storage.get_image(expnum, ccd, version, prefix=pre... | def compute_trans(expnums, ccd, version, prefix=None, default="WCS") | Pull the astrometric header for each image, compute an x/y transform and compare to trans.jmp
this one overides trans.jmp if they are very different.
@param expnums:
@param ccd:
@param version:
@param prefix:
@return: None | 3.262629 | 3.153494 | 1.034608 |
jmp_trans = ['step2ajmp']
jmp_args = ['step2bjmp']
matt_args = ['step2matt_jmp']
idx = 0
for expnum in expnums:
jmp_args.append(
storage.get_file(expnum, ccd=ccd, version=version, ext='obj.jmp', prefix=prefix)[0:-8]
)
jmp_trans.append(
storage.g... | def step2(expnums, ccd, version, prefix=None, dry_run=False, default="WCS") | run the actual step2 on the given exp/ccd combo | 3.435033 | 3.447184 | 0.996475 |
'''
parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return:
'''
zerostate = pandas.read_tab... | def parse_nate_sims(path) | parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return: | 6.615173 | 2.006374 | 3.297079 |
if mask not in range(0, 33):
raise scci.SCCIInvalidInputError(
'Netmask value is invalid.')
return socket.inet_ntoa(struct.pack(
'!L', int('1' * mask + '0' * (32 - mask), 2))) | def _convert_netmask(mask) | Convert netmask from CIDR format(integer) to doted decimal string. | 4.631981 | 4.173283 | 1.109913 |
self.root.use_virtual_addresses = True
self.root.manage.manage = True
self.root.mode = 'new'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) | def apply(self, reboot=False) | Apply the configuration to iRMC. | 12.417745 | 10.514451 | 1.181017 |
self.root.manage.manage = False
self.root.mode = 'delete'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) | def terminate(self, reboot=False) | Delete VIOM configuration from iRMC. | 14.290478 | 12.769336 | 1.119125 |
port_handler = _parse_physical_port_id(port_id)
port = self._find_port(port_handler)
if port:
port_handler.set_lan_port(port, mac)
else:
self._add_port(port_handler, port_handler.create_lan_port(mac)) | def set_lan_port(self, port_id, mac=None) | Set LAN port information to configuration.
:param port_id: Physical port ID.
:param mac: virtual MAC address if virtualization is necessary. | 3.473755 | 3.960301 | 0.877144 |
initiator_netmask = (_convert_netmask(initiator_netmask)
if initiator_netmask else None)
port_handler = _parse_physical_port_id(port_id)
iscsi_boot = _create_iscsi_boot(
initiator_iqn,
initiator_dhcp=initiator_dhcp,
init... | def set_iscsi_volume(self, port_id,
initiator_iqn, initiator_dhcp=False,
initiator_ip=None, initiator_netmask=None,
target_dhcp=False, target_iqn=None, target_ip=None,
target_port=3260, target_lun=0, boot_prio=1,
... | Set iSCSI volume information to configuration.
:param port_id: Physical port ID.
:param initiator_iqn: IQN of initiator.
:param initiator_dhcp: True if DHCP is used in the iSCSI network.
:param initiator_ip: IP address of initiator. None if DHCP is used.
:param initiator_netmask... | 1.893156 | 2.073745 | 0.912916 |
port_handler = _parse_physical_port_id(port_id)
fc_target = elcm.FCTarget(target_wwn, target_lun)
fc_boot = elcm.FCBoot(boot_prio=boot_prio, boot_enable=True)
fc_boot.add_target(fc_target)
port = self._find_port(port_handler)
if port:
port_handler.se... | def set_fc_volume(self, port_id,
target_wwn, target_lun=0, boot_prio=1,
initiator_wwnn=None, initiator_wwpn=None) | Set FibreChannel volume information to configuration.
:param port_id: Physical port ID.
:param target_wwn: WWN of target.
:param target_lun: LUN number of target.
:param boot_prio: Boot priority of the volume. 1 indicates the highest
priority.
:param initiator_wwn... | 2.860097 | 3.030195 | 0.943866 |
if not port_handler.need_padding():
return
for port_idx in range(1, port_handler.port_idx):
pad_handler = port_handler.__class__(
port_handler.slot_type,
port_handler.card_type,
port_handler.slot_idx,
port_h... | def _pad_former_ports(self, port_handler) | Create ports with former port index.
:param port_handler: Port information to be registered.
Depending on slot type and card type, it is necessary to register
LAN ports with former index to VIOM table. | 4.033286 | 3.263043 | 1.236051 |
byte_depth = _lookup[sf.subtype]
channels = sf.channels
bytes_per_second = byte_depth * sf.samplerate * channels
secs = len(buf) / bytes_per_second
secs = max(1, secs - 6)
return int(secs * sf.samplerate) | def chunk_size_samples(sf, buf) | Black magic to account for the fact that libsndfile's behavior varies
depending on file format when using the virtual io api.
If you ask for more samples from an ogg or flac file than are available
at that moment, libsndfile will give you no more samples ever, even if
more bytes arrive in the buffer la... | 5.406291 | 5.86659 | 0.921539 |
if not isinstance(number, (int, long)):
raise TypeError("Number must be an integer.")
base_n = ""
sign = ""
if number < 0:
sign = "-"
number = -number
if 0 <= number < len(alphabet):
return sign + alphabet[number]
while number != 0:
number, i = di... | def encode(number, alphabet) | Converts an integer to a base n string where n is the length of the
provided alphabet.
Modified from http://en.wikipedia.org/wiki/Base_36 | 1.862569 | 1.718633 | 1.08375 |
if normalize:
# normalize the signal
mx = x.max()
x = np.divide(x, mx, where=mx != 0)
# mu law compression
x = mu_law(x)
# translate and scale to [0, 1]
x = (x - x.min()) * 0.5
# convert to the range [0, 255]
x = (x * mu).astype(np.uint8)
# create the ar... | def categorical(x, mu=255, normalize=True) | Mu-law compress a block of audio samples, and convert them into a
categorical distribution | 4.259209 | 4.063361 | 1.048199 |
flat = x.reshape((-1, x.shape[-1]))
indices = np.argmax(flat, axis=1).astype(np.float32)
indices = (indices / mu) - 0.5
inverted = inverse_mu_law(indices, mu=mu).reshape(x.shape[:-1])
return ArrayWithUnits(inverted, x.dimensions[:2]) | def inverse_categorical(x, mu=255) | Invert categorical samples | 4.017135 | 4.07513 | 0.985769 |
freqs = np.array(freqs_in_hz)
scaling = 1 / len(freqs)
sr = int(self.samplerate)
cps = freqs / sr
ts = (duration / Seconds(1)) * sr
ranges = np.array([np.arange(0, ts * c, c) for c in cps])
raw = (np.sin(ranges * (2 * np.pi)) * scaling).sum(axis=0)
... | def synthesize(self, duration, freqs_in_hz=[440.]) | Synthesize one or more sine waves
Args:
duration (numpy.timdelta64): The duration of the sound to be
synthesized
freqs_in_hz (list of float): Numbers representing the frequencies
in hz that should be synthesized | 4.400032 | 5.225817 | 0.84198 |
sr = self.samplerate.samples_per_second
# create a short, tick sound
tick = np.random.uniform(low=-1., high=1., size=int(sr * .1))
tick *= np.linspace(1, 0, len(tick))
# create silence
samples = np.zeros(int(sr * (duration / Seconds(1))))
ticks_per_second... | def synthesize(self, duration, tick_frequency) | Synthesize periodic "ticks", generated from white noise and an envelope
Args:
duration (numpy.timedelta64): The total duration of the sound to be
synthesized
tick_frequency (numpy.timedelta64): The frequency of the ticking
sound | 4.274187 | 4.185398 | 1.021214 |
sr = self.samplerate.samples_per_second
seconds = duration / Seconds(1)
samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))
return AudioSamples(samples, self.samplerate) | def synthesize(self, duration) | Synthesize white noise
Args:
duration (numpy.timedelta64): The duration of the synthesized sound | 5.038632 | 5.610221 | 0.898116 |
self._ssos_queried = True
mpc_filename = self.save()
return self.builder.build_workunit(mpc_filename) | def query_ssos(self) | Use the MPC file that has been built up in processing this work
unit to generate another workunit. | 19.306854 | 7.014551 | 2.752401 |
self.get_writer().flush()
mpc_filename = self.get_writer().get_filename()
self.get_writer().close()
self._writer = None
return mpc_filename | def save(self) | Update the SouceReading information for the currently recorded observations and then flush those to a file.
@return: mpc_filename of the resulting save. | 5.74769 | 3.347494 | 1.717013 |
if self._writer is None:
suffix = tasks.get_suffix(tasks.TRACK_TASK)
try:
base_name = re.search("(?P<base_name>.*?)\.\d*{}".format(suffix), self.filename).group('base_name')
except:
base_name = os.path.splitext(self.filename)[0]
... | def get_writer(self) | Get a writer.
This method also makes the output filename be the same as the .track file but with .mpc.
(Currently only works on local filesystem)
:rtype MPCWriter | 3.843328 | 3.513329 | 1.093928 |
return self.name_filter is not None and re.search(self.name_filter, filename) is None | def _filter(self, filename) | return 'true' if filename doesn't match name_filter regex and should be filtered out of the list.
@param filename:
@return: | 5.390587 | 4.464279 | 1.207493 |
if ignore_list is None:
ignore_list = []
potential_files = self.get_potential_files(ignore_list)
while len(potential_files) > 0:
potential_file = self.select_potential_file(potential_files)
potential_files.remove(potential_file)
if self.... | def get_workunit(self, ignore_list=None) | Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been processed. A lock on
it has been acquired.
Ra... | 3.413301 | 3.295978 | 1.035596 |
exclude_prefix = self.taskid == tasks.suffixes.get(tasks.REALS_TASK, '') and 'fk' or None
filenames = [filename for filename in
self.directory_context.get_listing(self.taskid, exclude_prefix=exclude_prefix)
if filename not in ignore_list and
... | def get_potential_files(self, ignore_list) | Get a listing of files for the appropriate task which may or may
not be locked and/or done. | 5.364844 | 5.104075 | 1.05109 |
readings = self.get_readings(data)
discovery_index = self.get_discovery_index(data)
reordered_readings = (readings[discovery_index:discovery_index + 3] +
readings[:discovery_index] +
readings[discovery_index + 3:])
se... | def move_discovery_to_front(self, data) | Moves the discovery triplet to the front of the reading list.
Leaves everything else in the same order. | 2.605194 | 2.27078 | 1.147268 |
QUERY =(
)
# )
QUERY = QUERY.format( RAdeg, DECdeg, width, height)
data={"QUERY": QUERY,
"REQUEST": "doQuery",
"LANG": "ADQL",
"FORMAT": "votable"}
... | def TAPQuery(RAdeg=180.0, DECdeg=0.0, width=1, height=1) | Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object | 8.831962 | 9.225803 | 0.957311 |
tags = storage.get_tags(my_expnum)
count = 0
outcount = 0
fails = []
for ccd in my_ccds:
success = True
count += 1
for ops in ops_set:
for fake in ops[0]:
for my_program in ops[1]:
for version in ops[2]:
#print my_expnum,... | def check_tags(my_expnum, ops_set, my_ccds, dry_run=True) | check the tags for the given expnum/ccd set.
@param ops:
@param my_expnum:
@return: | 4.567513 | 4.777346 | 0.956078 |
import MOPfits
import os, shutil
filename=MOPfits.adGet(file_id,extno=int(ccd))
if int(ccd)<18:
tfname=filename+"F"
shutil.move(filename, tfname)
os.system("imcopy %s[-*,-*] %s" % (tfname, filename))
os.unlink(tfname)
if not os.access(filename,os.R_OK):
retur... | def get_flipped_ext(file_id,ccd) | Given a list of exposure numbers and CCD, get them from the DB | 7.767552 | 8.069718 | 0.962556 |
import MOPdbaccess
mysql = MOPdbaccess.connect('cfeps','cfhls',dbSystem='MYSQL')
cfeps=mysql.cursor()
sql="SELECT file_id FROM measure WHERE provisional LIKE %s"
cfeps.execute(sql,(object, ))
file_ids=cfeps.fetchall()
return (file_ids) | def get_file_ids(object) | Get the exposure for a particular line in the meausre table | 15.956484 | 12.564357 | 1.26998 |
parser = argparse.ArgumentParser(
description='replace image header')
parser.add_argument('--extname',
help='name of extension to in header')
parser.add_argument('expnum', type=str,
help='exposure to update')
parser.add_argument('-r', '--repla... | def main() | Do the script. | 4.407102 | 4.39716 | 1.002261 |
if deriv == 0:
return UK
if isinstance(deriv, complex):
def UKderiv(z):
return (-z) ** deriv.imag * UK(z)
return UKderiv
def UKderiv(z):
poly = arange(deriv) + 1
poly = poly - z if ndim(z) == 0 else poly - z.reshape(-1, 1)
poly = poly.prod(a... | def _deriv(UK, deriv) | Real deriv is to :math:`t`, complex deriv is to :math:`\ln t` | 4.734015 | 4.844777 | 0.977138 |
x = numpy.cos(lon) * numpy.cos(lat)
y = numpy.sin(lon) * numpy.cos(lat)
z = numpy.sin(lat)
# Invariable plane: values in arcseconds.
epsilon = 5713.86
omega = 387390.8
coseps = numpy.cos(epsilon * secrad)
sineps = numpy.sin(epsilon * secrad)
cosom = numpy.cos(omega * secrad)
... | def convert(lat, lon) | convert lat/lon from the ecliptic to the invariable plane. | 3.167706 | 2.711174 | 1.168389 |
import MOPfits,os
import MOPdbaccess
if len(expnums)!=3:
return(-1)
mysql=MOPdbaccess.connect('bucket','cfhls','MYSQL')
bucket=mysql.cursor()
### Some program Constants
proc_file = open("proc-these-files","w")
proc_file.write("# Files to be planted and search... | def searchTriples(expnums,ccd) | Given a list of exposure numbers, find all the KBOs in that set of exposures | 6.224062 | 6.256093 | 0.99488 |
if hasattr(error, "errno") and error.errno == errno.EACCES:
self.handle_certificate_problem(str(error))
else:
self.handle_general_download_error(str(error), download_request) | def handle_error(self, error, download_request) | Checks what error occured and looks for an appropriate solution.
Args:
error: Exception
The error that has occured.
download_request:
The request which resulted in the error. | 3.767955 | 4.052263 | 0.92984 |
# All HDU elements have the same date and time so just use
# last one, sometimes the first one is missing the header, in MEF
header = self.get_current_cutout().hdulist[-1].header
mjd_obs = float(header.get('MJD-OBS'))
exptime = float(header.get('EXPTIME'))
mpc_da... | def get_current_observation_date(self) | Get the date of the current observation by looking in the header
of the observation for the DATE and EXPTIME keywords.
The 'DATE AT MIDDLE OF OBSERVATION' of the observation is returned
@return: Time | 6.918177 | 6.636076 | 1.04251 |
return (eff_max-c*(m-21)**2)/(1+numpy.exp((m-m0)/sigma)) | def square(m, eff_max,c,m0,sigma,m1=21) | eff_max: Maximum of the efficiency function (peak efficiency)
c: shape of the drop-off in the efficiency at bright end
m0: transition to tappering at faint magnitudes
sigma: width of the transition in efficeincy
m1: magnitude at which peak efficeincy occurs
square(m) = (eff_max-c*(m-21)**2)/(1+exp... | 6.209519 | 2.611585 | 2.377682 |
if not line.startswith("square_param="):
raise ValueError("Not a valid square_param line")
values = line.split()
params = {'sigma': float(values.pop()),
'm0': float(values.pop()),
'c': float(values.pop()),
'eff_max': float(values.pop())
}
... | def parse_square_param(line) | Parse the line from the .eff file that contains the efficiency function
parameters for a 'square' function
line : the line containt the parameters, must start with 'square_param' | 4.046443 | 3.638198 | 1.112211 |
blocks = []
block = {}
with open(filename) as efile:
for line in efile.readlines():
if line.lstrip().startswith("#"):
continue
keyword = line.lstrip().split("=")[0]
funcs = {'square_param': parse_square_param,
'rates': r... | def parse_eff(filename) | Parse through Jean-Marcs OSSSO .eff files.
The efficiency files comes in 'chunks' meant to be used at different 'rates' of motion. | 4.892322 | 4.964688 | 0.985424 |
if configfile in _configs:
appconfig = _configs[configfile]
else:
appconfig = AppConfig(configfile=configfile)
_configs[configfile] = appconfig
return appconfig.read(keypath) | def read(keypath, configfile=None) | Reads a value from the configuration file.
Args:
keypath: str
Specifies the key for which the value is desired. It can be a
hierarchical path. Example: "section1.subsection.key1"
configfile: str
Path to the config file to read. Defaults to None, in which case
the appl... | 2.720877 | 3.897123 | 0.698176 |
fields = self.fields
header_lines = []
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
line += self._entry(fieldName, width, colsep)
header_lines.append(line)
line = ""
for fieldName in... | def _cdata_header(self, colsep="|") | Create a header for the CDATA section, as a visual guide. | 2.084221 | 2.042 | 1.020676 |
fields = self.fields
sra = coordinate.ra.to_string(units.hour, sep=':', precision=2, pad=True)
sdec = coordinate.dec.to_string(units.degree, sep=':', precision=1, alwayssign=True)
coord = SkyCoord(sra + " " + sdec, unit=(units.hour, units.degree))
sra = coord.ra.to_strin... | def _append_cdata(self, coordinate) | Append an target location to the ephemeris listing. | 2.828528 | 2.754026 | 1.027052 |
f_handle.write(GEMINI_HEADER)
# Date__(UT)__HR:MN Date_________JDUT R.A.___(ICRF/J2000.0)___DEC dRA*cosD d(DEC)/dt
# 1 2 3 4 5 6 7 8 9
# 12345678901234567890123456789012345678901234567890123456789012345... | def gemini_writer(self, f_handle) | Write out a GEMINI formated OT ephemeris. This is just a hack of SSD Horizons output. | 4.043816 | 3.920232 | 1.031524 |
for expnum in storage.list_dbimages():
for ccd in range(36):
if not storage.get_status(MKPSF, "", expnum, "p", ccd):
# get_status returns FALSE if process didn't succeed,
# with return_message=True it returns the error message.
print expnum, ... | def mkpsf_failures() | A simple script to loop over the standard tags for the mkpsf and
step1 processing steps. If exposure/ccd combo isn't marked as
'success' then report the failure.
This example uses the vos client directly. | 8.220591 | 6.940222 | 1.184485 |
sql= % ( expnum )
try:
import MOPdbaccess
mysql=MOPdbaccess.connect('bucket','cfhls',dbSystem='MYSQL')
bucket=mysql.cursor()
bucket.execute(sql)
nailings = bucket.fetchall()
mysql.close()
if int(ccd) < 18:
cutout="[-*,-*]"
else:
... | def get_nailing(expnum,ccd) | Get the 'nailing' images associated with expnum | 13.338847 | 13.352787 | 0.998956 |
lowest_stop = min(self.stop_hz, other.stop_hz)
highest_start = max(self.start_hz, other.start_hz)
return FrequencyBand(highest_start, lowest_stop) | def intersect(self, other) | Return the intersection between this frequency band and another.
Args:
other (FrequencyBand): the instance to intersect with
Examples::
>>> import zounds
>>> b1 = zounds.FrequencyBand(500, 1000)
>>> b2 = zounds.FrequencyBand(900, 2000)
>>> in... | 3.300911 | 2.743491 | 1.203179 |
if self._bands is None:
self._bands = self._compute_bands()
return self._bands | def bands(self) | An iterable of all bands in this scale | 3.917992 | 3.827465 | 1.023652 |
msg = \
'band {i}: ratio must be at least {required_ratio} but was {ratio}'
for i in range(0, len(self) - 1):
b1 = self[i]
b2 = self[i + 1]
try:
ratio = b1.intersection_ratio(b2)
except ValueError:
ra... | def ensure_overlap_ratio(self, required_ratio=0.5) | Ensure that every adjacent pair of frequency bands meets the overlap
ratio criteria. This can be helpful in scenarios where a scale is
being used in an invertible transform, and something like the `constant
overlap add constraint
<https://ccrma.stanford.edu/~jos/sasp/Constant_Overlap_Ad... | 3.654743 | 3.666404 | 0.996819 |
return np.array(list(self.center_frequencies)) \
/ np.array(list(self.bandwidths)) | def Q(self) | The quality factor of the scale, or, the ratio of center frequencies
to bandwidths | 8.333158 | 5.82774 | 1.429913 |
index = frequency_band
if isinstance(index, slice):
types = {
index.start.__class__,
index.stop.__class__,
index.step.__class__
}
if Hertz not in types:
return index
try:
... | def get_slice(self, frequency_band) | Given a frequency band, and a frequency dimension comprised of
n_samples, return a slice using integer indices that may be used to
extract only the frequency samples that intersect with the frequency
band | 3.4196 | 3.593597 | 0.951581 |
fb = FrequencyBand(0, sample_rate.nyquist)
return LinearScale(fb, n_bands, always_even=always_even) | def from_sample_rate(sample_rate, n_bands, always_even=False) | Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist frequency
will serve as the upper frequency bound of this scale
... | 6.015577 | 5.251319 | 1.145536 |
return np.log(hz / self._a440) / np.log(self._a) | def _hz_to_semitones(self, hz) | Convert hertz into a number of semitones above or below some reference
value, in this case, A440 | 7.107006 | 6.062253 | 1.172337 |
import re
sesame_cmd = 'curl -s http://cdsweb.u-strasbg.fr/viz-bin/nph-sesame/-oI?'+string.replace(object,' ','')
f = os.popen(sesame_cmd)
lines = f.readlines()
f.close()
for line in lines:
if re.search('%J ', line):
result2 = line.split()
ra_deg = ... | def resolve(object) | Look up the name of a source using a resolver | 5.738627 | 5.62676 | 1.019881 |
ax = axes or plt.gca()
for spine in remove:
ax.spines[spine].set_visible(False)
for spine in keep:
ax.spines[spine].set_linewidth(0.5)
# ax.spines[spine].set_color('white')
# remove all ticks, then add back the ones in keep
# Does this also need to specify the ticks' co... | def remove_border(axes=None, keep=('left', 'bottom'), remove=('right', 'top'), labelcol=ALMOST_BLACK) | Minimize chart junk by stripping out unnecessary plot borders and axis ticks.
The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn | 2.385604 | 2.451815 | 0.972995 |
# d is supposed to be a Dialog instance
if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
if code == d.DIALOG_CANCEL:
msg = "You chose cancel in the last dialog box. Do you want to " \
"exit this demo?"
else:
msg = "You pressed ESC in the last dialog box.... | def handle_exit_code(d, code) | Sample function showing how to interpret the dialog exit codes.
This function is not used after every call to dialog in this demo
for two reasons:
1. For some boxes, unfortunately, dialog returns the code for
ERROR when the user presses ESC (instead of the one chosen
for ESC). As th... | 5.208331 | 4.921688 | 1.058241 |
try:
demo()
except dialog.error, exc_instance:
sys.stderr.write("Error:\n\n%s\n" % exc_instance.complete_message())
sys.exit(1)
sys.exit(0) | def main() | This demo shows the main features of the pythondialog Dialog class. | 5.853603 | 4.584947 | 1.2767 |
import MOPfits,os
import MOPdbaccess
if len(expnums)!=3:
return(-1)
### Some program Constants
proc_file = open("proc-these-files","w")
proc_file.write("# Files to be planted and searched\n")
proc_file.write("# image fwhm plant\n")
import string
... | def searchTriples(expnums,ccd) | Given a list of exposure numbers, find all the KBOs in that set of exposures | 8.200349 | 8.251486 | 0.993803 |
cfht.date = current_time.iso.replace('-', '/')
cfht.horizon = math.radians(-7)
sun.compute(cfht)
sun_rise = Time(str(sun.rise_time).replace('/', '-'))
sun_set = Time(str(sun.set_time).replace('/', '-'))
if current_time < sun_set or current_time > sun_rise:
return False
fb._ra ... | def is_up(coordinate, current_time) | Given the position and time determin if the given target is up.
@param coordinate: the J2000 location of the source
@param current_time: The time of the observations
@return: True/False | 3.124827 | 3.187638 | 0.980295 |
tapURL = "http://cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/sync"
## Some default parameters for that TAP service queries.
tapParams={'REQUEST': 'doQuery',
'LANG': 'ADQL',
'FORMAT': 'votable',
'QUERY': query}
cnt=0
while True:
try:
... | def TAPQuery(query) | The __main__ part of the script | 4.158513 | 4.2648 | 0.975078 |
storage.get_file(expnum, ccd, prefix=prefix, version=version, ext='mopheader')
filename = storage.get_image(expnum, ccd, version=version, prefix=prefix)
fwhm = storage.get_fwhm(expnum, ccd, prefix=prefix, version=version)
basename = os.path.splitext(filename)[0]
logging.info(util.exec_prog(['... | def step1(expnum,
ccd,
prefix='',
version='p',
sex_thresh=_SEX_THRESHOLD,
wave_thresh=_WAVE_THRESHOLD,
maxcount=_MAX_COUNT,
dry_run=False) | run the actual step1jmp/matt codes.
expnum: the CFHT expousre to process
ccd: which ccd in the mosaic to process
fwhm: the image quality, FWHM, of the image. In pixels.
sex_thresh: the detection threhold to run sExtractor at
wave_thresh: the detection threshold for wavelet
maxcount: saturation... | 2.639242 | 2.591866 | 1.018279 |
viom_table = self.get_basic_json()
if self.slots:
viom_table['Slots'] = {
'Slot': [s.get_json() for s in self.slots.values()]
}
if self.manage:
viom_table['VIOMManage'] = self.manage.get_json()
return viom_table | def get_json(self) | Create JSON data for AdapterConfig.
:returns: JSON data as follows:
{
"VIOMManage":{
},
"InitBoot":{
},
"UseVirtualAddresses":{
},
"BootMenuEnable":{
},
"... | 4.559955 | 3.332187 | 1.368457 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.