_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q262500 | Phase.Cp_mag | validation | def Cp_mag(self, T):
"""
Calculate the phase's magnetic contribution to heat capacity at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol/K] The magnetic heat capacity of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
c = (self._B_mag*(2*tau**3 + 2*tau**9/3 + 2*tau**15/5))/self._D_mag
else:
c = (2*tau**-5 + 2*tau**-15/3 + 2*tau**-25/5)/self._D_mag
result = R*math.log(self.beta0_mag + 1)*c
return result | python | {
"resource": ""
} |
q262501 | Phase.H | validation | def H(self, T):
"""
Calculate the enthalpy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The enthalpy of the compound phase.
"""
result = self.DHref
for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):
result += self._Cp_records[str(Tmax)].H(T)
if T <= Tmax:
return result + self.H_mag(T)
# Extrapolate beyond the upper limit by using a constant heat capacity.
Tmax = max([float(TT) for TT in self._Cp_records.keys()])
result += self.Cp(Tmax)*(T - Tmax)
return result + self.H_mag(T) | python | {
"resource": ""
} |
q262502 | Phase.H_mag | validation | def H_mag(self, T):
"""
Calculate the phase's magnetic contribution to enthalpy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol] The magnetic enthalpy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
h = (-self._A_mag/tau +
self._B_mag*(tau**3/2 + tau**9/15 + tau**15/40))/self._D_mag
else:
h = -(tau**-5/2 + tau**-15/21 + tau**-25/60)/self._D_mag
return R*T*math.log(self.beta0_mag + 1)*h | python | {
"resource": ""
} |
q262503 | Phase.S | validation | def S(self, T):
"""
Calculate the entropy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol/K] The entropy of the compound phase.
"""
result = self.Sref
for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):
result += self._Cp_records[str(Tmax)].S(T)
if T <= Tmax:
return result + self.S_mag(T)
# Extrapolate beyond the upper limit by using a constant heat capacity.
Tmax = max([float(TT) for TT in self._Cp_records.keys()])
result += self.Cp(Tmax)*math.log(T / Tmax)
return result + self.S_mag(T) | python | {
"resource": ""
} |
q262504 | Phase.S_mag | validation | def S_mag(self, T):
"""
Calculate the phase's magnetic contribution to entropy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol/K] The magnetic entropy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
s = 1 - (self._B_mag*(2*tau**3/3 + 2*tau**9/27 + 2*tau**15/75)) / \
self._D_mag
else:
s = (2*tau**-5/5 + 2*tau**-15/45 + 2*tau**-25/125)/self._D_mag
return -R*math.log(self.beta0_mag + 1)*s | python | {
"resource": ""
} |
q262505 | Phase.G_mag | validation | def G_mag(self, T):
"""
Calculate the phase's magnetic contribution to Gibbs energy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol] The magnetic Gibbs energy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
g = 1 - (self._A_mag/tau +
self._B_mag*(tau**3/6 + tau**9/135 + tau**15/600)) /\
self._D_mag
else:
g = -(tau**-5/10 + tau**-15/315 + tau**-25/1500)/self._D_mag
return R*T*math.log(self.beta0_mag + 1)*g | python | {
"resource": ""
} |
q262506 | Compound.Cp | validation | def Cp(self, phase, T):
"""
Calculate the heat capacity of a phase of the compound at a specified
temperature.
:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature
:returns: [J/mol/K] Heat capacity.
"""
if phase not in self._phases:
raise Exception("The phase '%s' was not found in compound '%s'." %
(phase, self.formula))
return self._phases[phase].Cp(T) | python | {
"resource": ""
} |
q262507 | Compound.H | validation | def H(self, phase, T):
"""
Calculate the enthalpy of a phase of the compound at a specified
temperature.
:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature
:returns: [J/mol] Enthalpy.
"""
try:
return self._phases[phase].H(T)
except KeyError:
raise Exception("The phase '{}' was not found in compound '{}'."
.format(phase, self.formula)) | python | {
"resource": ""
} |
q262508 | _create_polynomial_model | validation | def _create_polynomial_model(
name: str,
symbol: str,
degree: int,
ds: DataSet,
dss: dict):
"""
Create a polynomial model to describe the specified property based on the
specified data set, and save it to a .json file.
:param name: material name.
:param symbol: property symbol.
:param degree: polynomial degree.
:param ds: the source data set.
:param dss: dictionary of all datasets.
"""
ds_name = ds.name.split(".")[0].lower()
file_name = f"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}"
newmod = PolynomialModelT.create(ds, symbol, degree)
newmod.plot(dss, _path(f"data/{file_name}.pdf"), False)
newmod.write(_path(f"data/{file_name}.json")) | python | {
"resource": ""
} |
q262509 | _create_air | validation | def _create_air():
"""
Create a dictionary of datasets and a material object for air.
:return: (Material, {str, DataSet})
"""
name = "Air"
namel = name.lower()
mm = 28.9645 # g/mol
ds_dict = _create_ds_dict([
"dataset-air-lienhard2015",
"dataset-air-lienhard2018"])
active_ds = "dataset-air-lienhard2018"
# create polynomial models to describe material properties
# comment it out after model creation is complete, so that it does not
# run every time during use.
# _create_polynomial_model(name, "Cp", 13, ds_dict[active_ds], ds_dict)
# _create_polynomial_model(name, "k", 8, ds_dict[active_ds], ds_dict)
# _create_polynomial_model(name, "mu", 8, ds_dict[active_ds], ds_dict)
# _create_polynomial_model(name, "rho", 14, ds_dict[active_ds], ds_dict)
# IgRhoT(mm, 101325.0).plot(ds_dict, _path(f"data/{namel}-rho-igrhot.pdf"))
model_dict = {
"rho": IgRhoT(mm, 101325.0),
"beta": IgBetaT()}
model_type = "polynomialmodelt"
for property in ["Cp", "mu", "k"]:
name = f"data/{namel}-{property.lower()}-{model_type}-{active_ds}.json"
model_dict[property] = PolynomialModelT.read(_path(name))
material = Material(name, StateOfMatter.gas, model_dict)
return material, ds_dict | python | {
"resource": ""
} |
q262510 | Report.render | validation | def render(self, format=ReportFormat.printout):
"""
Render the report in the specified format
:param format: The format. The default format is to print
the report to the console.
:returns: If the format was set to 'string' then a string
representation of the report is returned.
"""
table = self._generate_table_()
if format == ReportFormat.printout:
print(tabulate(table, headers="firstrow", tablefmt="simple"))
elif format == ReportFormat.latex:
self._render_latex_(table)
elif format == ReportFormat.txt:
self._render_txt_(table)
elif format == ReportFormat.csv:
self._render_csv_(table)
elif format == ReportFormat.string:
return str(tabulate(table, headers="firstrow", tablefmt="simple"))
elif format == ReportFormat.matplotlib:
self._render_matplotlib_()
elif format == ReportFormat.png:
if self.output_path is None:
self._render_matplotlib_()
else:
self._render_matplotlib_(True) | python | {
"resource": ""
} |
q262511 | rgb_to_hex | validation | def rgb_to_hex(rgb):
"""
Convert an RGB color representation to a HEX color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HEX representation of the input RGB value.
:rtype: str
"""
r, g, b = rgb
return "#{0}{1}{2}".format(hex(int(r))[2:].zfill(2), hex(int(g))[2:].zfill(2), hex(int(b))[2:].zfill(2)) | python | {
"resource": ""
} |
q262512 | rgb_to_yiq | validation | def rgb_to_yiq(rgb):
"""
Convert an RGB color representation to a YIQ color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: YIQ representation of the input RGB value.
:rtype: tuple
"""
r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255
y = (0.299 * r) + (0.587 * g) + (0.114 * b)
i = (0.596 * r) - (0.275 * g) - (0.321 * b)
q = (0.212 * r) - (0.528 * g) + (0.311 * b)
return round(y, 3), round(i, 3), round(q, 3) | python | {
"resource": ""
} |
q262513 | rgb_to_hsv | validation | def rgb_to_hsv(rgb):
"""
Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HSV representation of the input RGB value.
:rtype: tuple
"""
r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255
_min = min(r, g, b)
_max = max(r, g, b)
v = _max
delta = _max - _min
if _max == 0:
return 0, 0, v
s = delta / _max
if delta == 0:
delta = 1
if r == _max:
h = 60 * (((g - b) / delta) % 6)
elif g == _max:
h = 60 * (((b - r) / delta) + 2)
else:
h = 60 * (((r - g) / delta) + 4)
return round(h, 3), round(s, 3), round(v, 3) | python | {
"resource": ""
} |
q262514 | hex_to_rgb | validation | def hex_to_rgb(_hex):
"""
Convert a HEX color representation to an RGB color representation.
hex :: hex -> [000000, FFFFFF]
:param _hex: The 3- or 6-char hexadecimal string representing the color value.
:return: RGB representation of the input HEX value.
:rtype: tuple
"""
_hex = _hex.strip('#')
n = len(_hex) // 3
if len(_hex) == 3:
r = int(_hex[:n] * 2, 16)
g = int(_hex[n:2 * n] * 2, 16)
b = int(_hex[2 * n:3 * n] * 2, 16)
else:
r = int(_hex[:n], 16)
g = int(_hex[n:2 * n], 16)
b = int(_hex[2 * n:3 * n], 16)
return r, g, b | python | {
"resource": ""
} |
q262515 | yiq_to_rgb | validation | def yiq_to_rgb(yiq):
"""
Convert a YIQ color representation to an RGB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the luma and chrominance.
:return: RGB representation of the input YIQ value.
:rtype: tuple
"""
y, i, q = yiq
r = y + (0.956 * i) + (0.621 * q)
g = y - (0.272 * i) - (0.647 * q)
b = y - (1.108 * i) + (1.705 * q)
r = 1 if r > 1 else max(0, r)
g = 1 if g > 1 else max(0, g)
b = 1 if b > 1 else max(0, b)
return round(r * 255, 3), round(g * 255, 3), round(b * 255, 3) | python | {
"resource": ""
} |
q262516 | hsv_to_rgb | validation | def hsv_to_rgb(hsv):
"""
Convert an HSV color representation to an RGB color representation.
(h, s, v) :: h -> [0, 360)
s -> [0, 1]
v -> [0, 1]
:param hsv: A tuple of three numeric values corresponding to the hue, saturation, and value.
:return: RGB representation of the input HSV value.
:rtype: tuple
"""
h, s, v = hsv
c = v * s
h /= 60
x = c * (1 - abs((h % 2) - 1))
m = v - c
if h < 1:
res = (c, x, 0)
elif h < 2:
res = (x, c, 0)
elif h < 3:
res = (0, c, x)
elif h < 4:
res = (0, x, c)
elif h < 5:
res = (x, 0, c)
elif h < 6:
res = (c, 0, x)
else:
raise ColorException("Unable to convert from HSV to RGB")
r, g, b = res
return round((r + m)*255, 3), round((g + m)*255, 3), round((b + m)*255, 3) | python | {
"resource": ""
} |
q262517 | color_run | validation | def color_run(start_color, end_color, step_count, inclusive=True, to_color=True):
"""
Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between
the start and end color.
:param start_color: The color starting the run
:param end_color: The color ending the run
:param step_count: The number of colors to have between the start and end color
:param inclusive: Flag determining whether to include start and end values in run (default True)
:param to_color: Flag indicating return values should be Color objects (default True)
:return: List of colors between the start and end color
:rtype: list
"""
if isinstance(start_color, Color):
start_color = start_color.rgb
if isinstance(end_color, Color):
end_color = end_color.rgb
step = tuple((end_color[i] - start_color[i])/step_count for i in range(3))
add = lambda x, y: tuple(sum(z) for z in zip(x, y))
mult = lambda x, y: tuple(y * z for z in x)
run = [add(start_color, mult(step, i)) for i in range(1, step_count)]
if inclusive:
run = [start_color] + run + [end_color]
return run if not to_color else [Color(c) for c in run] | python | {
"resource": ""
} |
q262518 | ForgiveDB.get | validation | def get(self, key, default=None):
""" Get key value, return default if key doesn't exist """
if self.in_memory:
return self._memory_db.get(key, default)
else:
db = self._read_file()
return db.get(key, default) | python | {
"resource": ""
} |
q262519 | ForgiveDB.set | validation | def set(self, key, value):
""" Set key value """
if self.in_memory:
self._memory_db[key] = value
else:
db = self._read_file()
db[key] = value
with open(self.db_path, 'w') as f:
f.write(json.dumps(db, ensure_ascii=False, indent=2)) | python | {
"resource": ""
} |
q262520 | paginate_link_tag | validation | def paginate_link_tag(item):
"""
Create an A-HREF tag that points to another page usable in paginate.
"""
a_tag = Page.default_link_tag(item)
if item['type'] == 'current_page':
return make_html_tag('li', a_tag, **{'class': 'blue white-text'})
return make_html_tag('li', a_tag) | python | {
"resource": ""
} |
q262521 | EcoNetApiInterface.set_state | validation | def set_state(_id, body):
"""
Set a devices state.
"""
url = DEVICE_URL % _id
if "mode" in body:
url = MODES_URL % _id
arequest = requests.put(url, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code != '202':
_LOGGER.error("State not accepted. " + status_code)
return False | python | {
"resource": ""
} |
q262522 | EcoNetApiInterface.get_modes | validation | def get_modes(_id):
"""
Pull a water heater's modes from the API.
"""
url = MODES_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.json() | python | {
"resource": ""
} |
q262523 | EcoNetApiInterface.get_usage | validation | def get_usage(_id):
"""
Pull a water heater's usage report from the API.
"""
url = USAGE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
try:
return arequest.json()
except ValueError:
_LOGGER.info("Failed to get usage. Not supported by unit?")
return None | python | {
"resource": ""
} |
q262524 | EcoNetApiInterface.get_device | validation | def get_device(_id):
"""
Pull a device from the API.
"""
url = DEVICE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.json() | python | {
"resource": ""
} |
q262525 | EcoNetApiInterface.get_locations | validation | def get_locations():
"""
Pull the accounts locations.
"""
arequest = requests.get(LOCATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.json() | python | {
"resource": ""
} |
q262526 | EcoNetApiInterface.get_vacations | validation | def get_vacations():
"""
Pull the accounts vacations.
"""
arequest = requests.get(VACATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.json() | python | {
"resource": ""
} |
q262527 | EcoNetApiInterface.create_vacation | validation | def create_vacation(body):
"""
Create a vacation.
"""
arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code != '200':
_LOGGER.error("Failed to create vacation. " + status_code)
_LOGGER.error(arequest.json())
return False
return arequest.json() | python | {
"resource": ""
} |
q262528 | EcoNetApiInterface.delete_vacation | validation | def delete_vacation(_id):
"""
Delete a vacation by ID.
"""
arequest = requests.delete(VACATIONS_URL + "/" + _id, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code != '202':
_LOGGER.error("Failed to delete vacation. " + status_code)
return False
return True | python | {
"resource": ""
} |
q262529 | EcoNetApiInterface._authenticate | validation | def _authenticate(self):
"""
Authenticate with the API and return an authentication token.
"""
auth_url = BASE_URL + "/auth/token"
payload = {'username': self.email, 'password': self.password, 'grant_type': 'password'}
arequest = requests.post(auth_url, data=payload, headers=BASIC_HEADERS)
status = arequest.status_code
if status != 200:
_LOGGER.error("Authentication request failed, please check credintials. " + str(status))
return False
response = arequest.json()
_LOGGER.debug(str(response))
self.token = response.get("access_token")
self.refresh_token = response.get("refresh_token")
_auth = HEADERS.get("Authorization")
_auth = _auth % self.token
HEADERS["Authorization"] = _auth
_LOGGER.info("Authentication was successful, token set.")
return True | python | {
"resource": ""
} |
q262530 | PyEcoNet.get_water_heaters | validation | def get_water_heaters(self):
"""
Return a list of water heater devices.
Parses the response from the locations endpoint in to a pyeconet.WaterHeater.
"""
water_heaters = []
for location in self.locations:
_location_id = location.get("id")
for device in location.get("equipment"):
if device.get("type") == "Water Heater":
water_heater_modes = self.api_interface.get_modes(device.get("id"))
water_heater_usage = self.api_interface.get_usage(device.get("id"))
water_heater = self.api_interface.get_device(device.get("id"))
vacations = self.api_interface.get_vacations()
device_vacations = []
for vacation in vacations:
for equipment in vacation.get("participatingEquipment"):
if equipment.get("id") == water_heater.get("id"):
device_vacations.append(EcoNetVacation(vacation, self.api_interface))
water_heaters.append(EcoNetWaterHeater(water_heater, water_heater_modes, water_heater_usage,
_location_id,
device_vacations,
self.api_interface))
return water_heaters | python | {
"resource": ""
} |
q262531 | models_preparing | validation | def models_preparing(app):
""" Wrap all sqlalchemy model in settings.
"""
def wrapper(resource, parent):
if isinstance(resource, DeclarativeMeta):
resource = ListResource(resource)
if not getattr(resource, '__parent__', None):
resource.__parent__ = parent
return resource
resources_preparing_factory(app, wrapper) | python | {
"resource": ""
} |
q262532 | _translateCommands | validation | def _translateCommands(commands):
"""Generate the binary strings for a comma seperated list of commands."""
for command in commands.split(','):
# each command results in 2 bytes of binary data
result = [0, 0]
device, command = command.strip().upper().split(None, 1)
# translate the house code
result[0] = houseCodes[device[0]]
# translate the device number if there is one
if len(device) > 1:
deviceNumber = deviceNumbers[device[1:]]
result[0] |= deviceNumber[0]
result[1] = deviceNumber[1]
# translate the command
result[1] |= commandCodes[command]
# convert 2 bytes to bit strings and yield them
yield ' '.join(map(_strBinary, result)) | python | {
"resource": ""
} |
q262533 | _sendBinaryData | validation | def _sendBinaryData(port, data):
"""Send a string of binary data to the FireCracker with proper timing.
See the diagram in the spec referenced above for timing information.
The module level variables leadInOutDelay and bitDelay represent how
long each type of delay should be in seconds. They may require tweaking
on some setups.
"""
_reset(port)
time.sleep(leadInOutDelay)
for digit in data:
_sendBit(port, digit)
time.sleep(leadInOutDelay) | python | {
"resource": ""
} |
q262534 | _setRTSDTR | validation | def _setRTSDTR(port, RTS, DTR):
"""Set RTS and DTR to the requested state."""
port.setRTS(RTS)
port.setDTR(DTR) | python | {
"resource": ""
} |
q262535 | sendCommands | validation | def sendCommands(comPort, commands):
"""Send X10 commands using the FireCracker on comPort
comPort should be the name of a serial port on the host platform. On
Windows, for example, 'com1'.
commands should be a string consisting of X10 commands separated by
commas. For example. 'A1 On, A Dim, A Dim, A Dim, A Lamps Off'. The
letter is a house code (A-P) and the number is the device number (1-16).
Possible commands for a house code / device number combination are
'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a
house code alone after sending an On command to a specific device. The
'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also
be used with a house code alone.
# Turn on module A1
>>> sendCommands('com1', 'A1 On')
# Turn all modules with house code A off
>>> sendCommands('com1', 'A All Off')
# Turn all lamp modules with house code B on
>>> sendCommands('com1', 'B Lamps On')
# Turn on module A1 and dim it 3 steps, then brighten it 1 step
>>> sendCommands('com1', 'A1 On, A Dim, A Dim, A Dim, A Bright')
"""
mutex.acquire()
try:
try:
port = serial.Serial(port=comPort)
header = '11010101 10101010'
footer = '10101101'
for command in _translateCommands(commands):
_sendBinaryData(port, header + command + footer)
except serial.SerialException:
print('Unable to open serial port %s' % comPort)
print('')
raise
finally:
mutex.release() | python | {
"resource": ""
} |
q262536 | main | validation | def main(argv=None):
"""Send X10 commands when module is used from the command line.
This uses syntax similar to sendCommands, for example:
x10.py com2 A1 On, A2 Off, B All Off
"""
if len(argv):
# join all the arguments together by spaces so that quotes
# aren't required on the command line.
commands = ' '.join(argv)
# the comPort is everything leading up to the first space
comPort, commands = commands.split(None, 1)
sendCommands(comPort, commands)
return 0 | python | {
"resource": ""
} |
q262537 | normalize_housecode | validation | def normalize_housecode(house_code):
"""Returns a normalized house code, i.e. upper case.
Raises exception X10InvalidHouseCode if house code appears to be invalid
"""
if house_code is None:
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
if not isinstance(house_code, basestring):
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
if len(house_code) != 1:
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
house_code = house_code.upper()
if not ('A' <= house_code <= 'P'):
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
return house_code | python | {
"resource": ""
} |
q262538 | normalize_unitnumber | validation | def normalize_unitnumber(unit_number):
"""Returns a normalized unit number, i.e. integers
Raises exception X10InvalidUnitNumber if unit number appears to be invalid
"""
try:
try:
unit_number = int(unit_number)
except ValueError:
raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)
except TypeError:
raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)
if not (1 <= unit_number <= 16):
raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)
return unit_number | python | {
"resource": ""
} |
q262539 | X10Driver.x10_command | validation | def x10_command(self, house_code, unit_number, state):
"""Send X10 command to ??? unit.
@param house_code (A-P) - example='A'
@param unit_number (1-16)- example=1 (or None to impact entire house code)
@param state - Mochad command/state, See
https://sourceforge.net/p/mochad/code/ci/master/tree/README
examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc.
Examples:
x10_command('A', '1', ON)
x10_command('A', '1', OFF)
x10_command('A', '1', 'ON')
x10_command('A', '1', 'OFF')
x10_command('A', None, ON)
x10_command('A', None, OFF)
x10_command('A', None, 'all_lights_off')
x10_command('A', None, 'all_units_off')
x10_command('A', None, ALL_OFF)
x10_command('A', None, 'all_lights_on')
x10_command('A', 1, 'xdim 128')
"""
house_code = normalize_housecode(house_code)
if unit_number is not None:
unit_number = normalize_unitnumber(unit_number)
# else command is intended for the entire house code, not a single unit number
# TODO normalize/validate state
return self._x10_command(house_code, unit_number, state) | python | {
"resource": ""
} |
q262540 | get_parser | validation | def get_parser():
"""
Generate an appropriate parser.
:returns: an argument parser
:rtype: `ArgumentParser`
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"package",
choices=arg_map.keys(),
help="designates the package to test")
parser.add_argument("--ignore", help="ignore these files")
return parser | python | {
"resource": ""
} |
q262541 | get_command | validation | def get_command(namespace):
"""
Get the pylint command for these arguments.
:param `Namespace` namespace: the namespace
"""
cmd = ["pylint", namespace.package] + arg_map[namespace.package]
if namespace.ignore:
cmd.append("--ignore=%s" % namespace.ignore)
return cmd | python | {
"resource": ""
} |
q262542 | _wrapper | validation | def _wrapper(func):
"""
Wraps a generated function so that it catches all Type- and ValueErrors
and raises IntoDPValueErrors.
:param func: the transforming function
"""
@functools.wraps(func)
def the_func(expr):
"""
The actual function.
:param object expr: the expression to be xformed to dbus-python types
"""
try:
return func(expr)
except (TypeError, ValueError) as err:
raise IntoDPValueError(expr, "expr", "could not be transformed") \
from err
return the_func | python | {
"resource": ""
} |
q262543 | xformers | validation | def xformers(sig):
"""
Get the list of xformer functions for the given signature.
:param str sig: a signature
:returns: a list of xformer functions for the given signature.
:rtype: list of tuple of a function * str
Each function catches all TypeErrors it encounters and raises
corresponding IntoDPValueError exceptions.
"""
return \
[(_wrapper(f), l) for (f, l) in \
_XFORMER.PARSER.parseString(sig, parseAll=True)] | python | {
"resource": ""
} |
q262544 | xformer | validation | def xformer(signature):
"""
Returns a transformer function for the given signature.
:param str signature: a dbus signature
:returns: a function to transform a list of objects to inhabit the signature
:rtype: (list of object) -> (list of object)
"""
funcs = [f for (f, _) in xformers(signature)]
def the_func(objects):
"""
Returns the a list of objects, transformed.
:param objects: a list of objects
:type objects: list of object
:returns: transformed objects
:rtype: list of object (in dbus types)
"""
if len(objects) != len(funcs):
raise IntoDPValueError(
objects,
"objects",
"must have exactly %u items, has %u" % \
(len(funcs), len(objects))
)
return [x for (x, _) in (f(a) for (f, a) in zip(funcs, objects))]
return the_func | python | {
"resource": ""
} |
q262545 | _ToDbusXformer._variant_levels | validation | def _variant_levels(level, variant):
"""
Gets the level for the variant.
:param int level: the current variant level
:param int variant: the value for this level if variant
:returns: a level for the object and one for the function
:rtype: int * int
"""
return (level + variant, level + variant) \
if variant != 0 else (variant, level) | python | {
"resource": ""
} |
q262546 | _ToDbusXformer._handle_variant | validation | def _handle_variant(self):
"""
Generate the correct function for a variant signature.
:returns: function that returns an appropriate value
:rtype: ((str * object) or list)-> object
"""
def the_func(a_tuple, variant=0):
"""
Function for generating a variant value from a tuple.
:param a_tuple: the parts of the variant
:type a_tuple: (str * object) or list
:param int variant: object's variant index
:returns: a value of the correct type with correct variant level
:rtype: object * int
"""
# pylint: disable=unused-argument
(signature, an_obj) = a_tuple
(func, sig) = self.COMPLETE.parseString(signature)[0]
assert sig == signature
(xformed, _) = func(an_obj, variant=variant + 1)
return (xformed, xformed.variant_level)
return (the_func, 'v') | python | {
"resource": ""
} |
q262547 | _ToDbusXformer._handle_array | validation | def _handle_array(toks):
"""
Generate the correct function for an array signature.
:param toks: the list of parsed tokens
:returns: function that returns an Array or Dictionary value
:rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str
"""
if len(toks) == 5 and toks[1] == '{' and toks[4] == '}':
subtree = toks[2:4]
signature = ''.join(s for (_, s) in subtree)
[key_func, value_func] = [f for (f, _) in subtree]
def the_dict_func(a_dict, variant=0):
"""
Function for generating a Dictionary from a dict.
:param a_dict: the dictionary to transform
:type a_dict: dict of (`a * `b)
:param int variant: variant level
:returns: a dbus dictionary of transformed values and level
:rtype: Dictionary * int
"""
elements = \
[(key_func(x), value_func(y)) for (x, y) in a_dict.items()]
level = 0 if elements == [] \
else max(max(x, y) for ((_, x), (_, y)) in elements)
(obj_level, func_level) = \
_ToDbusXformer._variant_levels(level, variant)
return (dbus.types.Dictionary(
((x, y) for ((x, _), (y, _)) in elements),
signature=signature,
variant_level=obj_level), func_level)
return (the_dict_func, 'a{' + signature + '}')
if len(toks) == 2:
(func, sig) = toks[1]
def the_array_func(a_list, variant=0):
"""
Function for generating an Array from a list.
:param a_list: the list to transform
:type a_list: list of `a
:param int variant: variant level of the value
:returns: a dbus Array of transformed values and variant level
:rtype: Array * int
"""
if isinstance(a_list, dict):
raise IntoDPValueError(a_list, "a_list",
"is a dict, must be an array")
elements = [func(x) for x in a_list]
level = 0 if elements == [] else max(x for (_, x) in elements)
(obj_level, func_level) = \
_ToDbusXformer._variant_levels(level, variant)
return (dbus.types.Array(
(x for (x, _) in elements),
signature=sig,
variant_level=obj_level), func_level)
return (the_array_func, 'a' + sig)
raise IntoDPValueError(toks, "toks",
"unexpected tokens") | python | {
"resource": ""
} |
q262548 | _ToDbusXformer._handle_struct | validation | def _handle_struct(toks):
"""
Generate the correct function for a struct signature.
:param toks: the list of parsed tokens
:returns: function that returns an Array or Dictionary value
:rtype: ((list or tuple) -> (Struct * int)) * str
"""
subtrees = toks[1:-1]
signature = ''.join(s for (_, s) in subtrees)
funcs = [f for (f, _) in subtrees]
def the_func(a_list, variant=0):
"""
Function for generating a Struct from a list.
:param a_list: the list to transform
:type a_list: list or tuple
:param int variant: variant index
:returns: a dbus Struct of transformed values and variant level
:rtype: Struct * int
:raises IntoDPValueError:
"""
if isinstance(a_list, dict):
raise IntoDPValueError(a_list, "a_list",
"must be a simple sequence, is a dict")
if len(a_list) != len(funcs):
raise IntoDPValueError(
a_list,
"a_list",
"must have exactly %u items, has %u" % \
(len(funcs), len(a_list))
)
elements = [f(x) for (f, x) in zip(funcs, a_list)]
level = 0 if elements == [] else max(x for (_, x) in elements)
(obj_level, func_level) = \
_ToDbusXformer._variant_levels(level, variant)
return (dbus.types.Struct(
(x for (x, _) in elements),
signature=signature,
variant_level=obj_level), func_level)
return (the_func, '(' + signature + ')') | python | {
"resource": ""
} |
q262549 | _ToDbusXformer._handle_base_case | validation | def _handle_base_case(klass, symbol):
"""
Handle a base case.
:param type klass: the class constructor
:param str symbol: the type code
"""
def the_func(value, variant=0):
"""
Base case.
:param int variant: variant level for this object
:returns: a tuple of a dbus object and the variant level
:rtype: dbus object * int
"""
(obj_level, func_level) = _ToDbusXformer._variant_levels(
0, variant)
return (klass(value, variant_level=obj_level), func_level)
return lambda: (the_func, symbol) | python | {
"resource": ""
} |
q262550 | signature | validation | def signature(dbus_object, unpack=False):
"""
Get the signature of a dbus object.
:param dbus_object: the object
:type dbus_object: a dbus object
:param bool unpack: if True, unpack from enclosing variant type
:returns: the corresponding signature
:rtype: str
"""
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-branches
if dbus_object.variant_level != 0 and not unpack:
return 'v'
if isinstance(dbus_object, dbus.Array):
sigs = frozenset(signature(x) for x in dbus_object)
len_sigs = len(sigs)
if len_sigs > 1: # pragma: no cover
raise IntoDPValueError(dbus_object, "dbus_object",
"has bad signature")
if len_sigs == 0:
return 'a' + dbus_object.signature
return 'a' + [x for x in sigs][0]
if isinstance(dbus_object, dbus.Struct):
sigs = (signature(x) for x in dbus_object)
return '(' + "".join(x for x in sigs) + ')'
if isinstance(dbus_object, dbus.Dictionary):
key_sigs = frozenset(signature(x) for x in dbus_object.keys())
value_sigs = frozenset(signature(x) for x in dbus_object.values())
len_key_sigs = len(key_sigs)
len_value_sigs = len(value_sigs)
if len_key_sigs != len_value_sigs: # pragma: no cover
raise IntoDPValueError(dbus_object, "dbus_object",
"has bad signature")
if len_key_sigs > 1: # pragma: no cover
raise IntoDPValueError(dbus_object, "dbus_object",
"has bad signature")
if len_key_sigs == 0:
return 'a{' + dbus_object.signature + '}'
return 'a{' + [x for x in key_sigs][0] + [x
for x in value_sigs][0] + '}'
if isinstance(dbus_object, dbus.Boolean):
return 'b'
if isinstance(dbus_object, dbus.Byte):
return 'y'
if isinstance(dbus_object, dbus.Double):
return 'd'
if isinstance(dbus_object, dbus.Int16):
return 'n'
if isinstance(dbus_object, dbus.Int32):
return 'i'
if isinstance(dbus_object, dbus.Int64):
return 'x'
if isinstance(dbus_object, dbus.ObjectPath):
return 'o'
if isinstance(dbus_object, dbus.Signature):
return 'g'
if isinstance(dbus_object, dbus.String):
return 's'
if isinstance(dbus_object, dbus.UInt16):
return 'q'
if isinstance(dbus_object, dbus.UInt32):
return 'u'
if isinstance(dbus_object, dbus.UInt64):
return 't'
if isinstance(dbus_object, dbus.types.UnixFd): # pragma: no cover
return 'h'
raise IntoDPValueError(dbus_object, "dbus_object",
"has no signature") | python | {
"resource": ""
} |
q262551 | lower | validation | def lower(option,value):
'''
Enforces lower case options and option values where appropriate
'''
if type(option) is str:
option=option.lower()
if type(value) is str:
value=value.lower()
return (option,value) | python | {
"resource": ""
} |
q262552 | to_float | validation | def to_float(option,value):
'''
Converts string values to floats when appropriate
'''
if type(value) is str:
try:
value=float(value)
except ValueError:
pass
return (option,value) | python | {
"resource": ""
} |
q262553 | to_bool | validation | def to_bool(option,value):
'''
Converts string values to booleans when appropriate
'''
if type(value) is str:
if value.lower() == 'true':
value=True
elif value.lower() == 'false':
value=False
return (option,value) | python | {
"resource": ""
} |
q262554 | Config.fork | validation | def fork(self,name):
'''
Create fork and store it in current instance
'''
fork=deepcopy(self)
self[name]=fork
return fork | python | {
"resource": ""
} |
q262555 | ld_to_dl | validation | def ld_to_dl(ld):
'''
Convert list of dictionaries to dictionary of lists
'''
if ld:
keys = list(ld[0])
dl = {key:[d[key] for d in ld] for key in keys}
return dl
else:
return {} | python | {
"resource": ""
} |
q262556 | split_list | validation | def split_list(l,N):
'''
Subdivide list into N lists
'''
npmode = isinstance(l,np.ndarray)
if npmode:
l=list(l)
g=np.concatenate((np.array([0]),np.cumsum(split_integer(len(l),length=N))))
s=[l[g[i]:g[i+1]] for i in range(N)]
if npmode:
s=[np.array(sl) for sl in s]
return s | python | {
"resource": ""
} |
q262557 | path_from_keywords | validation | def path_from_keywords(keywords,into='path'):
'''
turns keyword pairs into path or filename
if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy
'''
subdirs = []
def prepare_string(s):
s = str(s)
s = re.sub('[][{},*"'+f"'{os.sep}]",'_',s)#replace characters that make bash life difficult by underscore
if into=='file':
s = s.replace('_', ' ')#Remove underscore because they will be used as separator
if ' ' in s:
s = s.title()
s = s.replace(' ','')
return s
if isinstance(keywords,set):
keywords_list = sorted(keywords)
for property in keywords_list:
subdirs.append(prepare_string(property))
else:
keywords_list = sorted(keywords.items())
for property,value in keywords_list: # @reservedassignment
if Bool.valid(value):
subdirs.append(('' if value else ('not_' if into=='path' else 'not'))+prepare_string(property))
#elif String.valid(value):
# subdirs.append(prepare_string(value))
elif (Float|Integer).valid(value):
subdirs.append('{}{}'.format(prepare_string(property),prepare_string(value)))
else:
subdirs.append('{}{}{}'.format(prepare_string(property),'_' if into == 'path' else '',prepare_string(value)))
if into == 'path':
out = os.path.join(*subdirs)
else:
out = '_'.join(subdirs)
return out | python | {
"resource": ""
} |
q262558 | grid_evaluation | validation | def grid_evaluation(X, Y, f,vectorized=True):
'''
Evaluate function on given grid and return values in grid format
Assume X and Y are 2-dimensional arrays containing x and y coordinates,
respectively, of a two-dimensional grid, and f is a function that takes
1-d arrays with two entries. This function evaluates f on the grid points
described by X and Y and returns another 2-dimensional array of the shape
of X and Y that contains the values of f.
:param X: 2-dimensional array of x-coordinates
:param Y: 2-dimensional array of y-coordinates
:param f: function to be evaluated on grid
:param vectorized: `f` can handle arrays of inputs
:return: 2-dimensional array of values of f
'''
XX = np.reshape(np.concatenate([X[..., None], Y[..., None]], axis=2), (X.size, 2), order='C')
if vectorized:
ZZ = f(XX)
else:
ZZ = np.array([f(x) for x in XX])
return np.reshape(ZZ, X.shape, order='C') | python | {
"resource": ""
} |
q262559 | log_calls | validation | def log_calls(function):
'''
Decorator that logs function calls in their self.log
'''
def wrapper(self,*args,**kwargs):
self.log.log(group=function.__name__,message='Enter')
function(self,*args,**kwargs)
self.log.log(group=function.__name__,message='Exit')
return wrapper | python | {
"resource": ""
} |
q262560 | add_runtime | validation | def add_runtime(function):
'''
Decorator that adds a runtime profile object to the output
'''
def wrapper(*args,**kwargs):
pr=cProfile.Profile()
pr.enable()
output = function(*args,**kwargs)
pr.disable()
return pr,output
return wrapper | python | {
"resource": ""
} |
q262561 | print_memory | validation | def print_memory(function):
'''
Decorator that prints memory information at each call of the function
'''
import memory_profiler
def wrapper(*args,**kwargs):
m = StringIO()
temp_func = memory_profiler.profile(func = function,stream=m,precision=4)
output = temp_func(*args,**kwargs)
print(m.getvalue())
m.close()
return output
return wrapper | python | {
"resource": ""
} |
q262562 | print_profile | validation | def print_profile(function):
'''
Decorator that prints memory and runtime information at each call of the function
'''
import memory_profiler
def wrapper(*args,**kwargs):
m=StringIO()
pr=cProfile.Profile()
pr.enable()
temp_func = memory_profiler.profile(func=function,stream=m,precision=4)
output = temp_func(*args,**kwargs)
print(m.getvalue())
pr.disable()
ps = pstats.Stats(pr)
ps.sort_stats('cumulative').print_stats('(?!.*memory_profiler.*)(^.*$)',20)
m.close()
return output
return wrapper | python | {
"resource": ""
} |
q262563 | declaration | validation | def declaration(function):
'''
Declare abstract function.
Requires function to be empty except for docstring describing semantics.
To apply function, first argument must come with implementation of semantics.
'''
function,name=_strip_function(function)
if not function.__code__.co_code in [empty_function.__code__.co_code, doc_string_only_function.__code__.co_code]:
raise ValueError('Declaration requires empty function definition')
def not_implemented_function(*args,**kwargs):
raise ValueError('Argument \'{}\' did not specify how \'{}\' should act on it'.format(args[0],name))
not_implemented_function.__qualname__=not_implemented_function.__name__
return default(not_implemented_function,name=name) | python | {
"resource": ""
} |
q262564 | print_runtime | validation | def print_runtime(function):
'''
Decorator that prints running time information at each call of the function
'''
def wrapper(*args,**kwargs):
pr=cProfile.Profile()
pr.enable()
output = function(*args,**kwargs)
pr.disable()
ps = pstats.Stats(pr)
ps.sort_stats('tot').print_stats(20)
return output
return wrapper | python | {
"resource": ""
} |
q262565 | _validate_many | validation | def _validate_many(args, specs, defaults,passed_conditions,value_conditions,
allow_unknowns,unknowns_spec):
'''
Similar to validate but validates multiple objects at once, each with their own specification.
Fill objects that were specified but not provided with NotPassed or default values
Apply `value_condition` to object dictionary as a whole
'''
validated_args = builtins.dict()
passed_but_not_specified = set(args.keys()) - set(specs.keys())
if passed_but_not_specified:
if not allow_unknowns:
raise ValueError(('Arguments {} were passed but not specified (use ' +
'`allow_unknowns=True` to avoid this error)'.format(passed_but_not_specified)))
else:
for arg in passed_but_not_specified:
if unknowns_spec is not None:
specs[arg] = unknowns_spec
if passed_conditions:
validate(args, Dict(passed_conditions=passed_conditions))
for arg in specs:
if (not arg in args) or NotPassed(args[arg]):
if arg in defaults:
if isinstance(defaults[arg],DefaultGenerator):
validated_args[arg] = defaults[arg]()
else:
validated_args[arg] = defaults[arg]
else:
validated_args[arg] = NotPassed
else:#Default values and NotPassed values are not validated. Former has advantage that default values need to be `correct` without validation and thus encourage the user to pass stuff that doesn't need validation, and is therefore faster
validated_args[arg] = validate(args[arg], specs[arg])
if value_conditions:
validated_args = validate(validated_args, value_conditions)
return validated_args | python | {
"resource": ""
} |
q262566 | ModelMixin.get_default_fields | validation | def get_default_fields(self):
"""
get all fields of model, execpt id
"""
field_names = self._meta.get_all_field_names()
if 'id' in field_names:
field_names.remove('id')
return field_names | python | {
"resource": ""
} |
q262567 | DownloaderBase.fetch | validation | def fetch(self, url, path, filename):
"""Verify if the file is already downloaded and complete. If they don't
exists or if are not complete, use homura download function to fetch
files. Return a list with the path of the downloaded file and the size
of the remote file.
"""
logger.debug('initializing download in ', url)
remote_file_size = self.get_remote_file_size(url)
if exists(join(path, filename)):
size = getsize(join(path, filename))
if size == remote_file_size:
logger.error('%s already exists on your system' % filename)
print('%s already exists on your system' % filename)
return [join(path, filename), size]
logger.debug('Downloading: %s' % filename)
print('Downloading: %s' % filename)
fetch(url, path)
print('stored at %s' % path)
logger.debug('stored at %s' % path)
return [join(path, filename), remote_file_size] | python | {
"resource": ""
} |
q262568 | DownloaderBase.validate_bands | validation | def validate_bands(self, bands):
"""Validate bands parameter."""
if not isinstance(bands, list):
logger.error('Parameter bands must be a "list"')
raise TypeError('Parameter bands must be a "list"')
valid_bands = list(range(1, 12)) + ['BQA']
for band in bands:
if band not in valid_bands:
logger.error('%s is not a valid band' % band)
raise InvalidBandError('%s is not a valid band' % band) | python | {
"resource": ""
} |
q262569 | GoogleDownloader.validate_sceneInfo | validation | def validate_sceneInfo(self):
"""Check scene name and whether remote file exists. Raises
WrongSceneNameError if the scene name is wrong.
"""
if self.sceneInfo.prefix not in self.__satellitesMap:
logger.error('Google Downloader: Prefix of %s (%s) is invalid'
% (self.sceneInfo.name, self.sceneInfo.prefix))
raise WrongSceneNameError('Google Downloader: Prefix of %s (%s) is invalid'
% (self.sceneInfo.name, self.sceneInfo.prefix)) | python | {
"resource": ""
} |
q262570 | GoogleDownloader.download | validation | def download(self, bands, download_dir=None, metadata=False):
"""Download remote .tar.bz file."""
super(GoogleDownloader, self).validate_bands(bands)
pattern = re.compile('^[^\s]+_(.+)\.tiff?', re.I)
image_list = []
band_list = ['B%i' % (i,) if isinstance(i, int) else i for i in bands]
if download_dir is None:
download_dir = DOWNLOAD_DIR
check_create_folder(join(download_dir, self.sceneInfo.name))
filename = "%s%s" % (self.sceneInfo.name, self.__remote_file_ext)
downloaded = self.fetch(self.remote_file_url, download_dir, filename)
try:
tar = tarfile.open(downloaded[0], 'r')
folder_path = join(download_dir, self.sceneInfo.name)
logger.debug('Starting data extraction in directory ', folder_path)
tar.extractall(folder_path)
remove(downloaded[0])
images_path = listdir(folder_path)
for image_path in images_path:
matched = pattern.match(image_path)
file_path = join(folder_path, image_path)
if matched and matched.group(1) in band_list:
image_list.append([file_path, getsize(file_path)])
elif matched:
remove(file_path)
except tarfile.ReadError as error:
logger.error('Error when extracting files: ', error)
print('Error when extracting files.')
return image_list | python | {
"resource": ""
} |
q262571 | AWSDownloader.validate_sceneInfo | validation | def validate_sceneInfo(self):
"""Check whether sceneInfo is valid to download from AWS Storage."""
if self.sceneInfo.prefix not in self.__prefixesValid:
raise WrongSceneNameError('AWS: Prefix of %s (%s) is invalid'
% (self.sceneInfo.name, self.sceneInfo.prefix)) | python | {
"resource": ""
} |
q262572 | AWSDownloader.download | validation | def download(self, bands, download_dir=None, metadata=False):
"""Download each specified band and metadata."""
super(AWSDownloader, self).validate_bands(bands)
if download_dir is None:
download_dir = DOWNLOAD_DIR
dest_dir = check_create_folder(join(download_dir, self.sceneInfo.name))
downloaded = []
for band in bands:
if band == 'BQA':
filename = '%s_%s.%s' % (self.sceneInfo.name, band, self.__remote_file_ext)
else:
filename = '%s_B%s.%s' % (self.sceneInfo.name, band, self.__remote_file_ext)
band_url = join(self.base_url, filename)
downloaded.append(self.fetch(band_url, dest_dir, filename))
if metadata:
filename = '%s_MTL.txt' % (self.sceneInfo.name)
url = join(self.base_url, filename)
self.fetch(url, dest_dir, filename)
return downloaded | python | {
"resource": ""
} |
q262573 | open_archive | validation | def open_archive(fs_url, archive):
"""Open an archive on a filesystem.
This function tries to mimick the behaviour of `fs.open_fs` as closely
as possible: it accepts either a FS URL or a filesystem instance, and
will close all resources it had to open.
Arguments:
fs_url (FS or text_type): a FS URL, or a filesystem
instance, where the archive file is located.
archive (text_type): the path to the archive file on the
given filesystem.
Raises:
`fs.opener._errors.Unsupported`: when the archive type is not supported
(either the file extension is unknown or the opener requires unmet
dependencies).
Example:
>>> from fs.archive import open_archive
>>> with open_archive('mem://', 'test.tar.gz') as archive_fs:
... type(archive_fs)
<class 'fs.archive.tarfs.TarFS'>
Hint:
This function finds the entry points defined in group
``fs.archive.open_archive``, using the names of the entry point
as the registered extension.
"""
it = pkg_resources.iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise UnsupportedProtocol(
'unknown archive extension: {}'.format(archive))
try:
archive_opener = entry_point.load()
except pkg_resources.DistributionNotFound as df: # pragma: no cover
six.raise_from(UnsupportedProtocol(
'extension {} requires {}'.format(entry_point.name, df.req)), None)
try:
binfile = None
archive_fs = None
fs = open_fs(fs_url)
if issubclass(archive_opener, base.ArchiveFS):
try:
binfile = fs.openbin(archive, 'r+')
except errors.ResourceNotFound:
binfile = fs.openbin(archive, 'w')
except errors.ResourceReadOnly:
binfile = fs.openbin(archive, 'r')
archive_opener = archive_opener._read_fs_cls
elif issubclass(archive_opener, base.ArchiveReadFS):
binfile = fs.openbin(archive, 'r')
if not hasattr(binfile, 'name'):
binfile.name = basename(archive)
archive_fs = archive_opener(binfile)
except Exception:
getattr(archive_fs, 'close', lambda: None)()
getattr(binfile, 'close', lambda: None)()
raise
else:
return archive_fs | python | {
"resource": ""
} |
q262574 | iso_name_slugify | validation | def iso_name_slugify(name):
"""Slugify a name in the ISO-9660 way.
Example:
>>> slugify('épatant')
"_patant"
"""
name = name.encode('ascii', 'replace').replace(b'?', b'_')
return name.decode('ascii') | python | {
"resource": ""
} |
q262575 | iso_name_increment | validation | def iso_name_increment(name, is_dir=False, max_length=8):
"""Increment an ISO name to avoid name collision.
Example:
>>> iso_name_increment('foo.txt')
'foo1.txt'
>>> iso_name_increment('bar10')
'bar11'
>>> iso_name_increment('bar99', max_length=5)
'ba100'
"""
# Split the extension if needed
if not is_dir and '.' in name:
name, ext = name.rsplit('.')
ext = '.{}'.format(ext)
else:
ext = ''
# Find the position of the last letter
for position, char in reversed(list(enumerate(name))):
if char not in string.digits:
break
# Extract the numbers and the text from the name
base, tag = name[:position+1], name[position+1:]
tag = str(int(tag or 0) + 1)
# Crop the text if the numbers are too long
if len(tag) + len(base) > max_length:
base = base[:max_length - len(tag)]
# Return the name with the extension
return ''.join([base, tag, ext]) | python | {
"resource": ""
} |
q262576 | iso_path_slugify | validation | def iso_path_slugify(path, path_table, is_dir=False, strict=True):
"""Slugify a path, maintaining a map with the previously slugified paths.
The path table is used to prevent slugified names from collisioning,
using the `iso_name_increment` function to deduplicate slugs.
Example:
>>> path_table = {'/': '/'}
>>> iso_path_slugify('/ébc.txt', path_table)
'/_BC.TXT'
>>> iso_path_slugify('/àbc.txt', path_table)
'/_BC2.TXT'
"""
# Split the path to extract the parent and basename
parent, base = split(path)
# Get the parent in slugified form
slug_parent = path_table[parent]
# Slugify the base name
if is_dir:
slug_base = iso_name_slugify(base)[:8]
else:
name, ext = base.rsplit('.', 1) if '.' in base else (base, '')
slug_base = '.'.join([iso_name_slugify(name)[:8], ext])
if strict:
slug_base = slug_base.upper()
# Deduplicate slug if needed and update path_table
slugs = set(path_table.values())
path_table[path] = slug = join(slug_parent, slug_base)
while slug in slugs:
slug_base = iso_name_increment(slug_base, is_dir)
path_table[path] = slug = join(slug_parent, slug_base)
# Return the unique slug
return slug | python | {
"resource": ""
} |
q262577 | writable_path | validation | def writable_path(path):
"""Test whether a path can be written to.
"""
if os.path.exists(path):
return os.access(path, os.W_OK)
try:
with open(path, 'w'):
pass
except (OSError, IOError):
return False
else:
os.remove(path)
return True | python | {
"resource": ""
} |
q262578 | writable_stream | validation | def writable_stream(handle):
"""Test whether a stream can be written to.
"""
if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):
return handle.writable()
try:
handle.write(b'')
except (io.UnsupportedOperation, IOError):
return False
else:
return True | python | {
"resource": ""
} |
q262579 | QuadContourGenerator.from_curvilinear | validation | def from_curvilinear(cls, x, y, z, formatter=numpy_formatter):
"""Construct a contour generator from a curvilinear grid.
Note
----
This is an alias for the default constructor.
Parameters
----------
x : array_like
x coordinates of each point in `z`. Must be the same size as `z`.
y : array_like
y coordinates of each point in `z`. Must be the same size as `z`.
z : array_like
The 2-dimensional curvilinear grid of data to compute
contours for. Masked arrays are supported.
formatter : callable
A conversion function to convert from the internal `Matplotlib`_
contour format to an external format. See :ref:`formatters` for
more information.
Returns
-------
: :class:`QuadContourGenerator`
Initialized contour generator.
"""
return cls(x, y, z, formatter) | python | {
"resource": ""
} |
q262580 | QuadContourGenerator.from_rectilinear | validation | def from_rectilinear(cls, x, y, z, formatter=numpy_formatter):
"""Construct a contour generator from a rectilinear grid.
Parameters
----------
x : array_like
x coordinates of each column of `z`. Must be the same length as
the number of columns in `z`. (len(x) == z.shape[1])
y : array_like
y coordinates of each row of `z`. Must be the same length as the
number of columns in `z`. (len(y) == z.shape[0])
z : array_like
The 2-dimensional rectilinear grid of data to compute contours for.
Masked arrays are supported.
formatter : callable
A conversion function to convert from the internal `Matplotlib`_
contour format to an external format. See :ref:`formatters` for
more information.
Returns
-------
: :class:`QuadContourGenerator`
Initialized contour generator.
"""
x = np.asarray(x, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
z = np.ma.asarray(z, dtype=np.float64)
# Check arguments.
if x.ndim != 1:
raise TypeError(
"'x' must be a 1D array but is a {:d}D array".format(x.ndim))
if y.ndim != 1:
raise TypeError(
"'y' must be a 1D array but is a {:d}D array".format(y.ndim))
if z.ndim != 2:
raise TypeError(
"'z' must be a 2D array but it a {:d}D array".format(z.ndim))
if x.size != z.shape[1]:
raise TypeError(
("the length of 'x' must be equal to the number of columns in "
"'z' but the length of 'x' is {:d} and 'z' has {:d} "
"columns").format(x.size, z.shape[1]))
if y.size != z.shape[0]:
raise TypeError(
("the length of 'y' must be equal to the number of rows in "
"'z' but the length of 'y' is {:d} and 'z' has {:d} "
"rows").format(y.size, z.shape[0]))
# Convert to curvilinear format and call constructor.
y, x = np.meshgrid(y, x, indexing='ij')
return cls(x, y, z, formatter) | python | {
"resource": ""
} |
q262581 | QuadContourGenerator.from_uniform | validation | def from_uniform(
cls, z, origin=(0, 0), step=(1, 1), formatter=numpy_formatter):
"""Construct a contour generator from a uniform grid.
NOTE
----
The default `origin` and `step` values is equivalent to calling
:meth:`matplotlib.axes.Axes.contour` with only the `z` argument.
Parameters
----------
z : array_like
The 2-dimensional uniform grid of data to compute contours for.
Masked arrays are supported.
origin : (number.Number, number.Number)
The (x, y) coordinate of data point `z[0,0]`.
step : (number.Number, number.Number)
The (x, y) distance between data points in `z`.
formatter : callable
A conversion function to convert from the internal `Matplotlib`_
contour format to an external format. See :ref:`formatters` for
more information.
Returns
-------
: :class:`QuadContourGenerator`
Initialized contour generator.
"""
z = np.ma.asarray(z, dtype=np.float64)
# Check arguments.
if z.ndim != 2:
raise TypeError(
"'z' must be a 2D array but it a {:d}D array".format(z.ndim))
if len(origin) != 2:
raise TypeError(
"'origin' must be of length 2 but has length {:d}".format(
len(origin)))
if len(step) != 2:
raise TypeError(
"'step' must be of length 2 but has length {:d}".format(
len(step)))
if any(s == 0 for s in step):
raise ValueError(
"'step' must have non-zero values but is {:s}".format(
str(step)))
# Convert to curvilinear format and call constructor.
y, x = np.mgrid[
origin[0]:(origin[0]+step[0]*z.shape[0]):step[0],
origin[1]:(origin[1]+step[1]*z.shape[1]):step[1]]
return cls(x, y, z, formatter) | python | {
"resource": ""
} |
q262582 | SphinxSearchPlugin._wait_for_connection | validation | def _wait_for_connection(self, port):
"""
Wait until we can make a socket connection to sphinx.
"""
connected = False
max_tries = 10
num_tries = 0
wait_time = 0.5
while not connected or num_tries >= max_tries:
time.sleep(wait_time)
try:
af = socket.AF_INET
addr = ('127.0.0.1', port)
sock = socket.socket(af, socket.SOCK_STREAM)
sock.connect(addr)
except socket.error:
if sock:
sock.close()
num_tries += 1
continue
connected = True
if not connected:
print("Error connecting to sphinx searchd", file=sys.stderr) | python | {
"resource": ""
} |
q262583 | Plugin.get_unique_token | validation | def get_unique_token(self):
"""
Get a unique token for usage in differentiating test runs that need to
run in parallel.
"""
if self._unique_token is None:
self._unique_token = self._random_token()
return self._unique_token | python | {
"resource": ""
} |
q262584 | Plugin._random_token | validation | def _random_token(self, bits=128):
"""
Generates a random token, using the url-safe base64 alphabet.
The "bits" argument specifies the bits of randomness to use.
"""
alphabet = string.ascii_letters + string.digits + '-_'
# alphabet length is 64, so each letter provides lg(64) = 6 bits
num_letters = int(math.ceil(bits / 6.0))
return ''.join(random.choice(alphabet) for i in range(num_letters)) | python | {
"resource": ""
} |
q262585 | Poll.url | validation | def url(self):
"""Returns the url of the poll. If the poll has not been submitted yet,
an empty string is returned instead.
"""
if self.id is None:
return ''
return '{}/{}'.format(strawpoll.API._BASE_URL, self.id) | python | {
"resource": ""
} |
q262586 | API.get_poll | validation | def get_poll(self, arg, *, request_policy=None):
"""Retrieves a poll from strawpoll.
:param arg: Either the ID of the poll or its strawpoll url.
:param request_policy: Overrides :attr:`API.requests_policy` for that \
request.
:type request_policy: Optional[:class:`RequestsPolicy`]
:raises HTTPException: Requesting the poll failed.
:returns: A poll constructed with the requested data.
:rtype: :class:`Poll`
"""
if isinstance(arg, str):
# Maybe we received an url to parse
match = self._url_re.match(arg)
if match:
arg = match.group('id')
return self._http_client.get('{}/{}'.format(self._POLLS, arg),
request_policy=request_policy,
cls=strawpoll.Poll) | python | {
"resource": ""
} |
q262587 | API.submit_poll | validation | def submit_poll(self, poll, *, request_policy=None):
"""Submits a poll on strawpoll.
:param poll: The poll to submit.
:type poll: :class:`Poll`
:param request_policy: Overrides :attr:`API.requests_policy` for that \
request.
:type request_policy: Optional[:class:`RequestsPolicy`]
:raises ExistingPoll: This poll instance has already been submitted.
:raises HTTPException: The submission failed.
:returns: The given poll updated with the data sent back from the submission.
:rtype: :class:`Poll`
.. note::
Only polls that have a non empty title and between 2 and 30 options
can be submitted.
"""
if poll.id is not None:
raise ExistingPoll()
options = poll.options
data = {
'title': poll.title,
'options': options,
'multi': poll.multi,
'dupcheck': poll.dupcheck,
'captcha': poll.captcha
}
return self._http_client.post(self._POLLS,
data=data,
request_policy=request_policy,
cls=strawpoll.Poll) | python | {
"resource": ""
} |
q262588 | numpy_formatter | validation | def numpy_formatter(_, vertices, codes=None):
"""`NumPy`_ style contour formatter.
Contours are returned as a list of Nx2 arrays containing the x and y
vertices of the contour line.
For filled contours the direction of vertices matters:
* CCW (ACW): The vertices give the exterior of a contour polygon.
* CW: The vertices give a hole of a contour polygon. This hole will
always be inside the exterior of the last contour exterior.
.. note:: This is the fastest format.
.. _NumPy: http://www.numpy.org
"""
if codes is None:
return vertices
numpy_vertices = []
for vertices_, codes_ in zip(vertices, codes):
starts = np.nonzero(codes_ == MPLPATHCODE.MOVETO)[0]
stops = np.nonzero(codes_ == MPLPATHCODE.CLOSEPOLY)[0]
for start, stop in zip(starts, stops):
numpy_vertices.append(vertices_[start:stop+1, :])
return numpy_vertices | python | {
"resource": ""
} |
q262589 | matlab_formatter | validation | def matlab_formatter(level, vertices, codes=None):
"""`MATLAB`_ style contour formatter.
Contours are returned as a single Nx2, `MATLAB`_ style, contour array.
There are two types of rows in this format:
* Header: The first element of a header row is the level of the contour
(the lower level for filled contours) and the second element is the
number of vertices (to follow) belonging to this contour line.
* Vertex: x,y coordinate pairs of the vertex.
A header row is always followed by the coresponding number of vertices.
Another header row may follow if there are more contour lines.
For filled contours the direction of vertices matters:
* CCW (ACW): The vertices give the exterior of a contour polygon.
* CW: The vertices give a hole of a contour polygon. This hole will
always be inside the exterior of the last contour exterior.
For further explanation of this format see the `Mathworks documentation
<https://www.mathworks.com/help/matlab/ref/contour-properties.html#prop_ContourMatrix>`_
noting that the MATLAB format used in the `contours` package is the
transpose of that used by `MATLAB`_ (since `MATLAB`_ is column-major
and `NumPy`_ is row-major by default).
.. _NumPy: http://www.numpy.org
.. _MATLAB: https://www.mathworks.com/products/matlab.html
"""
vertices = numpy_formatter(level, vertices, codes)
if codes is not None:
level = level[0]
headers = np.vstack((
[v.shape[0] for v in vertices],
[level]*len(vertices))).T
vertices = np.vstack(
list(it.__next__() for it in
itertools.cycle((iter(headers), iter(vertices)))))
return vertices | python | {
"resource": ""
} |
q262590 | shapely_formatter | validation | def shapely_formatter(_, vertices, codes=None):
"""`Shapely`_ style contour formatter.
Contours are returned as a list of :class:`shapely.geometry.LineString`,
:class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`
geometry elements.
Filled contours return a list of :class:`shapely.geometry.Polygon`
elements instead.
.. note:: If possible, `Shapely speedups`_ will be enabled.
.. _Shapely: http://toblerity.org/shapely/manual.html
.. _Shapely speedups: http://toblerity.org/shapely/manual.html#performance
See Also
--------
`descartes <https://bitbucket.org/sgillies/descartes/>`_ : Use `Shapely`_
or GeoJSON-like geometric objects as matplotlib paths and patches.
"""
elements = []
if codes is None:
for vertices_ in vertices:
if np.all(vertices_[0, :] == vertices_[-1, :]):
# Contour is single point.
if len(vertices) < 3:
elements.append(Point(vertices_[0, :]))
# Contour is closed.
else:
elements.append(LinearRing(vertices_))
# Contour is open.
else:
elements.append(LineString(vertices_))
else:
for vertices_, codes_ in zip(vertices, codes):
starts = np.nonzero(codes_ == MPLPATHCODE.MOVETO)[0]
stops = np.nonzero(codes_ == MPLPATHCODE.CLOSEPOLY)[0]
try:
rings = [LinearRing(vertices_[start:stop+1, :])
for start, stop in zip(starts, stops)]
elements.append(Polygon(rings[0], rings[1:]))
except ValueError as err:
# Verify error is from degenerate (single point) polygon.
if np.any(stop - start - 1 == 0):
# Polygon is single point, remove the polygon.
if stops[0] < starts[0]+2:
pass
# Polygon has single point hole, remove the hole.
else:
rings = [
LinearRing(vertices_[start:stop+1, :])
for start, stop in zip(starts, stops)
if stop >= start+2]
elements.append(Polygon(rings[0], rings[1:]))
else:
raise(err)
return elements | python | {
"resource": ""
} |
q262591 | ContourMixin.contour | validation | def contour(self, level):
"""Get contour lines at the given level.
Parameters
----------
level : numbers.Number
The data level to calculate the contour lines for.
Returns
-------
:
The result of the :attr:`formatter` called on the contour at the
given `level`.
"""
if not isinstance(level, numbers.Number):
raise TypeError(
("'_level' must be of type 'numbers.Number' but is "
"'{:s}'").format(type(level)))
vertices = self._contour_generator.create_contour(level)
return self.formatter(level, vertices) | python | {
"resource": ""
} |
q262592 | ContourMixin.filled_contour | validation | def filled_contour(self, min=None, max=None):
"""Get contour polygons between the given levels.
Parameters
----------
min : numbers.Number or None
The minimum data level of the contour polygon. If :obj:`None`,
``numpy.finfo(numpy.float64).min`` will be used.
max : numbers.Number or None
The maximum data level of the contour polygon. If :obj:`None`,
``numpy.finfo(numpy.float64).max`` will be used.
Returns
-------
:
The result of the :attr:`formatter` called on the filled contour
between `min` and `max`.
"""
# pylint: disable=redefined-builtin,redefined-outer-name
# Get the contour vertices.
if min is None:
min = np.finfo(np.float64).min
if max is None:
max = np.finfo(np.float64).max
vertices, codes = (
self._contour_generator.create_filled_contour(min, max))
return self.formatter((min, max), vertices, codes) | python | {
"resource": ""
} |
q262593 | Axis.add_node | validation | def add_node(self, node, offset):
"""Add a Node object to nodes dictionary, calculating its coordinates using offset
Parameters
----------
node : a Node object
offset : float
number between 0 and 1 that sets the distance
from the start point at which the node will be placed
"""
# calculate x,y from offset considering axis start and end points
width = self.end[0] - self.start[0]
height = self.end[1] - self.start[1]
node.x = self.start[0] + (width * offset)
node.y = self.start[1] + (height * offset)
self.nodes[node.ID] = node | python | {
"resource": ""
} |
q262594 | get_settings_path | validation | def get_settings_path(settings_module):
'''
Hunt down the settings.py module by going up the FS path
'''
cwd = os.getcwd()
settings_filename = '%s.py' % (
settings_module.split('.')[-1]
)
while cwd:
if settings_filename in os.listdir(cwd):
break
cwd = os.path.split(cwd)[0]
if os.name == 'nt' and NT_ROOT.match(cwd):
return None
elif cwd == '/':
return None
return cwd | python | {
"resource": ""
} |
q262595 | NoseDjango._should_use_transaction_isolation | validation | def _should_use_transaction_isolation(self, test, settings):
"""
Determine if the given test supports transaction management for
database rollback test isolation and also whether or not the test has
opted out of that support.
Transactions make database rollback much quicker when supported, with
the caveat that any tests that are explicitly testing transactions
won't work properly and any tests that depend on external access to the
test database won't be able to view data created/altered during the
test.
"""
if not getattr(test.context, 'use_transaction_isolation', True):
# The test explicitly says not to use transaction isolation
return False
if getattr(settings, 'DISABLE_TRANSACTION_MANAGEMENT', False):
# Do not use transactions if user has forbidden usage.
return False
if hasattr(settings, 'DATABASE_SUPPORTS_TRANSACTIONS'):
if not settings.DATABASE_SUPPORTS_TRANSACTIONS:
# The DB doesn't support transactions. Don't try it
return False
return True | python | {
"resource": ""
} |
q262596 | NoseDjango.finalize | validation | def finalize(self, result=None):
"""
Clean up any created database and schema.
"""
if not self.settings_path:
# short circuit if no settings file can be found
return
from django.test.utils import teardown_test_environment
from django.db import connection
from django.conf import settings
self.call_plugins_method('beforeDestroyTestDb', settings, connection)
try:
connection.creation.destroy_test_db(
self.old_db,
verbosity=self.verbosity,
)
except Exception:
# If we can't tear down the test DB, don't worry about it.
pass
self.call_plugins_method('afterDestroyTestDb', settings, connection)
self.call_plugins_method(
'beforeTeardownTestEnv', settings, teardown_test_environment)
teardown_test_environment()
self.call_plugins_method('afterTeardownTestEnv', settings) | python | {
"resource": ""
} |
q262597 | make_clean_figure | validation | def make_clean_figure(figsize, remove_tooltips=False, remove_keybindings=False):
"""
Makes a `matplotlib.pyplot.Figure` without tooltips or keybindings
Parameters
----------
figsize : tuple
Figsize as passed to `matplotlib.pyplot.figure`
remove_tooltips, remove_keybindings : bool
Set to True to remove the tooltips bar or any key bindings,
respectively. Default is False
Returns
-------
fig : `matplotlib.pyplot.Figure`
"""
tooltip = mpl.rcParams['toolbar']
if remove_tooltips:
mpl.rcParams['toolbar'] = 'None'
fig = pl.figure(figsize=figsize)
mpl.rcParams['toolbar'] = tooltip
if remove_keybindings:
fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)
return fig | python | {
"resource": ""
} |
q262598 | OrthoPrefeature.update_field | validation | def update_field(self, poses=None):
"""updates self.field"""
m = np.clip(self.particle_field, 0, 1)
part_color = np.zeros(self._image.shape)
for a in range(4): part_color[:,:,:,a] = self.part_col[a]
self.field = np.zeros(self._image.shape)
for a in range(4):
self.field[:,:,:,a] = m*part_color[:,:,:,a] + (1-m) * self._image[:,:,:,a] | python | {
"resource": ""
} |
q262599 | OrthoPrefeature._remove_closest_particle | validation | def _remove_closest_particle(self, p):
"""removes the closest particle in self.pos to ``p``"""
#1. find closest pos:
dp = self.pos - p
dist2 = (dp*dp).sum(axis=1)
ind = dist2.argmin()
rp = self.pos[ind].copy()
#2. delete
self.pos = np.delete(self.pos, ind, axis=0)
return rp | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.