output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Return the soundex code for given character | Can you tell what is the following Python 3 function doing
def soundexCode(self, char):
'''Return the soundex code for given character
:param char:
Character whose soundex code is needed
:return:
Returns soundex code if character is found in charmap
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def soundex(self, name, length=8):
'''Calculate soundex of given string
This function calculates soundex for Indian language string
as well as English string.
This function is exposed as service method for JSONRPC in
SILPA framework.
:param name: String ... | Implement a function in Python 3 to
calculate soundex of given string. | You are a Python code architect, reviewing and designing scalable and efficient code |
def compare(self, string1, string2):
'''Compare soundex of given strings
This function checks if 2 given strings are phonetically
sounds same by doing soundex code comparison
:param string1: First string for comparison
:param string2: Second string for comparison
... | Create a Python 3 function for
comparing two strings in the soundex of the same language and return the number of matches | As a Python code composer, you craft elegant and concise scripts. |
def get_response_for_url(self, url):
"""
Accepts a fully-qualified url.
Returns an HttpResponse, passing through all headers and the status code.
"""
if not url or "//" not in url:
raise ValueError("Missing or invalid url: %s" % url)
render_url = self.BASE_U... | Write a Python 3 script to
return a HttpResponse object that is passed through all headers and the status code of the request. | You are a Python code architect, reviewing and designing scalable and efficient code |
Updates the url of a specific entry in the cache. | How would you explain what the following Python 3 function does
def update_url(self, url=None, regex=None):
if not url and not regex:
raise ValueError("Neither a url or regex was provided to update_url.")
headers = {
'X-Prerender-Token': self.token,
'Content-Type': ... | As a python code expert, you are capable of creating scripts from specifications. |
Updates the url of the current user s log entry. | How would you explain what the following Python 3 function does
def update_url(self, url=None):
if not url:
raise ValueError("Neither a url or regex was provided to update_url.")
post_url = "%s%s" % (self.BASE_URL, url)
r = self.session.post(post_url)
return int(r.status_code... | You are a Python code generator, capable of creating scripts from specifications. |
Override create to provide a user via request. user by default. | Explain what the following Python 3 code does
def create(self, validated_data):
if 'user' not in validated_data:
validated_data['user'] = self.context['request'].user
return super(RefreshTokenSerializer, self).create(validated_data) | As a Python code analyst, you investigate and solve complex coding mysteries |
def has_object_permission(self, request, view, obj):
"""
Allow staff or superusers, and the owner of the object itself.
"""
user = request.user
if not user.is_authenticated:
return False
elif user.is_staff or user.is_superuser:
return True
... | Write a Python 3 script to
return True if the user has permission to view the object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Release the semaphore of all of its bounds setting the internal
counter back to its original bind limit. | Make a summary of the following Python 3 code
def clear(self):
with self._cond:
to_notify = self._initial - self._value
self._value = self._initial
self._cond.notify(to_notify) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _public(self, command, **params):
"""Invoke the 'command' public API with optional params."""
params['command'] = command
response = self.session.get(self._public_url, params=params)
return response | Implement a function in Python 3 to
invoke the command public API with optional params. | You are a Python code analyst, evaluating scripts for potential improvements. |
def returnOrderBook(self, currencyPair='all', depth='50'):
"""Returns the order book for a given market, as well as a sequence
number for use with the Push API and an indicator specifying whether
the market is frozen. You may set currencyPair to "all" to get the
order books of all market... | Write a Python 3 function that can
return the order book for a given market. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the past 200 trades for a given market or up to 50 000
trades between a range specified in UNIX timestamps by the start and end GET parameters. | Here you have a function in Python 3, explain what it does
def returnTradeHistory(self, currencyPair, start=None, end=None):
return self._public('returnTradeHistory', currencyPair=currencyPair,
start=start, end=end) | You are a Python code generator, capable of creating scripts from specifications. |
def returnChartData(self, currencyPair, period, start=0, end=2**32-1):
"""Returns candlestick chart data. Required GET parameters are
"currencyPair", "period" (candlestick period in seconds; valid values
are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end".
"Start" and "end" a... | Create a Python 3 function for
returning candlestick chart data. Required GET parameters are currencyPair period start and end. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Invoke the command public API with optional params. | Make a summary of the following Python 3 code
def _private(self, command, **params):
if not self._apikey or not self._secret:
raise PoloniexCredentialsException('missing apikey/secret')
with self.nonce_lock:
params.update({'command': command, 'nonce': next(self.nonce_iter)})
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def returnDepositsWithdrawals(self, start=0, end=2**32-1):
"""Returns your deposit and withdrawal history within a range,
specified by the "start" and "end" POST parameters, both of which
should be given as UNIX timestamps."""
return self._private('returnDepositsWithdrawals', start=start... | Implement a function in Python 3 to
return your deposits and withdrawal history within a range | As a python code expert, you are capable of creating scripts from specifications. |
Returns your trade history for a given market | Make a summary of the following Python 3 code
def returnTradeHistory(self, currencyPair='all', start=None, end=None, limit=500):
return self._private('returnTradeHistory', currencyPair=currencyPair,
start=start, end=end, limit=limit) | As a Python code composer, you craft elegant and concise scripts. |
def returnTradeHistoryPublic(self, currencyPair, start=None, end=None):
"""Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters."""
return super(Poloniex, self).returnTradeHistory(curre... | Implement a function in Python 3 to
return the public trades for a given market or up to 50 000 000 | As a Python code translator, you convert algorithms and pseudocode into Python. |
def buy(self, currencyPair, rate, amount, fillOrKill=None,
immediateOrCancel=None, postOnly=None):
"""Places a limit buy order in a given market. Required POST parameters
are "currencyPair", "rate", and "amount". If successful, the method
will return the order number.
You may... | Implement a Python 3 function for
placing a limit buy order in a given market. Required POST parameters are currencyPair rate and amount. Required POST parameters are fillOrKill immediateOrCancel and postOnly. | As a Python code analyst, you investigate and solve complex coding mysteries |
def moveOrder(self, orderNumber, rate, amount=None, postOnly=None,
immediateOrCancel=None):
"""Cancels an order and places a new one of the same type in a single
atomic transaction, meaning either both operations will succeed or both
will fail. Required POST parameters are "or... | Write a Python 3 function that can
cancel an order and places a new one of the same type in a single atomic transaction meaning either both operations will succeed or both operations will fail. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def marginBuy(self, currencyPair, rate, amount, lendingRate=None):
"""Places a margin buy order in a given market. Required POST
parameters are "currencyPair", "rate", and "amount". You may optionally
specify a maximum lending rate using the "lendingRate" parameter.
If successful, the ... | How would you code a function in Python 3 to
place a margin buy order in a given market. | You are a Python code generator, capable of creating scripts from specifications. |
Places a margin sell order in a given market. Parameters and output
are the same as for the marginBuy method. | Here you have a function in Python 3, explain what it does
def marginSell(self, currencyPair, rate, amount, lendingRate=None):
return self._private('marginSell', currencyPair=currencyPair, rate=rate,
amount=amount, lendingRate=lendingRate) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a loan offer for a given currency. Required POST parameters
amount duration autoRenew and lendingRate. | Can you generate a brief explanation for the following Python 3 code
def createLoanOffer(self, currency, amount, duration, autoRenew,
lendingRate):
"""Creates a loan offer for a given currency. Required POST parameters
are "currency", "amount", "duration", "autoRenew" (0 or 1), a... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns your lending history within a time range specified by the
start and end POST parameters as UNIX timestamps. | Given the following Python 3 function, write the documentation
def returnLendingHistory(self, start=0, end=2**32-1, limit=None):
return self._private('returnLendingHistory', start=start, end=end,
limit=limit) | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_cid():
"""Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)`
We want the simplest thin... | Create a Python 3 function for
returning the currently set correlation id. | You are a Python code generator, capable of creating scripts from specifications. |
def generate_new_cid(upstream_cid=None):
"""Generate a new correlation id, possibly based on the given one."""
if upstream_cid is None:
return str(uuid.uuid4()) if getattr(settings, 'CID_GENERATE', False) else None
if (
getattr(settings, 'CID_CONCATENATE_IDS', False)
and geta... | Create a Python 3 function for
generating a new correlation id possibly based on the given one. | As a python code expert, you are capable of creating scripts from specifications. |
def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
"""
try:
# Nod to tastypie's use of importlib.
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_p... | Create a Python 3 function for
attempting to import a class from a string representation. | As a Python code composer, you craft elegant and concise scripts. |
Function to check if the time to battery charge depletion is at least the amount of time remaining in the time of the utility power of the battery. | How would you explain what the following Python 3 function does
def check_ups_estimated_minutes_remaining(the_session, the_helper, the_snmp_value):
the_helper.add_metric(
label=the_helper.options.type,
value=the_snmp_value,
uom="minutes")
the_helper.set_summary("Remaining runtime on bat... | You are a Python code generator, capable of creating scripts from specifications. |
Update the MIB excerpt
The present input frequency. | Here you have a function in Python 3, explain what it does
def check_ups_input_frequency(the_session, the_helper, the_snmp_value):
a_frequency = calc_frequency_from_snmpvalue(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
value=a_frequency,
uom='Hz')
the_helpe... | As a python code expert, you are capable of creating scripts from specifications. |
Update the output current of the resource. | Can you generate a brief explanation for the following Python 3 code
def check_ups_output_current(the_session, the_helper, the_snmp_value):
a_current = calc_output_current_from_snmpvalue(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
value=a_current,
uom='A')
... | You are a Python code generator, capable of creating scripts from specifications. |
Update the status of the active alarms. | How would you explain what the following Python 3 function does
def check_ups_alarms_present(the_session, the_helper, the_snmp_value):
if the_snmp_value != '0':
the_helper.add_status(pynag.Plugins.critical)
else:
the_helper.add_status(pynag.Plugins.ok)
the_helper.set_summary("{} active alarm... | You are a Python code analyst, evaluating scripts for potential improvements. |
OID. 1. 3. 6. 1. 534. 1. 534. 1. 4. 0 | Here you have a function in Python 3, explain what it does
def check_xups_bat_capacity(the_session, the_helper, the_snmp_value):
the_helper.add_metric(
label=the_helper.options.type,
value=a_snmp_value,
uom='%')
the_helper.set_summary("Remaining Battery Capacity {} %".format(the_snmp_v... | You are a Python code generator, capable of creating scripts from specifications. |
def check_ressources(sess):
"""
check the Ressources of the Fortinet Controller
all thresholds are currently hard coded. should be fine.
"""
# get the data
cpu_value = get_data(sess, cpu_oid, helper)
memory_value = get_data(sess, memory_oid, helper)
fil... | Can you implement a function in Python 3 that
checks the Ressources of the Fortinet Controller | As a python code expert, you are capable of creating scripts from specifications. |
def check_controller(sess):
"""
check the status of the controller
"""
controller_operational = get_data(sess, operational_oid, helper)
controller_availability = get_data(sess, availability_oid, helper)
controller_alarm = get_data(sess, alarm_oid, helper)... | Write a Python 3 script to
check the status of the controller | As a python code expert, you are capable of creating scripts from specifications. |
def check_accesspoints(sess):
"""
check the status of all connected access points
"""
ap_names = walk_data(sess, name_ap_oid, helper)[0]
ap_operationals = walk_data(sess, operational_ap_oid, helper)[0]
ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0]
... | Write a Python 3 function for
checking the status of all connected access points in the tree | You are a Python code architect, reviewing and designing scalable and efficient code |
check if the status is ok | Can you generate the documentation for the following Python 3 function
def normal_check(name, status, device_type):
status_string = NORMAL_STATE.get(int(status), "unknown")
if status_string == "ok":
return ok, "{} '{}': {}".format(device_type, name, status_string)
elif status_string == "unknown":
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a string containing the status of a given process. | Make a summary of the following Python 3 code
def probe_check(name, status, device_type):
status_string = PROBE_STATE.get(int(status), "unknown")
if status_string == "ok":
return ok, "{} '{}': {}".format(device_type, name, status_string)
if status_string == "unknown":
return unknown, "{} '... | As a python code expert, you are capable of creating scripts from specifications. |
def add_device_information(helper, session):
""" add general device information to summary """
host_name_data = helper.get_snmp_value(session, helper,
DEVICE_INFORMATION_OIDS['oid_host_name'])
product_type_data = helper.get_snmp_value(session, help... | How would you implement a function in Python 3 that
adds general device information to summary | You are a Python code analyst, evaluating scripts for potential improvements. |
process a single status | Given the following Python 3 function, write the documentation
def process_status(self, helper, session, check):
snmp_result_status = helper.get_snmp_value(session, helper, DEVICE_GLOBAL_OIDS['oid_' + check])
if check == "system_lcd":
helper.update_status(helper, normal_check("global", snmp... | As a Python code translator, you convert algorithms and pseudocode into Python. |
process status values from a table | Can you generate a brief explanation for the following Python 3 code
def process_states(self, helper, session, check):
snmp_result_status = helper.walk_snmp_values(session, helper,
DEVICE_STATES_OIDS["oid_" + check],
... | As a python code expert, you are capable of creating scripts from specifications. |
process the temperature sensors | Can you tell what is the following Python 3 function doing
def process_temperature_sensors(helper, session):
snmp_result_temp_sensor_names = helper.walk_snmp_values(
session, helper,
DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors")
snmp_result_tem... | As a python code expert, you are capable of creating scripts from specifications. |
def check_drives(drivename, drivestatus):
""" check the drive status """
return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format(
drivename, DISK_STATES[int(drivestatus)]["result"]) | Can you write a function in Python 3 where it
checks the status of the given drive | You are a Python code architect, reviewing and designing scalable and efficient code |
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data):
""" check the status of the power units """
return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"],
"Power unit '{}' redundancy: {}".format(power_unit_name_data,
... | How would you code a function in Python 3 to
check the status of the power units | You are a Python code architect, reviewing and designing scalable and efficient code |
check a global status
check_global_status(True, "Global Storage", '.1.3.6.1.4.1.232.3.1.3.0') | Can you generate the documentation for the following Python 3 function
def check_global_status(flag, name, oid):
# only check the status, if the "no" flag is not set
if flag:
# get the data via snmp
myData = get_data(sess, oid, helper)
data_summary_output, data_long_output = state_summar... | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_server_power():
"""
Check if the server is powered on
Skip this check, if the --noPowerState is set
"""
if power_state_flag:
power_state = get_data(sess, oid_power_state, helper)
power_state_summary_output, power_state_long_output = state_summary(power_state, 'Server power'... | Create a Python 3 function for
checking if the server is powered on | As a python code expert, you are capable of creating scripts from specifications. |
def check_storage_controllers():
"""
Check the status of the storage controllers
Skip this check, if --noController is set
"""
if ctrl_flag:
ctrl = walk_data(sess, oid_ctrl, helper)[0]
for x, data in enumerate(ctrl, 1):
ctrl_summary_output, ctrl_long_output = state_summar... | How would you implement a function in Python 3 that
checks the status of the storage controllers | As a python code expert, you are capable of creating scripts from specifications. |
def check_temperature_sensors():
"""
Check all temperature sensors of the server
All sensors with the value or threshold is -99 or 0 are ignored
"""
# walk all temperature sensor values and thresholds
env_temp = walk_data(sess, oid_env_temp, helper)[0]
env_temp_thresh = walk_data(sess, o... | Write a Python 3 script to
check all temperature sensors of the server and add them to the output | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if the power supplies are ok and we have the configured amount
| Given the following Python 3 function, write the documentation
def check_ps():
if int(input_pwr_sply) != 0:
ps_data = walk_data(sess, oid_ps, helper)[0]
ps_ok_count = 0
for x, state in enumerate(ps_data, 1):
# human readable status
hr_status = nor... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def check_power_redundancy():
"""
Check if the power supplies are redundant
The check is skipped if --noPowerRedundancy is set
"""
# skip the check if --noPowerRedundancy is set
if power_redundancy_flag:
# walk the data
ps_redundant_data = walk_data(sess, oid_ps_redundant... | Write a Python 3 function for
checking if the power supplies are redundant | As a Python code analyst, you investigate and solve complex coding mysteries |
def check_fan(input_fan):
"""
check the fans
"""
# get a list of all fans
fan_data = walk_data(sess, oid_fan, helper)[0]
fan_count = 0
summary_output = ''
long_output = ''
for x, fan in enumerate(fan_data, 1):
fan = int(fan)
if normal_state[fan] == 'ok':
... | Write a Python 3 function for
checking the fan count and return a summary and long output | You are a Python code generator, capable of creating scripts from specifications. |
Get SNMP values from 1st host. | Can you generate the documentation for the following Python 3 function
def get_snmp_from_host1(self):
response = self.snmp1.get_oids(ps1_oid, ps2_oid, fan1_oid, fan2_oid, bat_oid, temp_oid, activity_oid, logfill_oid)
self.ps1_value = states[int(response[0])]
self.ps2_value = states[int(response[... | You are a Python code generator, capable of creating scripts from specifications. |
Get SNMP values from 2nd host. | How would you explain what the following Python 3 function does
def get_snmp_from_host2(self):
if not self.snmp2:
self.activity_value2 = None
else:
response = self.snmp2.get_oids(activity_oid)
self.activity_value2 = activity[int(response[0])] | As a Python code analyst, you investigate and solve complex coding mysteries |
def check(self):
"""
Evaluate health status from device parameters.
"""
try:
self.get_snmp_from_host1()
self.get_snmp_from_host2()
except (health_monitoring_plugins.SnmpException, TypeError, KeyError):
self.helper.status(unknown)
se... | Write a Python 3 script to
evaluate health status from device parameters. | As a Python code composer, you craft elegant and concise scripts. |
update the status of the resource | Here you have a function in Python 3, explain what it does
def update_status(self, helper, status):
if status:
self.status(status[0])
# if the status is ok, add it to the long output
if status[0] == 0:
self.add_long_output(status[1])
# if the stat... | As a python code expert, you are capable of creating scripts from specifications. |
def get_snmp_value(sess, helper, oid):
""" return a snmp value or exits the plugin with unknown"""
snmp_result = sess.get_oids(oid)[0]
if snmp_result is None:
helper.exit(summary="No response from device for oid " + oid, exit_code=unknown, perfdata='')
else:
retu... | How would you code a function in Python 3 to
get a snmp value from the device | You are a Python code generator, capable of creating scripts from specifications. |
return a list of snmp values or exits the plugin with unknown | Can you tell what is the following Python 3 function doing
def walk_snmp_values(sess, helper, oid, check):
try:
snmp_walk = sess.walk_oid(oid)
result_list = []
for x in range(len(snmp_walk)):
result_list.append(snmp_walk[x].val)
if result_list !=... | You are a Python code analyst, evaluating scripts for potential improvements. |
def walk_oid(self, oid):
"""Get a list of SNMP varbinds in response to a walk for oid.
Each varbind in response list has a tag, iid, val and type attribute."""
var = netsnmp.Varbind(oid)
varlist = netsnmp.VarList(var)
data = self.walk(varlist)
if len(data) == 0:
... | Write a Python 3 script to
walk for oid. ArcGIS returns a list of SNMP varbinds in response to a walk for oid. ArcGIS returns a list of SNMP varbinds in response to a walk for oid. ArcGIS returns a list of SNMP varbinds in response to a walk for oid. ArcGIS returns a list of SNMP varbinds in response to a walk for oid.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def run_scan():
"""
show all available partitions
"""
all_disks = walk_data(sess, oid_hrStorageDescr, helper)[0]
print "All available disks at: " + host
for disk in all_disks:
print "Disk: \t'" + disk + "'"
quit() | Create a Python 3 function to
scan all available partitions | As a Python code translator, you convert algorithms and pseudocode into Python. |
returns True if the partition is in the description | Can you tell what is the following Python 3 function doing
def partition_found(partition, description):
# if we want to have a linux partition (/) we use the full path (startswith "/" would result in / /var /dev etc).
# if we start with something else, we use the startswith function
if "/" in partition:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_partition():
"""
check the defined partition
"""
all_index = walk_data(sess, oid_hrStorageIndex, helper)[0]
all_descriptions = walk_data(sess, oid_hrStorageDescr, helper)[0]
# we need the sucess flag for the error handling (partition found or not found)
sucess ... | Can you write a function in Python 3 where it
checks the defined partition and return the list of all the items that are in the order they were used | As a Python code composer, you craft elegant and concise scripts. |
def check_sensors():
"""
collect and check all available sensors
"""
all_sensors = walk_data(sess, oid_description, helper)[0]
all_status = walk_data(sess, oid_status, helper)[0]
# here we zip all index and descriptions to have a list like
# [('Fan Sensor', '2'), ('Power Supply Sensor', '4... | Write a Python 3 script to
collect and check all available sensors and status | As a Python code composer, you craft elegant and concise scripts. |
This function checks the basic battery status of the UPS batteries. | Here you have a function in Python 3, explain what it does
def check_basic_battery_status(the_session, the_helper, the_snmp_value):
apc_battery_states = {
'1' : 'unknown',
'2' : 'batteryNormal',
'3' : 'batteryLow',
'4' : 'batteryInFaultCondition'
}
a_state = apc_battery_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Checks the SNMP value for the battery replacement indicator. | Explain what the following Python 3 code does
def check_battery_replace_indicator(the_session, the_helper, the_snmp_value):
apc_states = {
'1' : 'Battery does not need to be replaced',
'2' : 'Battery needs to be replaced!'}
a_state = apc_states.get(the_snmp_value, "Unknown battery replacement s... | As a python code expert, you are capable of creating scripts from specifications. |
This function checks the environment temperature of the current probe. | Here you have a function in Python 3, explain what it does
def check_environment_temperature(the_session, the_helper, the_snmp_value, the_unit=1):
a_snmp_unit = snmpSessionBaseClass.get_data(
the_session,
apc_oid_environment_temperature_unit,
the_helper)
snmp_units = {
'1' : 'C'... | As a python code expert, you are capable of creating scripts from specifications. |
check if typ parameter is TCP or UDP
| Here you have a function in Python 3, explain what it does
def check_typ(helper, typ):
if typ != "tcp" and typ != "udp":
helper.exit(summary="Type (-t) must be udp or tcp.", exit_code=unknown, perfdata='') | As a python code expert, you are capable of creating scripts from specifications. |
def check_port(helper, port):
"""
check if the port parameter is really a port or "scan"
"""
try:
int(port)
except ValueError:
helper.exit(summary="Port (-p) must be a integer value.", exit_code=unknown, perfdata='') | How would you code a function in Python 3 to
check if the port parameter is really a port or scan | As a Python code analyst, you investigate and solve complex coding mysteries |
def check_udp(helper, host, port, session):
"""
the check logic for UDP ports
"""
open_ports = walk_data(session, '.1.3.6.1.2.1.7.5.1.2', helper)[0] # the udpLocaLPort from UDP-MIB.mib (deprecated)
# here we show all open UDP ports
if scan:
print "All open UDP ports at host " + host... | How would you implement a function in Python 3 that
checks if UDP port is open and close | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_tcp(helper, host, port, warning_param, critical_param, session):
"""
the check logic for check TCP ports
"""
# from tcpConnState from TCP-MIB
tcp_translate = {
"1" : "closed",
"2" : "listen",
"3" : "synSent",
"4" : "synReceived",
"5" : "established",... | Write a Python 3 script for
checking TCP ports and status | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a json string representing the python object obj. | Here you have a function in Python 3, explain what it does
def to_json(obj):
i = StringIO.StringIO()
w = Writer(i, encoding='UTF-8')
w.write_value(obj)
return i.getvalue() | As a python code expert, you are capable of creating scripts from specifications. |
Get SNMP values from host | Make a summary of the following Python 3 code
def get_data(self):
"Get SNMP values from host"
alarm_oids = [netsnmp.Varbind(alarms[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']]
metric_oids = [netsnmp.Varbind(metrics[metric_id]['oid']) for metric_id in self.models[self... | As a Python code analyst, you investigate and solve complex coding mysteries |
Build list with active alarms | Explain what the following Python 3 code does
def process_alarms(self, snmp_data):
"Build list with active alarms"
self.active_alarms = []
for i in range(0, len(self.models[self.modem_type]['alarms'])):
if bool(int(snmp_data[i])) == True:
self.active_alarms.append(sel... | As a Python code composer, you craft elegant and concise scripts. |
Build list with metrics | Explain what the following Python 3 code does
def process_metrics(self, snmp_data):
"Build list with metrics"
self.metrics = {}
for i in range(0, len(snmp_data)):
metric_id = self.models[self.modem_type]['metrics'][i]
value = int(snmp_data[i])
self.metrics[met... | As a Python code composer, you craft elegant and concise scripts. |
def convert_in_oid(service_name):
"""
calculate the correct OID for the service name
"""
s = service_name
# convert the service_name to ascci
service_ascii = [ord(c) for c in s]
# we need the length of the service name
length = str(len(s))
# make the oid
oid = base_oid + "." + l... | Can you write a function in Python 3 where it
converts the service name to OID | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_data(self):
"Return one SNMP response list for all status OIDs, and one list for all metric OIDs."
alarm_oids = [netsnmp.Varbind(status_mib[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']]
metric_oids = [netsnmp.Varbind(metric_mib[metric_id]['oid']) for metric_id... | Can you create a Python 3 function that
returns one SNMP response list for all status OIDs and one list for all metric OIDs. | You are a Python code analyst, evaluating scripts for potential improvements. |
Build list with active alarms | Here you have a function in Python 3, explain what it does
def process_alarms(self, snmp_data):
"Build list with active alarms"
self.active_alarms = {}
for i in range(0, len(self.models[self.modem_type]['alarms'])):
mib_name = self.models[self.modem_type]['alarms'][i]
con... | You are a Python code architect, reviewing and designing scalable and efficient code |
def process_metrics(self, snmp_data):
"Build list with metrics"
self.metrics = {}
for i in range(0, len(snmp_data)):
mib_name = self.models[self.modem_type]['metrics'][i]
conv = metric_mib[mib_name]['conv']
self.metrics[mib_name] = conv(snmp_data[i]) | Can you implement a function in Python 3 that
builds list with metrics | As a python code expert, you are capable of creating scripts from specifications. |
def real_value(value, digit):
"""
function to calculate the real value
we need to devide the value by the digit
e.g.
value = 100
digit = 2
return: "1.0"
"""
return str(float(value) / math.pow(10, float(digit))) | Write a Python 3 function that can
function to calculate the real value of the value by the digit | As a Python code translator, you convert algorithms and pseudocode into Python. |
def check_inlet(self, helper):
"""
check the Inlets of Raritan PDUs
"""
# walk the data
try:
inlet_values = self.sess.walk_oid(self.oids['oid_inlet_value'])
inlet_units = self.sess.walk_oid(self.oids['oid_inlet_unit'])
inlet_digits = self.sess.... | Can you implement a function in Python 3 that
checks the Inlets of Raritan PDUs | You are a Python code generator, capable of creating scripts from specifications. |
def check_outlet(self, helper):
"""
check the status of the specified outlet
"""
try:
outlet_name, outlet_state = self.sess.get_oids(self.oids['oid_outlet_name'], self.oids['oid_outlet_state'])
except health_monitoring_plugins.SnmpException as e:
helper.ex... | Can you implement a function in Python 3 that
checks the status of the specified outlet | As a Python code analyst, you investigate and solve complex coding mysteries |
check the status of the specified sensor | Can you generate a brief explanation for the following Python 3 code
def check_sensor(self, helper):
try:
sensor_name, sensor_state, sensor_type = self.sess.get_oids(
self.oids['oid_sensor_name'], self.oids['oid_sensor_state'], self.oids['oid_sensor_type'])
except health_moni... | You are a Python code analyst, evaluating scripts for potential improvements. |
Wrapper for netsnmp s dev_null and dev_null_wrapper. | Make a summary of the following Python 3 code
def dev_null_wrapper(func, *a, **kwargs):
os.dup2(dev_null, sys.stdout.fileno())
return_object = func(*a, **kwargs)
sys.stdout.flush()
os.dup2(tmp_stdout, sys.stdout.fileno())
return return_object | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a summary and long output for a given state | Can you tell what is the following Python 3 function doing
def state_summary(value, name, state_list, helper, ok_value = 'ok', info = None):
# translate the value (integer) we receive to a human readable value (e.g. ok, critical etc.) with the given state_list
state_value = state_list[int(value)]
summar... | You are a Python code analyst, evaluating scripts for potential improvements. |
Add output to the summary report | Explain what the following Python 3 code does
def add_output(summary_output, long_output, helper):
if summary_output != '':
helper.add_summary(summary_output)
helper.add_long_output(long_output) | You are a Python code generator, capable of creating scripts from specifications. |
Process the GPS position from the SNMP server | Make a summary of the following Python 3 code
def process_gps_position(self, helper, sess):
gps_position = helper.get_snmp_value(sess, helper, self.oids['oid_gps_position'])
if gps_position:
helper.add_summary(gps_position)
else:
helper.add_summary("Could not retrieve G... | As a Python code composer, you craft elegant and concise scripts. |
def process_status(self, helper, sess, check):
""" get the snmp value, check the status and update the helper"""
if check == 'ntp_current_state':
ntp_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_ntp_current_state_int'])
result = self.check_ntp_status(ntp_statu... | Can you write a function in Python 3 where it
gets the snmp value check the status and update the helper | As a Python code translator, you convert algorithms and pseudocode into Python. |
def check_ntp_status(self, ntp_status_int):
"""
check the NTP status
"""
# convert the ntp_status integer value in a human readable value
ntp_status_string = self.ntp_status.get(ntp_status_int, "unknown")
if ntp_status_string == "unknown":
return unknown, ("N... | Can you create a Python 3 function that
checks the NTP status and return the appropriate object | You are a Python code generator, capable of creating scripts from specifications. |
def check_gps_status(self, gps_status_int):
"""
check the GPS status
"""
gps_mode_string = self.gps_mode.get(gps_status_int, "unknown")
if gps_mode_string == "unknown":
return unknown, ("GPS status: " + gps_mode_string)
elif gps_mode_string != "normalOperati... | Write a Python 3 function for
checking the GPS status | As a Python code analyst, you investigate and solve complex coding mysteries |
Process the good satellites from the SNMP server | Can you tell what is the following Python 3 function doing
def process_satellites(self, helper, sess):
good_satellites = helper.get_snmp_value(sess, helper, self.oids['oid_gps_satellites_good'])
# Show the summary and add the metric and afterwards check the metric
helper.add_summary("Good satel... | You are a Python code architect, reviewing and designing scalable and efficient code |
def login_password(self, value):
"""Set the value of the login password field."""
password = self.selenium.find_element(*self._password_input_locator)
password.clear()
password.send_keys(value) | Can you implement a function in Python 3 that
sets the value of the login password field. | You are a Python code architect, reviewing and designing scalable and efficient code |
def email(self, value):
"""Set the value of the email field."""
email = self.wait.until(expected.visibility_of_element_located(
self._email_input_locator))
email.clear()
email.send_keys(value) | How would you implement a function in Python 3 that
sets the value of the email field. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Signs in using the specified email address and password. | Can you generate the documentation for the following Python 3 function
def sign_in(self, email, password):
self.email = email
self.login_password = password
if self.is_element_present(*self._next_button_locator):
self.wait.until(expected.visibility_of_element_located(
... | As a python code expert, you are capable of creating scripts from specifications. |
Signs in a user either with the specified email address and password or a returning user. | Here you have a function in Python 3, explain what it does
def sign_in(self, email=None, password=None):
from .pages.sign_in import SignIn
sign_in = SignIn(self.selenium, self.timeout)
sign_in.sign_in(email, password) | You are a Python code architect, reviewing and designing scalable and efficient code |
Dump rows to fileobj with the given encoding and csv dialect. | Make a summary of the following Python 3 code
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT):
csvwriter = csv.writer(fileobj, dialect=dialect)
csv_writerows(csvwriter, rows, encoding) | You are a Python code analyst, evaluating scripts for potential improvements. |
def write_dataframe(rows, encoding=ENCODING, dialect=DIALECT, **kwargs):
"""Dump ``rows`` to string buffer and load with ``pandas.read_csv()`` using ``kwargs``."""
global pandas
if pandas is None: # pragma: no cover
import pandas
with contextlib.closing(CsvBuffer()) as fd:
write_csv(fd,... | Write a Python 3 function that can
dump rows to string buffer and load with pandas. read_csv | You are a Python code analyst, evaluating scripts for potential improvements. |
def from_string(cls, link):
"""Return a new SheetUrl instance from parsed URL string.
>>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam')
<SheetUrl id='spam' gid=0>
"""
ma = cls._pattern.search(link)
if ma is None:
raise ValueError(link)
... | Write a Python 3 script to
return a new SheetUrl instance from parsed URL string. | You are a Python code analyst, evaluating scripts for potential improvements. |
def doctemplate(*args):
"""Return a decorator putting ``args`` into the docstring of the decorated ``func``.
>>> @doctemplate('spam', 'spam')
... def spam():
... '''Returns %s, lovely %s.'''
... return 'Spam'
>>> spam.__doc__
'Returns spam, lovely spam.'
"""
def decorator(f... | Write a Python 3 function for
returning a decorator putting args into the docstring of the decorated func. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a list defaultdict with items grouped by keyfunc. | Can you generate a brief explanation for the following Python 3 code
def group_dict(items, keyfunc):
result = collections.defaultdict(list)
for i in items:
key = keyfunc(i)
result[key].append(i)
return result | You are a Python code analyst, evaluating scripts for potential improvements. |
Return unique list of items preserving order. | Given the following Python 3 function, write the documentation
def uniqued(iterable):
seen = set()
return [item for item in iterable if item not in seen and not seen.add(item)] | You are a Python code architect, reviewing and designing scalable and efficient code |
Build a service endpoint for interacting with Google API. | Can you tell what is the following Python 3 function doing
def build_service(name=None, **kwargs):
if name is not None:
for kw, value in iteritems(SERVICES[name]):
kwargs.setdefault(kw, value)
return apiclient.discovery.build(**kwargs) | As a python code expert, you are capable of creating scripts from specifications. |
Yields a list of files from the Google drive. | Make a summary of the following Python 3 code
def iterfiles(service, name=None, mimeType=SHEET, order=FILEORDER):
params = {'orderBy': order, 'pageToken': None}
q = []
if name is not None:
q.append("name='%s'" % name)
if mimeType is not None:
q.append("mimeType='%s'" % mimeType)
if q... | As a Python code composer, you craft elegant and concise scripts. |
def spreadsheet(service, id):
"""Fetch and return spreadsheet meta data with Google sheets API."""
request = service.spreadsheets().get(spreadsheetId=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
... | Implement a function in Python 3 to
fetch and return spreadsheet meta data with Google sheets API. | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.