repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
lobocv/pyperform
pyperform/benchmark.py
Benchmark.write_log
python
def write_log(self, fs=None): log = StringIO.StringIO() log.write(self.setup_src) # If the function is not bound, write the test score to the log if not self.is_class_method: time_avg = convert_time_units(self.time_average_seconds) log.write("\nAverage time: {0} ...
Write the results of the benchmark to a log file. :param fs: file-like object.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/benchmark.py#L68-L83
[ "def convert_time_units(t):\n \"\"\" Convert time in seconds into reasonable time units. \"\"\"\n if t == 0:\n return '0 s'\n order = log10(t)\n if -9 < order < -6:\n time_units = 'ns'\n factor = 1000000000\n elif -6 <= order < -3:\n time_units = 'us'\n factor = 100...
class Benchmark(object): enable = True def __init__(self, setup=None, classname=None, timeit_repeat=3, timeit_number=1000, largs=None, kwargs=None): self.setup = setup self.timeit_repeat = timeit_repeat self.timeit_number = timeit_number self.classname = classname self.g...
lobocv/pyperform
pyperform/benchmark.py
Benchmark.run_timeit
python
def run_timeit(self, stmt, setup): _timer = timeit.Timer(stmt=stmt, setup=setup) trials = _timer.repeat(self.timeit_repeat, self.timeit_number) self.time_average_seconds = sum(trials) / len(trials) / self.timeit_number # Convert into reasonable time units time_avg = convert_time_...
Create the function call statement as a string used for timeit.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/benchmark.py#L85-L92
[ "def convert_time_units(t):\n \"\"\" Convert time in seconds into reasonable time units. \"\"\"\n if t == 0:\n return '0 s'\n order = log10(t)\n if -9 < order < -6:\n time_units = 'ns'\n factor = 1000000000\n elif -6 <= order < -3:\n time_units = 'us'\n factor = 100...
class Benchmark(object): enable = True def __init__(self, setup=None, classname=None, timeit_repeat=3, timeit_number=1000, largs=None, kwargs=None): self.setup = setup self.timeit_repeat = timeit_repeat self.timeit_number = timeit_number self.classname = classname self.g...
lobocv/pyperform
pyperform/cprofile_parser.py
cProfileFuncStat.from_dict
python
def from_dict(cls, d): stats = [] for (filename, lineno, name), stat_values in d.iteritems(): if len(stat_values) == 5: ncalls, ncall_nr, total_time, cum_time, subcall_stats = stat_values else: ncalls, ncall_nr, total_time, cum_time = stat_values ...
Used to create an instance of this class from a pstats dict item
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/cprofile_parser.py#L62-L74
null
class cProfileFuncStat(object): """ Class that represents a item in the pstats dictionary """ stats = {} run_time_s = 0 n_decimal_percentages = 2 def __init__(self, filename, lineno, name, ncalls, ncall_nr, total_time, cum_time, subcall_stats=None): self.filename = filename ...
lobocv/pyperform
pyperform/cprofile_parser.py
cProfileFuncStat.to_dict
python
def to_dict(self): if self.subcall is not None: if isinstance(self.subcall, dict): subcalls = self.subcall else: subcalls = {} for s in self.subcall: subcalls.update(s.to_dict()) return {(self.filename, self....
Convert back to the pstats dictionary representation (used for saving back as pstats binary file)
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/cprofile_parser.py#L76-L89
null
class cProfileFuncStat(object): """ Class that represents a item in the pstats dictionary """ stats = {} run_time_s = 0 n_decimal_percentages = 2 def __init__(self, filename, lineno, name, ncalls, ncall_nr, total_time, cum_time, subcall_stats=None): self.filename = filename ...
lobocv/pyperform
pyperform/cprofile_parser.py
cProfileParser.exclude_functions
python
def exclude_functions(self, *funcs): for f in funcs: f.exclude = True run_time_s = sum(0 if s.exclude else s.own_time_s for s in self.stats) cProfileFuncStat.run_time_s = run_time_s
Excludes the contributions from the following functions.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/cprofile_parser.py#L111-L118
null
class cProfileParser(object): """ A manager class that reads in a pstats file and allows futher decontruction of the statistics. """ def __init__(self, pstats_file): self.path = pstats_file with open(stat_file, 'rb') as _f: self.raw_stats = _f.read() with open(stat_...
lobocv/pyperform
pyperform/cprofile_parser.py
cProfileParser.get_top
python
def get_top(self, stat, n): """Return the top n values when sorting by 'stat'""" return sorted(self.stats, key=lambda x: getattr(x, stat), reverse=True)[:n]
Return the top n values when sorting by 'stat
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/cprofile_parser.py#L120-L122
null
class cProfileParser(object): """ A manager class that reads in a pstats file and allows futher decontruction of the statistics. """ def __init__(self, pstats_file): self.path = pstats_file with open(stat_file, 'rb') as _f: self.raw_stats = _f.read() with open(stat_...
lobocv/pyperform
pyperform/cprofile_parser.py
cProfileParser.save_pstat
python
def save_pstat(self, path): stats = {} for s in self.stats: if not s.exclude: stats.update(s.to_dict()) with open(path, 'wb') as f: marshal.dump(stats, f)
Save the modified pstats file
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/cprofile_parser.py#L124-L134
null
class cProfileParser(object): """ A manager class that reads in a pstats file and allows futher decontruction of the statistics. """ def __init__(self, pstats_file): self.path = pstats_file with open(stat_file, 'rb') as _f: self.raw_stats = _f.read() with open(stat_...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/i2c_utility.py
TCA_select
python
def TCA_select(bus, addr, channel): """ This function will write to the control register of the TCA module to select the channel that will be exposed on the TCA module. After doing this, the desired module can be used as it would be normally. (Th...
This function will write to the control register of the TCA module to select the channel that will be exposed on the TCA module. After doing this, the desired module can be used as it would be normally. (The caller should use the address of the I2C sensor modu...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/i2c_utility.py#L6-L40
null
#!/usr/bin/python # This file contains utility functions used to select # channels via the I2C Multiplexer or the ADC def TCA_select(bus, addr, channel): """ This function will write to the control register of the TCA module to select the channel that will be exposed on th...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/i2c_utility.py
get_ADC_value
python
def get_ADC_value(bus, addr, channel): """ This method selects a channel and initiates conversion The ADC operates at 240 SPS (12 bits) with 1x gain One shot conversions are used, meaning a wait period is needed in order to acquire new data. This is done via a constant poll of ...
This method selects a channel and initiates conversion The ADC operates at 240 SPS (12 bits) with 1x gain One shot conversions are used, meaning a wait period is needed in order to acquire new data. This is done via a constant poll of the ready bit. Upon completion, a voltage value ...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/i2c_utility.py#L43-L77
null
#!/usr/bin/python # This file contains utility functions used to select # channels via the I2C Multiplexer or the ADC def TCA_select(bus, addr, channel): """ This function will write to the control register of the TCA module to select the channel that will be exposed on th...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/i2c_utility.py
IO_expander_output
python
def IO_expander_output(bus, addr, bank, mask): """ Method for controlling the GPIO expander via I2C which accepts a bank - A(0) or B(1) and a mask to push to the pins of the expander. The method also assumes the the expander is operating in sequential mode. If this mode is no...
Method for controlling the GPIO expander via I2C which accepts a bank - A(0) or B(1) and a mask to push to the pins of the expander. The method also assumes the the expander is operating in sequential mode. If this mode is not used, the register addresses will need to be chang...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/i2c_utility.py#L80-L114
null
#!/usr/bin/python # This file contains utility functions used to select # channels via the I2C Multiplexer or the ADC def TCA_select(bus, addr, channel): """ This function will write to the control register of the TCA module to select the channel that will be exposed on th...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/i2c_utility.py
get_IO_reg
python
def get_IO_reg(bus, addr, bank): """ Method retrieves the register corresponding to respective bank (0 or 1) """ output_map = [0x14, 0x15] if (bank != 0) and (bank != 1): print() raise InvalidIOUsage("An invalid IO bank has been selected") output_reg = output_map[bank] ...
Method retrieves the register corresponding to respective bank (0 or 1)
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/i2c_utility.py#L116-L127
null
#!/usr/bin/python # This file contains utility functions used to select # channels via the I2C Multiplexer or the ADC def TCA_select(bus, addr, channel): """ This function will write to the control register of the TCA module to select the channel that will be exposed on th...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/i2c_utility.py
import_i2c_addr
python
def import_i2c_addr(bus, opt="sensors"): """ import_i2c_addresses will return a list of the currently connected I2C devices. This can be used a means to automatically detect the number of connected sensor modules. Modules are between int(112) and int(119) By...
import_i2c_addresses will return a list of the currently connected I2C devices. This can be used a means to automatically detect the number of connected sensor modules. Modules are between int(112) and int(119) By default, the method will return a list ...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/i2c_utility.py#L129-L160
null
#!/usr/bin/python # This file contains utility functions used to select # channels via the I2C Multiplexer or the ADC def TCA_select(bus, addr, channel): """ This function will write to the control register of the TCA module to select the channel that will be exposed on th...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/sense.py
get_lux_count
python
def get_lux_count(lux_byte): """ Method to convert data from the TSL2550D lux sensor into more easily usable ADC count values. """ LUX_VALID_MASK = 0b10000000 LUX_CHORD_MASK = 0b01110000 LUX_STEP_MASK = 0b00001111 valid = lux_byte & LUX_VALID_MASK if valid != 0: step_n...
Method to convert data from the TSL2550D lux sensor into more easily usable ADC count values.
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/sense.py#L282-L300
null
#!/usr/bin/python # Contains class information for sensor nodes. # Each plant is treated as a base, and each plant contains multiple sensors. # Basic usage: # Create a plant record using: # plant1 = Plant(temp_addr, humidity_addr, lux_addr, adc_addr) # Updating individual sensor values can be done with # Note...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/sense.py
SensorCluster.update_lux
python
def update_lux(self, extend=0): """ Communicates with the TSL2550D light sensor and returns a lux value. Note that this method contains approximately 1 second of total delay. This delay is necessary in order to obtain full resolution compensated lux values. ...
Communicates with the TSL2550D light sensor and returns a lux value. Note that this method contains approximately 1 second of total delay. This delay is necessary in order to obtain full resolution compensated lux values. Alternatively, the device could be ...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/sense.py#L64-L115
[ "def TCA_select(bus, addr, channel):\n \"\"\"\n This function will write to the control register of the\n TCA module to select the channel that will be\n exposed on the TCA module.\n After doing this, the desired module can be used as it would be normally.\n ...
class SensorCluster(object): 'Base class for each individual plant containing sensor info' __metaclass__ = IterList _list = [] analog_power_pin = 0 power_bank = 0 # bank and pin used to toggle analog sensor power temp_addr = 0x48 temp_chan = 3 humidity_addr = 0x27 humidity_chan = 1 ...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/sense.py
SensorCluster.update_humidity_temp
python
def update_humidity_temp(self): """ This method utilizes the HIH7xxx sensor to read humidity and temperature in one call. """ # Create mask for STATUS (first two bits of 64 bit wide result) STATUS = 0b11 << 6 TCA_select(SensorCluster.bus, self.mux_addr, Senso...
This method utilizes the HIH7xxx sensor to read humidity and temperature in one call.
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/sense.py#L117-L139
[ "def TCA_select(bus, addr, channel):\n \"\"\"\n This function will write to the control register of the\n TCA module to select the channel that will be\n exposed on the TCA module.\n After doing this, the desired module can be used as it would be normally.\n ...
class SensorCluster(object): 'Base class for each individual plant containing sensor info' __metaclass__ = IterList _list = [] analog_power_pin = 0 power_bank = 0 # bank and pin used to toggle analog sensor power temp_addr = 0x48 temp_chan = 3 humidity_addr = 0x27 humidity_chan = 1 ...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/sense.py
SensorCluster.update_soil_moisture
python
def update_soil_moisture(self): """ Method will select the ADC module, turn on the analog sensor, wait for voltage settle, and then digitize the sensor voltage. Voltage division/signal loss is accounted for by scaling up the sensor output. ...
Method will select the ADC module, turn on the analog sensor, wait for voltage settle, and then digitize the sensor voltage. Voltage division/signal loss is accounted for by scaling up the sensor output. This may need to be adjusted if ...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/sense.py#L141-L162
[ "def get_ADC_value(bus, addr, channel):\n \"\"\"\n This method selects a channel and initiates conversion\n The ADC operates at 240 SPS (12 bits) with 1x gain\n One shot conversions are used, meaning a wait period is needed\n in order to acquire new data. This is done via a constant poll\n ...
class SensorCluster(object): 'Base class for each individual plant containing sensor info' __metaclass__ = IterList _list = [] analog_power_pin = 0 power_bank = 0 # bank and pin used to toggle analog sensor power temp_addr = 0x48 temp_chan = 3 humidity_addr = 0x27 humidity_chan = 1 ...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/sense.py
SensorCluster.update_instance_sensors
python
def update_instance_sensors(self, opt=None): """ Method runs through all sensor modules and updates to the latest sensor values. After running through each sensor module, The sensor head (the I2C multiplexer), is disabled in order to avoid address conflicts. ...
Method runs through all sensor modules and updates to the latest sensor values. After running through each sensor module, The sensor head (the I2C multiplexer), is disabled in order to avoid address conflicts. Usage: plant_sensor_object.updateAllSensors(bus...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/sense.py#L164-L189
[ "def TCA_select(bus, addr, channel):\n \"\"\"\n This function will write to the control register of the\n TCA module to select the channel that will be\n exposed on the TCA module.\n After doing this, the desired module can be used as it would be normally.\n ...
class SensorCluster(object): 'Base class for each individual plant containing sensor info' __metaclass__ = IterList _list = [] analog_power_pin = 0 power_bank = 0 # bank and pin used to toggle analog sensor power temp_addr = 0x48 temp_chan = 3 humidity_addr = 0x27 humidity_chan = 1 ...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/sense.py
SensorCluster.sensor_values
python
def sensor_values(self): """ Returns the values of all sensors for this cluster """ self.update_instance_sensors(opt="all") return { "light": self.lux, "water": self.soil_moisture, "humidity": self.humidity, "temperature": ...
Returns the values of all sensors for this cluster
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/sense.py#L191-L201
[ "def update_instance_sensors(self, opt=None):\n\n \"\"\" Method runs through all sensor modules and updates \n to the latest sensor values.\n After running through each sensor module,\n The sensor head (the I2C multiplexer), is disabled\n in order to avoid address conflicts.\n Usage:\n ...
class SensorCluster(object): 'Base class for each individual plant containing sensor info' __metaclass__ = IterList _list = [] analog_power_pin = 0 power_bank = 0 # bank and pin used to toggle analog sensor power temp_addr = 0x48 temp_chan = 3 humidity_addr = 0x27 humidity_chan = 1 ...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/sense.py
SensorCluster.analog_sensor_power
python
def analog_sensor_power(cls, bus, operation): """ Method that turns on all of the analog sensor modules Includes all attached soil moisture sensors Note that all of the SensorCluster object should be attached in parallel and only 1 GPIO pin is available ...
Method that turns on all of the analog sensor modules Includes all attached soil moisture sensors Note that all of the SensorCluster object should be attached in parallel and only 1 GPIO pin is available to toggle analog sensor power. The sensor p...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/sense.py#L220-L244
[ "def IO_expander_output(bus, addr, bank, mask):\n \"\"\"\n Method for controlling the GPIO expander via I2C\n which accepts a bank - A(0) or B(1) and a mask\n to push to the pins of the expander.\n\n The method also assumes the the expander is operating\n in sequential mode. If this mo...
class SensorCluster(object): 'Base class for each individual plant containing sensor info' __metaclass__ = IterList _list = [] analog_power_pin = 0 power_bank = 0 # bank and pin used to toggle analog sensor power temp_addr = 0x48 temp_chan = 3 humidity_addr = 0x27 humidity_chan = 1 ...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/sense.py
SensorCluster.get_water_level
python
def get_water_level(cls): """ This method uses the ADC on the control module to measure the current water tank level and returns the water volume remaining in the tank. For this method, it is assumed that a simple voltage divider is used to interface the se...
This method uses the ADC on the control module to measure the current water tank level and returns the water volume remaining in the tank. For this method, it is assumed that a simple voltage divider is used to interface the sensor to the ADC module. ...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/sense.py#L247-L279
[ "def get_ADC_value(bus, addr, channel):\n \"\"\"\n This method selects a channel and initiates conversion\n The ADC operates at 240 SPS (12 bits) with 1x gain\n One shot conversions are used, meaning a wait period is needed\n in order to acquire new data. This is done via a constant poll\n ...
class SensorCluster(object): 'Base class for each individual plant containing sensor info' __metaclass__ = IterList _list = [] analog_power_pin = 0 power_bank = 0 # bank and pin used to toggle analog sensor power temp_addr = 0x48 temp_chan = 3 humidity_addr = 0x27 humidity_chan = 1 ...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/control.py
ControlCluster.compile_instance_masks
python
def compile_instance_masks(cls): # Compute required # of IO expanders needed, clear mask variable. number_IO_expanders = ((len(cls._list) - 1) / 4) + 1 cls.master_mask = [0, 0] * number_IO_expanders for ctrlobj in cls: # Or masks together bank-by-banl cls.master_...
Compiles instance masks into a master mask that is usable by the IO expander. Also determines whether or not the pump should be on. Method is generalized to support multiple IO expanders for possible future expansion.
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L44-L60
null
class ControlCluster(object): """ This class serves as a control module for each plant's fan, light, and pump valve. Upon instantiation, the class will use it's ID in order to generate a GPIO mapping corresponding to the pins on the MCP IO expander. Currently, o...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/control.py
ControlCluster.update
python
def update(self): ControlCluster.compile_instance_masks() IO_expander_output( ControlCluster.bus, self.IOexpander, self.bank, ControlCluster.master_mask[self.bank]) if self.bank != ControlCluster.pump_bank: IO_expander_output( Con...
This method exposes a more simple interface to the IO module Regardless of what the control instance contains, this method will transmit the queued IO commands to the IO expander Usage: plant1Control.update(bus)
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L62-L80
[ "def IO_expander_output(bus, addr, bank, mask):\n \"\"\"\n Method for controlling the GPIO expander via I2C\n which accepts a bank - A(0) or B(1) and a mask\n to push to the pins of the expander.\n\n The method also assumes the the expander is operating\n in sequential mode. If this mo...
class ControlCluster(object): """ This class serves as a control module for each plant's fan, light, and pump valve. Upon instantiation, the class will use it's ID in order to generate a GPIO mapping corresponding to the pins on the MCP IO expander. Currently, o...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/control.py
ControlCluster.form_GPIO_map
python
def form_GPIO_map(self): # Compute bank/pins/IOexpander address based on ID if self.ID == 1: self.IOexpander = 0x20 self.bank = 0 self.fan = 2 self.light = 3 self.valve = 4 elif self.ID == 2: self.IOexpander = 0x20 ...
This method creates a dictionary to map plant IDs to GPIO pins are associated in triples. Each ID gets a light, a fan, and a mist nozzle.
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L82-L125
null
class ControlCluster(object): """ This class serves as a control module for each plant's fan, light, and pump valve. Upon instantiation, the class will use it's ID in order to generate a GPIO mapping corresponding to the pins on the MCP IO expander. Currently, o...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/control.py
ControlCluster.manage_pump
python
def manage_pump(self, operation): if operation == "on": self.controls["pump"] = "on" elif operation == "off": self.controls["pump"] = "off" return True
Updates control module knowledge of pump requests. If any sensor module requests water, the pump will turn on.
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L152-L163
null
class ControlCluster(object): """ This class serves as a control module for each plant's fan, light, and pump valve. Upon instantiation, the class will use it's ID in order to generate a GPIO mapping corresponding to the pins on the MCP IO expander. Currently, o...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/control.py
ControlCluster.control
python
def control(self, on=[], off=[]): controls = {"light", "valve", "fan", "pump"} def cast_arg(arg): if type(arg) is str: if arg == "all": return controls else: return {arg} & controls else: ret...
This method serves as the primary interaction point to the controls interface. - The 'on' and 'off' arguments can either be a list or a single string. This allows for both individual device control and batch controls. Note: Both the onlist and offlist are optional. ...
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L178-L219
[ "def update(self):\n \"\"\" This method exposes a more simple interface to the IO module\n Regardless of what the control instance contains, this method\n will transmit the queued IO commands to the IO expander\n\n Usage: plant1Control.update(bus)\n \"\"\"\n ControlCluster.compile_instance_masks()...
class ControlCluster(object): """ This class serves as a control module for each plant's fan, light, and pump valve. Upon instantiation, the class will use it's ID in order to generate a GPIO mapping corresponding to the pins on the MCP IO expander. Currently, o...
ECESeniorDesign/greenhouse_envmgmt
greenhouse_envmgmt/control.py
ControlCluster.restore_state
python
def restore_state(self): current_mask = get_IO_reg(ControlCluster.bus, self.IOexpander, self.bank) if current_mask & (1 << ControlCluster.pump_pin): self.manage_pump("on") if current_mask & (1 << self.fan): ...
Method should be called on obj. initialization When called, the method will attempt to restore IO expander and RPi coherence and restore local knowledge across a possible power failure
train
https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L221-L235
[ "def get_IO_reg(bus, addr, bank):\n \"\"\"\n Method retrieves the register corresponding to respective bank (0 or 1)\n \"\"\"\n output_map = [0x14, 0x15]\n if (bank != 0) and (bank != 1):\n print()\n raise InvalidIOUsage(\"An invalid IO bank has been selected\")\n\n output_reg = outp...
class ControlCluster(object): """ This class serves as a control module for each plant's fan, light, and pump valve. Upon instantiation, the class will use it's ID in order to generate a GPIO mapping corresponding to the pins on the MCP IO expander. Currently, o...
brbsix/pip-utils
pip_utils/dependants.py
command_dependants
python
def command_dependants(options): dependants = sorted( get_dependants(options.package.project_name), key=lambda n: n.lower() ) if dependants: print(*dependants, sep='\n')
Command launched by CLI.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/dependants.py#L18-L26
[ "def get_dependants(project_name):\n \"\"\"Yield dependants of `project_name`.\"\"\"\n for package in get_installed_distributions(user_only=ENABLE_USER_SITE):\n if is_dependant(package, project_name):\n yield package.project_name\n" ]
# -*- coding: utf-8 -*- """List dependants of package""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # standard imports from site import ENABLE_USER_SITE # external imports try: from pip._internal.utils.misc import get_installed_distributions except ImportError: #...
brbsix/pip-utils
pip_utils/dependants.py
get_dependants
python
def get_dependants(project_name): for package in get_installed_distributions(user_only=ENABLE_USER_SITE): if is_dependant(package, project_name): yield package.project_name
Yield dependants of `project_name`.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/dependants.py#L29-L33
[ "def is_dependant(package, project_name):\n \"\"\"Determine whether `package` is a dependant of `project_name`.\"\"\"\n for requirement in package.requires():\n # perform case-insensitive matching\n if requirement.project_name.lower() == project_name.lower():\n return True\n return...
# -*- coding: utf-8 -*- """List dependants of package""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # standard imports from site import ENABLE_USER_SITE # external imports try: from pip._internal.utils.misc import get_installed_distributions except ImportError: #...
brbsix/pip-utils
pip_utils/dependants.py
is_dependant
python
def is_dependant(package, project_name): for requirement in package.requires(): # perform case-insensitive matching if requirement.project_name.lower() == project_name.lower(): return True return False
Determine whether `package` is a dependant of `project_name`.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/dependants.py#L36-L42
null
# -*- coding: utf-8 -*- """List dependants of package""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # standard imports from site import ENABLE_USER_SITE # external imports try: from pip._internal.utils.misc import get_installed_distributions except ImportError: #...
brbsix/pip-utils
pip_utils/locate.py
command_locate
python
def command_locate(options): matches = find_owners(options.file.name) if matches: print(*matches, sep='\n')
Command launched by CLI.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/locate.py#L21-L26
[ "def find_owners(path):\n \"\"\"Return the package(s) that file belongs to.\"\"\"\n abspath = os.path.abspath(path)\n\n packages = search_packages_info(\n sorted((d.project_name for d in\n get_installed_distributions(user_only=ENABLE_USER_SITE)),\n key=lambda d: d.lower(...
# -*- coding: utf-8 -*- """Identify package that file belongs to""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # standard imports import os from site import ENABLE_USER_SITE # external imports try: from pip._internal.commands.show import search_packages_info from...
brbsix/pip-utils
pip_utils/locate.py
find_owners
python
def find_owners(path): abspath = os.path.abspath(path) packages = search_packages_info( sorted((d.project_name for d in get_installed_distributions(user_only=ENABLE_USER_SITE)), key=lambda d: d.lower())) return [p['name'] for p in packages if is_owner(p, abspath)]
Return the package(s) that file belongs to.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/locate.py#L29-L38
null
# -*- coding: utf-8 -*- """Identify package that file belongs to""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # standard imports import os from site import ENABLE_USER_SITE # external imports try: from pip._internal.commands.show import search_packages_info from...
brbsix/pip-utils
pip_utils/locate.py
is_owner
python
def is_owner(package, abspath): try: files = package['files'] location = package['location'] except KeyError: return False paths = (os.path.abspath(os.path.join(location, f)) for f in files) return abspath in paths
Determine whether `abspath` belongs to `package`.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/locate.py#L41-L52
null
# -*- coding: utf-8 -*- """Identify package that file belongs to""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # standard imports import os from site import ENABLE_USER_SITE # external imports try: from pip._internal.commands.show import search_packages_info from...
brbsix/pip-utils
setup.py
long_description
python
def long_description(): # use re.compile() for flags support in Python 2.6 pattern = re.compile(r'\n^\.\. start-badges.*^\.\. end-badges\n', flags=re.M | re.S) return pattern.sub('', read('README.rst'))
Return the contents of README.rst (with badging removed).
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/setup.py#L32-L37
[ "def read(*names, **kwargs):\n \"\"\"Return contents of text file (in the same directory as this file).\"\"\"\n return io.open(\n os.path.join(os.path.dirname(__file__), *names),\n encoding=kwargs.get('encoding', 'utf8')\n ).read()\n" ]
# -*- coding: utf-8 -*- """ Application setup script To build package: python3 setup.py bdist_wheel sdist python2 setup.py bdist_wheel clean To run tests in an virtualenv: python setup.py test To run tests directly with verbose output: python -m pytest -vv """ # Python 2 forwards-compatibility from __future__ impor...
brbsix/pip-utils
pip_utils/dependents.py
command_dependents
python
def command_dependents(options): dependents = dependencies(options.package, options.recursive, options.info) if dependents: print(*dependents, sep='\n')
Command launched by CLI.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/dependents.py#L11-L16
[ "def dependencies(dist, recursive=False, info=False):\n \"\"\"Yield distribution's dependencies.\"\"\"\n\n def case_sorted(items):\n \"\"\"Return unique list sorted in case-insensitive order.\"\"\"\n return sorted(set(items), key=lambda i: i.lower())\n\n def requires(distribution):\n \...
# -*- coding: utf-8 -*- """List dependents of package""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # external imports from pip._vendor import pkg_resources def dependencies(dist, recursive=False, info=False): """Yield distribution's dependencies.""" def case_...
brbsix/pip-utils
pip_utils/dependents.py
dependencies
python
def dependencies(dist, recursive=False, info=False): def case_sorted(items): """Return unique list sorted in case-insensitive order.""" return sorted(set(items), key=lambda i: i.lower()) def requires(distribution): """Return the requirements for a distribution.""" if recursive:...
Yield distribution's dependencies.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/dependents.py#L19-L38
[ "def case_sorted(items):\n \"\"\"Return unique list sorted in case-insensitive order.\"\"\"\n return sorted(set(items), key=lambda i: i.lower())\n", "def requires(distribution):\n \"\"\"Return the requirements for a distribution.\"\"\"\n if recursive:\n req = set(pkg_resources.require(distribut...
# -*- coding: utf-8 -*- """List dependents of package""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # external imports from pip._vendor import pkg_resources def command_dependents(options): """Command launched by CLI.""" dependents = dependencies(options.package...
brbsix/pip-utils
pip_utils/outdated.py
ListCommand._build_package_finder
python
def _build_package_finder(options, index_urls, session): return PackageFinder( find_links=options.get('find_links'), index_urls=index_urls, allow_all_prereleases=options.get('pre'), trusted_hosts=options.get('trusted_hosts'), session=session, )
Create a package finder appropriate to this list command.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/outdated.py#L76-L86
null
class ListCommand(object): """ Modified version of pip's list command. Sourced from: pip.commands.list.ListCommand """ installed_distributions = [] options = { 'help': None, 'local': True, 'no_index': False, 'allow_all_insecure': False, 'proxy': '', ...
brbsix/pip-utils
pip_utils/outdated.py
ListCommand.can_be_updated
python
def can_be_updated(cls, dist, latest_version): scheme = get_scheme('default') name = dist.project_name dependants = cls.get_dependants(name) for dependant in dependants: requires = dependant.requires() for requirement in cls.get_requirement(name, requires): ...
Determine whether package can be updated or not.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/outdated.py#L126-L143
null
class ListCommand(object): """ Modified version of pip's list command. Sourced from: pip.commands.list.ListCommand """ installed_distributions = [] options = { 'help': None, 'local': True, 'no_index': False, 'allow_all_insecure': False, 'proxy': '', ...
brbsix/pip-utils
pip_utils/outdated.py
ListCommand.get_dependants
python
def get_dependants(cls, dist): for package in cls.installed_distributions: for requirement_package in package.requires(): requirement_name = requirement_package.project_name # perform case-insensitive matching if requirement_name.lower() == dist.lower(...
Yield dependant user packages for a given package name.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/outdated.py#L176-L183
null
class ListCommand(object): """ Modified version of pip's list command. Sourced from: pip.commands.list.ListCommand """ installed_distributions = [] options = { 'help': None, 'local': True, 'no_index': False, 'allow_all_insecure': False, 'proxy': '', ...
brbsix/pip-utils
pip_utils/outdated.py
ListCommand.get_requirement
python
def get_requirement(name, requires): for require in requires: if name.lower() == require.project_name.lower() and require.specs: safe_name = require.project_name.replace('-', '_') yield '%s (%s)' % (safe_name, require.specifier)
Yield matching requirement strings. The strings are presented in the format demanded by pip._vendor.distlib.util.parse_requirement. Hopefully I'll be able to figure out a better way to handle this in the future. Perhaps figure out how pip does it's version satisfaction tests and...
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/outdated.py#L186-L204
null
class ListCommand(object): """ Modified version of pip's list command. Sourced from: pip.commands.list.ListCommand """ installed_distributions = [] options = { 'help': None, 'local': True, 'no_index': False, 'allow_all_insecure': False, 'proxy': '', ...
brbsix/pip-utils
pip_utils/outdated.py
ListCommand.output_package
python
def output_package(dist): if dist_is_editable(dist): return '%s (%s, %s)' % ( dist.project_name, dist.version, dist.location, ) return '%s (%s)' % (dist.project_name, dist.version)
Return string displaying package information.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/outdated.py#L207-L215
null
class ListCommand(object): """ Modified version of pip's list command. Sourced from: pip.commands.list.ListCommand """ installed_distributions = [] options = { 'help': None, 'local': True, 'no_index': False, 'allow_all_insecure': False, 'proxy': '', ...
brbsix/pip-utils
pip_utils/outdated.py
ListCommand.run_outdated
python
def run_outdated(cls, options): latest_versions = sorted( cls.find_packages_latest_versions(cls.options), key=lambda p: p[0].project_name.lower()) for dist, latest_version, typ in latest_versions: if latest_version > dist.parsed_version: if options.al...
Print outdated user packages.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/outdated.py#L218-L245
[ "def can_be_updated(cls, dist, latest_version):\n \"\"\"Determine whether package can be updated or not.\"\"\"\n scheme = get_scheme('default')\n name = dist.project_name\n dependants = cls.get_dependants(name)\n for dependant in dependants:\n requires = dependant.requires()\n for requi...
class ListCommand(object): """ Modified version of pip's list command. Sourced from: pip.commands.list.ListCommand """ installed_distributions = [] options = { 'help': None, 'local': True, 'no_index': False, 'allow_all_insecure': False, 'proxy': '', ...
brbsix/pip-utils
pip_utils/parents.py
get_parents
python
def get_parents(): distributions = get_installed_distributions(user_only=ENABLE_USER_SITE) remaining = {d.project_name.lower() for d in distributions} requirements = {r.project_name.lower() for d in distributions for r in d.requires()} return get_realnames(remaining - requirements)
Return sorted list of names of packages without dependants.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/parents.py#L28-L35
[ "def get_realnames(packages):\n \"\"\"\n Return list of unique case-correct package names.\n\n Packages are listed in a case-insensitive sorted order.\n \"\"\"\n return sorted({get_distribution(p).project_name for p in packages},\n key=lambda n: n.lower())\n" ]
# -*- coding: utf-8 -*- """List packages lacking dependants""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # standard imports from site import ENABLE_USER_SITE # external imports try: from pip._internal.utils.misc import get_installed_distributions except ImportError:...
brbsix/pip-utils
pip_utils/parents.py
get_realnames
python
def get_realnames(packages): return sorted({get_distribution(p).project_name for p in packages}, key=lambda n: n.lower())
Return list of unique case-correct package names. Packages are listed in a case-insensitive sorted order.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/parents.py#L38-L45
null
# -*- coding: utf-8 -*- """List packages lacking dependants""" # Python 2 forwards-compatibility from __future__ import absolute_import, print_function # standard imports from site import ENABLE_USER_SITE # external imports try: from pip._internal.utils.misc import get_installed_distributions except ImportError:...
brbsix/pip-utils
pip_utils/cli.py
_parser
python
def _parser(): launcher = 'pip%s-utils' % sys.version_info.major parser = argparse.ArgumentParser( description='%s.' % __description__, epilog='See `%s COMMAND --help` for help ' 'on a specific subcommand.' % launcher, prog=launcher) parser.add_argument( '--ve...
Parse command-line options.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/cli.py#L31-L146
null
# -*- coding: utf-8 -*- """Command-line application""" # Python 2 forwards-compatibility from __future__ import absolute_import # standard imports import argparse import sys # external imports from pip._vendor.pkg_resources import DistributionNotFound, get_distribution # application imports from . import __descript...
brbsix/pip-utils
pip_utils/cli.py
main
python
def main(args=None): parser = _parser() # Python 2 will error 'too few arguments' if no subcommand is supplied. # No such error occurs in Python 3, which makes it feasible to check # whether a subcommand was provided (displaying a help message if not). # argparse internals vary significantly over t...
Start application.
train
https://github.com/brbsix/pip-utils/blob/bdd2a0a17cf36a1c88aa9e68002e9ed04a27bad8/pip_utils/cli.py#L149-L167
[ "def _parser():\n \"\"\"Parse command-line options.\"\"\"\n launcher = 'pip%s-utils' % sys.version_info.major\n\n parser = argparse.ArgumentParser(\n description='%s.' % __description__,\n epilog='See `%s COMMAND --help` for help '\n 'on a specific subcommand.' % launcher,\n ...
# -*- coding: utf-8 -*- """Command-line application""" # Python 2 forwards-compatibility from __future__ import absolute_import # standard imports import argparse import sys # external imports from pip._vendor.pkg_resources import DistributionNotFound, get_distribution # application imports from . import __descript...
etalab/cada
setup.py
pip
python
def pip(filename): '''Parse pip requirement file and transform it to setuptools requirements''' requirements = [] for line in open(os.path.join('requirements', filename)).readlines(): match = RE_REQUIREMENT.match(line) if match: requirements.extend(pip(match.group('filename'))) ...
Parse pip requirement file and transform it to setuptools requirements
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/setup.py#L38-L47
[ "def pip(filename):\n '''Parse pip requirement file and transform it to setuptools requirements'''\n requirements = []\n for line in open(os.path.join('requirements', filename)).readlines():\n match = RE_REQUIREMENT.match(line)\n if match:\n requirements.extend(pip(match.group('fil...
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import re from setuptools import setup, find_packages RE_REQUIREMENT = re.compile(r'^\s*-r\s*(?P<filename>.*)$') RE_BADGE = re.compile(r'^\[\!\[(?P<text>[^\]]+)\]\[(?P<badge>[^\]]+)\]\]\[(?P<target>[^\]]+)\]$', re.M) BADGES_TO_KEEP = ['gitter-badge',...
etalab/cada
cada/commands.py
echo
python
def echo(msg, *args, **kwargs): '''Wraps click.echo, handles formatting and check encoding''' file = kwargs.pop('file', None) nl = kwargs.pop('nl', True) err = kwargs.pop('err', False) color = kwargs.pop('color', None) msg = safe_unicode(msg).format(*args, **kwargs) click.echo(msg, file=file...
Wraps click.echo, handles formatting and check encoding
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L60-L67
[ "def safe_unicode(string):\n '''Safely transform any object into utf8 encoded bytes'''\n if not isinstance(string, basestring):\n string = unicode(string)\n if isinstance(string, unicode):\n string = string.encode('utf8')\n return string\n" ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
header
python
def header(msg, *args, **kwargs): '''Display an header''' msg = ' '.join((yellow(HEADER), white(msg), yellow(HEADER))) echo(msg, *args, **kwargs)
Display an header
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L70-L73
[ "def echo(msg, *args, **kwargs):\n '''Wraps click.echo, handles formatting and check encoding'''\n file = kwargs.pop('file', None)\n nl = kwargs.pop('nl', True)\n err = kwargs.pop('err', False)\n color = kwargs.pop('color', None)\n msg = safe_unicode(msg).format(*args, **kwargs)\n click.echo(ms...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
success
python
def success(msg, *args, **kwargs): '''Display a success message''' echo('{0} {1}'.format(green(OK), white(msg)), *args, **kwargs)
Display a success message
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L76-L78
[ "def echo(msg, *args, **kwargs):\n '''Wraps click.echo, handles formatting and check encoding'''\n file = kwargs.pop('file', None)\n nl = kwargs.pop('nl', True)\n err = kwargs.pop('err', False)\n color = kwargs.pop('color', None)\n msg = safe_unicode(msg).format(*args, **kwargs)\n click.echo(ms...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
warning
python
def warning(msg, *args, **kwargs): '''Display a warning message''' msg = '{0} {1}'.format(yellow(WARNING), msg) echo(msg, *args, **kwargs)
Display a warning message
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L81-L84
[ "def echo(msg, *args, **kwargs):\n '''Wraps click.echo, handles formatting and check encoding'''\n file = kwargs.pop('file', None)\n nl = kwargs.pop('nl', True)\n err = kwargs.pop('err', False)\n color = kwargs.pop('color', None)\n msg = safe_unicode(msg).format(*args, **kwargs)\n click.echo(ms...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
error
python
def error(msg, details=None, *args, **kwargs): '''Display an error message with optionnal details''' msg = '{0} {1}'.format(red(KO), white(msg)) if details: msg = '\n'.join((msg, safe_unicode(details))) echo(format_multiline(msg), *args, **kwargs)
Display an error message with optionnal details
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L87-L92
[ "def echo(msg, *args, **kwargs):\n '''Wraps click.echo, handles formatting and check encoding'''\n file = kwargs.pop('file', None)\n nl = kwargs.pop('nl', True)\n err = kwargs.pop('err', False)\n color = kwargs.pop('color', None)\n msg = safe_unicode(msg).format(*args, **kwargs)\n click.echo(ms...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
exit_with_error
python
def exit_with_error(msg='Aborted', details=None, code=-1, *args, **kwargs): '''Exit with error''' error(msg, details=details, *args, **kwargs) sys.exit(code)
Exit with error
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L95-L98
[ "def error(msg, details=None, *args, **kwargs):\n '''Display an error message with optionnal details'''\n msg = '{0} {1}'.format(red(KO), white(msg))\n if details:\n msg = '\\n'.join((msg, safe_unicode(details)))\n echo(format_multiline(msg), *args, **kwargs)\n" ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
load
python
def load(patterns, full_reindex): ''' Load one or more CADA CSV files matching patterns ''' header('Loading CSV files') for pattern in patterns: for filename in iglob(pattern): echo('Loading {}'.format(white(filename))) with open(filename) as f: reader...
Load one or more CADA CSV files matching patterns
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L147-L175
[ "def index(advice):\n '''Index/Reindex a CADA advice'''\n topics = []\n for topic in advice.topics:\n topics.append(topic)\n parts = topic.split('/')\n if len(parts) > 1:\n topics.append(parts[0])\n\n try:\n es.index(index=es.index_name, doc_type=DOCTYPE, id=advice...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
reindex
python
def reindex(): '''Reindex all advices''' header('Reindexing all advices') echo('Deleting index {0}', white(es.index_name)) if es.indices.exists(es.index_name): es.indices.delete(index=es.index_name) es.initialize() idx = 0 for idx, advice in enumerate(Advice.objects, 1): ind...
Reindex all advices
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L179-L193
[ "def index(advice):\n '''Index/Reindex a CADA advice'''\n topics = []\n for topic in advice.topics:\n topics.append(topic)\n parts = topic.split('/')\n if len(parts) > 1:\n topics.append(parts[0])\n\n try:\n es.index(index=es.index_name, doc_type=DOCTYPE, id=advice...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
static
python
def static(path, no_input): '''Compile and collect static files into path''' log = logging.getLogger('webassets') log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) cmdenv = CommandLineEnvironment(assets, log) cmdenv.build() if exists(path): warning('{0} directory ...
Compile and collect static files into path
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L199-L217
[ "def warning(msg, *args, **kwargs):\n '''Display a warning message'''\n msg = '{0} {1}'.format(yellow(WARNING), msg)\n echo(msg, *args, **kwargs)\n", "def echo(msg, *args, **kwargs):\n '''Wraps click.echo, handles formatting and check encoding'''\n file = kwargs.pop('file', None)\n nl = kwargs.p...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
anon
python
def anon(): '''Check for candidates to anonymization''' header(anon.__doc__) filename = 'urls_to_check.csv' candidates = Advice.objects(__raw__={ '$or': [ {'subject': { '$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}', '$options': 'imx...
Check for candidates to anonymization
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L221-L249
[ "def header(msg, *args, **kwargs):\n '''Display an header'''\n msg = ' '.join((yellow(HEADER), white(msg), yellow(HEADER)))\n echo(msg, *args, **kwargs)\n", "def echo(msg, *args, **kwargs):\n '''Wraps click.echo, handles formatting and check encoding'''\n file = kwargs.pop('file', None)\n nl = k...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/commands.py
fix
python
def fix(csvfile): '''Apply a fix (ie. remove plain names)''' header('Apply fixes from {}', csvfile.name) bads = [] reader = csv.reader(csvfile) reader.next() # Skip header for id, _, sources, dests in reader: advice = Advice.objects.get(id=id) sources = [s.strip() for s in sourc...
Apply a fix (ie. remove plain names)
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L254-L275
[ "def index(advice):\n '''Index/Reindex a CADA advice'''\n topics = []\n for topic in advice.topics:\n topics.append(topic)\n parts = topic.split('/')\n if len(parts) > 1:\n topics.append(parts[0])\n\n try:\n es.index(index=es.index_name, doc_type=DOCTYPE, id=advice...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import click import logging import pkg_resources import shutil import sys from glob import iglob from os.path import exists from webassets.script import CommandLineEnvironment from flask.cli import FlaskGroup, shell_command, run_command,...
etalab/cada
cada/search.py
build_sort
python
def build_sort(): '''Build sort query paramter from kwargs''' sorts = request.args.getlist('sort') sorts = [sorts] if isinstance(sorts, basestring) else sorts sorts = [s.split(' ') for s in sorts] return [{SORTS[s]: d} for s, d in sorts if s in SORTS]
Build sort query paramter from kwargs
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/search.py#L183-L188
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from datetime import datetime from elasticsearch import Elasticsearch from flask import current_app, request from cada.models import Advice log = logging.getLogger(__name__) MAPPING = { 'properties': { 'id': {'type': 'strin...
etalab/cada
cada/search.py
index
python
def index(advice): '''Index/Reindex a CADA advice''' topics = [] for topic in advice.topics: topics.append(topic) parts = topic.split('/') if len(parts) > 1: topics.append(parts[0]) try: es.index(index=es.index_name, doc_type=DOCTYPE, id=advice.id, body={ ...
Index/Reindex a CADA advice
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/search.py#L278-L301
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from datetime import datetime from elasticsearch import Elasticsearch from flask import current_app, request from cada.models import Advice log = logging.getLogger(__name__) MAPPING = { 'properties': { 'id': {'type': 'strin...
etalab/cada
cada/search.py
ElasticSearch.initialize
python
def initialize(self): '''Create or update indices and mappings''' if es.indices.exists(self.index_name): es.indices.put_mapping(index=self.index_name, doc_type=DOCTYPE, body=MAPPING) else: es.indices.create(self.index_name, { 'mappings': {'advice': MAPPING...
Create or update indices and mappings
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/search.py#L130-L138
null
class ElasticSearch(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app): app.config.setdefault('ELASTICSEARCH_URL', 'localhost:9200') app.extensions['elasticsearch'] = Elasticsearch([app.config['ELASTICSEARCH_URL']]) def...
etalab/cada
cada/csv.py
reader
python
def reader(f): '''CSV Reader factory for CADA format''' return unicodecsv.reader(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
CSV Reader factory for CADA format
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L30-L32
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import unicodecsv from flask import url_for from datetime import datetime from cada.models import Advice HEADER = [ 'Numéro de dossier', 'Administration', 'Type', 'Année', 'Séance', 'Objet', 'Thème et sous t...
etalab/cada
cada/csv.py
writer
python
def writer(f): '''CSV writer factory for CADA format''' return unicodecsv.writer(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
CSV writer factory for CADA format
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L35-L37
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import unicodecsv from flask import url_for from datetime import datetime from cada.models import Advice HEADER = [ 'Numéro de dossier', 'Administration', 'Type', 'Année', 'Séance', 'Objet', 'Thème et sous t...
etalab/cada
cada/csv.py
from_row
python
def from_row(row): '''Create an advice from a CSV row''' subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5] return Advice.objects.create( id=row[0], administration=cleanup(row[1]), type=row[2], session=datetime.strptime(row[4], '%d/%m/%Y'), subject=clean...
Create an advice from a CSV row
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L60-L74
[ "def cleanup(text):\n '''Sanitize text field from HTML encoded caracters'''\n return text.replace('&quot;', '\"').replace('&amp;', '&')\n", "def _part(string):\n '''Transform a part string (I, II or III) into an integer'''\n if string == 'I':\n return 1\n elif string == 'II':\n return...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import unicodecsv from flask import url_for from datetime import datetime from cada.models import Advice HEADER = [ 'Numéro de dossier', 'Administration', 'Type', 'Année', 'Séance', 'Objet', 'Thème et sous t...
etalab/cada
cada/csv.py
to_row
python
def to_row(advice): '''Serialize an advice into a CSV row''' return [ advice.id, advice.administration, advice.type, advice.session.year, advice.session.strftime('%d/%m/%Y'), advice.subject, ', '.join(advice.topics), ', '.join(advice.tags), ...
Serialize an advice into a CSV row
train
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/csv.py#L77-L91
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import unicodecsv from flask import url_for from datetime import datetime from cada.models import Advice HEADER = [ 'Numéro de dossier', 'Administration', 'Type', 'Année', 'Séance', 'Objet', 'Thème et sous t...
gr33ndata/dysl
dysl/dyslib/lm.py
LM.display
python
def display(self): ''' Displays statistics about our LM ''' voc_list = [] doc_ids = self.term_count_n.keys() doc_ids.sort() for doc_id in doc_ids: ngrams = len(self.term_count_n[doc_id]['ngrams']) print 'n-Grams (doc %s): %d' % (str(doc_id)...
Displays statistics about our LM
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/dyslib/lm.py#L133-L152
null
class LM: def __init__(self, n=3, lpad='', rpad='', smoothing='Laplace', laplace_gama=1, corpus_mix=0, corpus_mode='Miller', verbose=False): ''' Initialize our LM n: Order of ngram LM, e.g. for bigram LM, n=2 lpad, rpad: Left and ...
gr33ndata/dysl
dysl/dyslib/lm.py
LM.get_ngram_counts
python
def get_ngram_counts(self): ''' Returns a list of n-gram counts Array of classes counts and last item is for corpus ''' ngram_counts = { 'classes': [], 'corpus': 0 } doc_ids = self.term_count_n.keys() doc_ids.sort() for doc_id i...
Returns a list of n-gram counts Array of classes counts and last item is for corpus
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/dyslib/lm.py#L156-L172
null
class LM: def __init__(self, n=3, lpad='', rpad='', smoothing='Laplace', laplace_gama=1, corpus_mix=0, corpus_mode='Miller', verbose=False): ''' Initialize our LM n: Order of ngram LM, e.g. for bigram LM, n=2 lpad, rpad: Left and ...
gr33ndata/dysl
dysl/dyslib/lm.py
LM.to_ngrams
python
def to_ngrams(self, terms): ''' Converts terms to all possibe ngrams terms: list of terms ''' if len(terms) <= self.n: return terms if self.n == 1: n_grams = [[term] for term in terms] else: n_grams = [] for i in range(...
Converts terms to all possibe ngrams terms: list of terms
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/dyslib/lm.py#L204-L216
null
class LM: def __init__(self, n=3, lpad='', rpad='', smoothing='Laplace', laplace_gama=1, corpus_mix=0, corpus_mode='Miller', verbose=False): ''' Initialize our LM n: Order of ngram LM, e.g. for bigram LM, n=2 lpad, rpad: Left and ...
gr33ndata/dysl
dysl/dyslib/lm.py
LM.lr_padding
python
def lr_padding(self, terms): ''' Pad doc from the left and right before adding, depending on what's in self.lpad and self.rpad If any of them is '', then don't pad there. ''' lpad = rpad = [] if self.lpad: lpad = [self.lpad] * (self.n - 1) if...
Pad doc from the left and right before adding, depending on what's in self.lpad and self.rpad If any of them is '', then don't pad there.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/dyslib/lm.py#L218-L229
null
class LM: def __init__(self, n=3, lpad='', rpad='', smoothing='Laplace', laplace_gama=1, corpus_mix=0, corpus_mode='Miller', verbose=False): ''' Initialize our LM n: Order of ngram LM, e.g. for bigram LM, n=2 lpad, rpad: Left and ...
gr33ndata/dysl
dysl/dyslib/lm.py
LM.add_doc
python
def add_doc(self, doc_id ='', doc_terms=[], doc_length=-1): ''' Add new document to our Language Model (training phase) doc_id is used here, so we build seperate LF for each doc_id I.e. if you call it more than once with same doc_id, then all terms given via doc_terms will contri...
Add new document to our Language Model (training phase) doc_id is used here, so we build seperate LF for each doc_id I.e. if you call it more than once with same doc_id, then all terms given via doc_terms will contribute to same LM doc_terms: list of words in document to be added ...
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/dyslib/lm.py#L290-L308
[ "def to_ngrams(self, terms):\n ''' Converts terms to all possibe ngrams \n terms: list of terms\n '''\n if len(terms) <= self.n:\n return terms\n if self.n == 1:\n n_grams = [[term] for term in terms]\n else:\n n_grams = []\n for i in range(0,len(terms)-self.n+1):\n...
class LM: def __init__(self, n=3, lpad='', rpad='', smoothing='Laplace', laplace_gama=1, corpus_mix=0, corpus_mode='Miller', verbose=False): ''' Initialize our LM n: Order of ngram LM, e.g. for bigram LM, n=2 lpad, rpad: Left and ...
gr33ndata/dysl
dysl/dyslib/lm.py
LM.calculate
python
def calculate(self, doc_terms=[], actual_id='', doc_length=-1): ''' Given a set of terms, doc_terms We find the doc in training data (calc_id), whose LM is more likely to produce those terms Then return the data structure calculated back doc_length is passed to pr_ngram()...
Given a set of terms, doc_terms We find the doc in training data (calc_id), whose LM is more likely to produce those terms Then return the data structure calculated back doc_length is passed to pr_ngram() and pr_doc() it is up to them to use it or not. normally, i...
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/dyslib/lm.py#L413-L466
[ "def per_cic(self, calculated_id='', actual_id='', seen_unseen=None):\n calculated_id = str(calculated_id).strip()\n actual_id =str(actual_id).strip()\n unseen_ratio_str = self._seen_unseel_label(*seen_unseen)\n if not unseen_ratio_str in self.cic_counts:\n self.cic_counts[unseen_ratio_str] = [0,...
class LM: def __init__(self, n=3, lpad='', rpad='', smoothing='Laplace', laplace_gama=1, corpus_mix=0, corpus_mode='Miller', verbose=False): ''' Initialize our LM n: Order of ngram LM, e.g. for bigram LM, n=2 lpad, rpad: Left and ...
gr33ndata/dysl
dysl/social.py
SocialLM.tokenize
python
def tokenize(cls, text, mode='c'): if mode == 'c': return [ch for ch in text] else: return [w for w in text.split()]
Converts text into tokens :param text: string to be tokenized :param mode: split into chars (c) or words (w)
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/social.py#L15-L24
null
class SocialLM(LM): """ Social Media Flavoured Language Model """ @classmethod def karbasa(self, result): """ Finding if class probabilities are close to eachother Ratio of the distance between 1st and 2nd class, to the distance between 1st and last class. ...
gr33ndata/dysl
dysl/social.py
SocialLM.karbasa
python
def karbasa(self, result): probs = result['all_probs'] probs.sort() return float(probs[1] - probs[0]) / float(probs[-1] - probs[0])
Finding if class probabilities are close to eachother Ratio of the distance between 1st and 2nd class, to the distance between 1st and last class. :param result: The dict returned by LM.calculate()
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/social.py#L26-L35
null
class SocialLM(LM): """ Social Media Flavoured Language Model """ @classmethod def tokenize(cls, text, mode='c'): """ Converts text into tokens :param text: string to be tokenized :param mode: split into chars (c) or words (w) """ if mode == 'c': ...
gr33ndata/dysl
dysl/social.py
SocialLM.classify
python
def classify(self, text=u''): result = self.calculate(doc_terms=self.tokenize(text)) #return (result['calc_id'], result) return (result['calc_id'], self.karbasa(result))
Predicts the Language of a given text. :param text: Unicode text to be classified.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/social.py#L37-L44
null
class SocialLM(LM): """ Social Media Flavoured Language Model """ @classmethod def tokenize(cls, text, mode='c'): """ Converts text into tokens :param text: string to be tokenized :param mode: split into chars (c) or words (w) """ if mode == 'c': ...
gr33ndata/dysl
dysl/social.py
SocialLM.is_mention_line
python
def is_mention_line(cls, word): if word.startswith('@'): return True elif word.startswith('http://'): return True elif word.startswith('https://'): return True else: return False
Detects links and mentions :param word: Token to be evaluated
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/social.py#L47-L59
null
class SocialLM(LM): """ Social Media Flavoured Language Model """ @classmethod def tokenize(cls, text, mode='c'): """ Converts text into tokens :param text: string to be tokenized :param mode: split into chars (c) or words (w) """ if mode == 'c': ...
gr33ndata/dysl
dysl/social.py
SocialLM.strip_mentions_links
python
def strip_mentions_links(self, text): #print 'Before:', text new_text = [word for word in text.split() if not self.is_mention_line(word)] #print 'After:', u' '.join(new_text) return u' '.join(new_text)
Strips Mentions and Links :param text: Text to be stripped from.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/social.py#L61-L69
null
class SocialLM(LM): """ Social Media Flavoured Language Model """ @classmethod def tokenize(cls, text, mode='c'): """ Converts text into tokens :param text: string to be tokenized :param mode: split into chars (c) or words (w) """ if mode == 'c': ...
gr33ndata/dysl
dysl/social.py
SocialLM.normalize
python
def normalize(self, text): #print 'Normalize...\n' text = text.lower() text = unicodedata.normalize('NFC', text) text = self.strip_mentions_links(text) return text
Normalizes text. Converts to lowercase, Unicode NFC normalization and removes mentions and links :param text: Text to be normalized.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/social.py#L71-L83
null
class SocialLM(LM): """ Social Media Flavoured Language Model """ @classmethod def tokenize(cls, text, mode='c'): """ Converts text into tokens :param text: string to be tokenized :param mode: split into chars (c) or words (w) """ if mode == 'c': ...
gr33ndata/dysl
dysl/utils.py
decode_input
python
def decode_input(text_in): if type(text_in) == list: text_out = u' '.join([t.decode('utf-8') for t in text_in]) else: text_out = text_in.decode('utf-8') return text_out
Decodes `text_in` If text_in is is a string, then decode it as utf-8 string. If text_in is is a list of strings, then decode each string of it, then combine them into one outpust string.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/utils.py#L1-L14
null
def decode_input(text_in): """ Decodes `text_in` If text_in is is a string, then decode it as utf-8 string. If text_in is is a list of strings, then decode each string of it, then combine them into one outpust string. """ if type(text_in) == list: text_ou...
gr33ndata/dysl
dysl/langid.py
LangID._readfile
python
def _readfile(cls, filename): f = codecs.open(filename, encoding='utf-8') filedata = f.read() f.close() tokenz = LM.tokenize(filedata, mode='c') #print tokenz return tokenz
Reads a file a utf-8 file, and retuns character tokens. :param filename: Name of file to be read.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L40-L51
null
class LangID: """ Language Identification Class """ def __init__(self, unk=False): # Shall we mark some text as unk, # if top languages are too close? self.unk = unk self.min_karbasa = 0.08 # LM Parameters ngram = 3 lrpad = u' ' verbose = Fa...
gr33ndata/dysl
dysl/langid.py
LangID.train
python
def train(self, root=''): self.trainer = Train(root=root) corpus = self.trainer.get_corpus() # Show loaded Languages #print 'Lang Set: ' + ' '.join(train.get_lang_set()) for item in corpus: self.lm.add_doc(doc_id=item[0], doc_terms=self._readfile(item[1])) ...
Trains our Language Model. :param root: Path to training data.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L53-L69
[ "def _readfile(cls, filename):\n \"\"\" Reads a file a utf-8 file,\n and retuns character tokens.\n\n :param filename: Name of file to be read.\n \"\"\"\n f = codecs.open(filename, encoding='utf-8')\n filedata = f.read()\n f.close()\n tokenz = LM.tokenize(filedata, mode='c')\n #pr...
class LangID: """ Language Identification Class """ def __init__(self, unk=False): # Shall we mark some text as unk, # if top languages are too close? self.unk = unk self.min_karbasa = 0.08 # LM Parameters ngram = 3 lrpad = u' ' verbose = Fa...
gr33ndata/dysl
dysl/langid.py
LangID.is_training_modified
python
def is_training_modified(self): last_modified = self.trainer.get_last_modified() if last_modified > self.training_timestamp: return True else: return False
Returns `True` if training data was modified since last training. Returns `False` otherwise, or if using builtin training data.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L71-L82
null
class LangID: """ Language Identification Class """ def __init__(self, unk=False): # Shall we mark some text as unk, # if top languages are too close? self.unk = unk self.min_karbasa = 0.08 # LM Parameters ngram = 3 lrpad = u' ' verbose = Fa...
gr33ndata/dysl
dysl/langid.py
LangID.add_training_sample
python
def add_training_sample(self, text=u'', lang=''): self.trainer.add(text=text, lang=lang)
Initial step for adding new sample to training data. You need to call `save_training_samples()` afterwards. :param text: Sample text to be added. :param lang: Language label for the input text.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L90-L97
null
class LangID: """ Language Identification Class """ def __init__(self, unk=False): # Shall we mark some text as unk, # if top languages are too close? self.unk = unk self.min_karbasa = 0.08 # LM Parameters ngram = 3 lrpad = u' ' verbose = Fa...
gr33ndata/dysl
dysl/langid.py
LangID.save_training_samples
python
def save_training_samples(self, domain='', filename=''): self.trainer.save(domain=domain, filename=filename)
Saves data previously added via add_training_sample(). Data saved in folder specified by Train.get_corpus_path(). :param domain: Name for domain folder. If not set, current timestamp will be used. :param filename: Name for file to save data in. ...
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L99-L110
null
class LangID: """ Language Identification Class """ def __init__(self, unk=False): # Shall we mark some text as unk, # if top languages are too close? self.unk = unk self.min_karbasa = 0.08 # LM Parameters ngram = 3 lrpad = u' ' verbose = Fa...
gr33ndata/dysl
dysl/langid.py
LangID.classify
python
def classify(self, text=u''): text = self.lm.normalize(text) tokenz = LM.tokenize(text, mode='c') result = self.lm.calculate(doc_terms=tokenz) #print 'Karbasa:', self.karbasa(result) if self.unk and self.lm.karbasa(result) < self.min_karbasa: lang = 'unk' els...
Predicts the Language of a given text. :param text: Unicode text to be classified.
train
https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/langid.py#L117-L131
null
class LangID: """ Language Identification Class """ def __init__(self, unk=False): # Shall we mark some text as unk, # if top languages are too close? self.unk = unk self.min_karbasa = 0.08 # LM Parameters ngram = 3 lrpad = u' ' verbose = Fa...
hobson/pug-ann
pug/ann/data/weather.py
hourly
python
def hourly(location='Fresno, CA', days=1, start=None, end=None, years=1, use_cache=True, verbosity=1): airport_code = airport(location, default=location) if isinstance(days, int): start = start or None end = end or datetime.datetime.today().date() days = pd.date_range(start=start, end=e...
Get detailed (hourly) weather data for the requested days and location The Weather Underground URL for Fresno, CA on 1/1/2011 is: http://www.wunderground.com/history/airport/KFAT/2011/1/1/DailyHistory.html?MR=1&format=1 This will fail periodically on Travis, b/c wunderground says "No daily or hourly histo...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/data/weather.py#L24-L107
[ "def airport(location, default=None):\n return airport.locations.get(location, default)\n" ]
import os import urllib # import re import datetime import json import warnings import pandas as pd from pug.nlp import util, env np = pd.np DATA_PATH = os.path.dirname(os.path.realpath(__file__)) CACHE_PATH = os.path.join(DATA_PATH, 'cache') def airport(location, default=None): return airport.locations.get(...
hobson/pug-ann
pug/ann/data/weather.py
api
python
def api(feature='conditions', city='Portland', state='OR', key=None): features = ('alerts astronomy conditions currenthurricane forecast forecast10day geolookup history hourly hourly10day ' + 'planner rawtide satellite tide webcams yesterday').split(' ') feature = util.fuzzy_get(features, featur...
Use the wunderground API to get current conditions instead of scraping Please be kind and use your own key (they're FREE!): http://www.wunderground.com/weather/api/d/login.html References: http://www.wunderground.com/weather/api/d/terms.html Examples: >>> api('hurric', 'Boise', 'ID') ...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/data/weather.py#L110-L142
null
import os import urllib # import re import datetime import json import warnings import pandas as pd from pug.nlp import util, env np = pd.np DATA_PATH = os.path.dirname(os.path.realpath(__file__)) CACHE_PATH = os.path.join(DATA_PATH, 'cache') def airport(location, default=None): return airport.locations.get(...
hobson/pug-ann
pug/ann/data/weather.py
daily
python
def daily(location='Fresno, CA', years=1, use_cache=True, verbosity=1): this_year = datetime.date.today().year if isinstance(years, (int, float)): # current (incomplete) year doesn't count in total number of years # so 0 would return this calendar year's weather data years = np.arange(0,...
Retrieve weather for the indicated airport code or 'City, ST' string. >>> df = daily('Camas, WA', verbosity=-1) >>> 365 <= len(df) <= 365 * 2 + 1 True Sacramento data has gaps (airport KMCC): 8/21/2013 is missing from 2013. Whole months are missing from 2014. >>> df = daily('Sacram...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/data/weather.py#L145-L238
[ "def airport(location, default=None):\n return airport.locations.get(location, default)\n" ]
import os import urllib # import re import datetime import json import warnings import pandas as pd from pug.nlp import util, env np = pd.np DATA_PATH = os.path.dirname(os.path.realpath(__file__)) CACHE_PATH = os.path.join(DATA_PATH, 'cache') def airport(location, default=None): return airport.locations.get(...
hobson/pug-ann
pug/ann/util.py
build_ann
python
def build_ann(N_input=None, N_hidden=2, N_output=1, hidden_layer_type='Linear', verbosity=1): N_input = N_input or 1 N_output = N_output or 1 N_hidden = N_hidden or tuple() if isinstance(N_hidden, (int, float, basestring)): N_hidden = (int(N_hidden),) hidden_layer_type = hidden_layer_type o...
Build a neural net with the indicated input, hidden, and outout dimensions Arguments: params (dict or PyBrainParams namedtuple): default: {'N_hidden': 6} (this is the only parameter that affects the NN build) Returns: FeedForwardNetwork with N_input + N_hidden + N_output nodes in...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L62-L115
[ "def normalize_layer_type(layer_type):\n try:\n if layer_type in LAYER_TYPES:\n return layer_type\n except TypeError:\n pass\n try:\n return getattr(pb.structure, layer_type.strip())\n except AttributeError:\n try:\n return getattr(pb.structure, layer_ty...
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
prepend_dataset_with_weather
python
def prepend_dataset_with_weather(samples, location='Fresno, CA', weather_columns=None, use_cache=True, verbosity=0): if verbosity > 1: print('Prepending weather data for {} to dataset samples'.format(weather_columns)) if not weather_columns: return samples timestamps = pd.DatetimeIndex([s['t...
Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors samples[0..N]['target'] should have an index with the date timestamp If you use_cache for the curent year, you may not get the most recent data. Arguments: samples (list of dict): {'input': np.array(), 'ta...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L127-L166
[ "def daily(location='Fresno, CA', years=1, use_cache=True, verbosity=1):\n \"\"\"Retrieve weather for the indicated airport code or 'City, ST' string.\n\n >>> df = daily('Camas, WA', verbosity=-1)\n >>> 365 <= len(df) <= 365 * 2 + 1\n True\n\n Sacramento data has gaps (airport KMCC):\n 8/21/20...
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
dataset_from_dataframe
python
def dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=(-1,), normalize=False, verbosity=1): if isinstance(delays, int): if delays: delays = range(1, delays + 1) else: delays = [0] delays = np.abs(np.array([int(i) for i in delays])) inputs = [df.c...
Compose a pybrain.dataset from a pandas DataFrame Arguments: delays (list of int): sample delays to use for the input tapped delay line Positive and negative values are treated the same as sample counts into the past. default: [1, 2, 3], in z-transform notation: z^-1 + z^-2 + z^-3 input...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L169-L248
null
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
input_dataset_from_dataframe
python
def input_dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1): return dataset_from_dataframe(df=df, delays=delays, inputs=inputs, outputs=outputs, normalize=normalize, verbosity=verbosity)
Build a dataset with an empty output/target vector Identical to `dataset_from_dataframe`, except that default values for 2 arguments: outputs: None
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L348-L355
[ "def dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=(-1,), normalize=False, verbosity=1):\n \"\"\"Compose a pybrain.dataset from a pandas DataFrame\n\n Arguments:\n delays (list of int): sample delays to use for the input tapped delay line\n Positive and negative values ar...
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
inputs_from_dataframe
python
def inputs_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1): ds = input_dataset_from_dataframe(df=df, delays=delays, inputs=inputs, outputs=outputs, normalize=normalize, verbosity=verbosity) return ds['input']
Build a sequence of vectors suitable for "activation" by a neural net Identical to `dataset_from_dataframe`, except that only the input vectors are returned (not a full DataSet instance) and default values for 2 arguments are changed: outputs: None And only the input vectors are return
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L358-L369
[ "def input_dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1):\n \"\"\" Build a dataset with an empty output/target vector\n\n Identical to `dataset_from_dataframe`, except that default values for 2 arguments:\n outputs: None\n \"\"\"\n retu...
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
build_trainer
python
def build_trainer(nn, ds, verbosity=1): return pb.supervised.trainers.rprop.RPropMinusTrainer(nn, dataset=ds, batchlearning=True, verbose=bool(verbosity))
Configure neural net trainer from a pybrain dataset
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L372-L374
null
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
weight_matrices
python
def weight_matrices(nn): if isinstance(nn, ndarray): return nn try: return weight_matrices(nn.connections) except: pass try: return weight_matrices(nn.module) except: pass # Network objects are ParameterContainer's too, but won't reshape into a single ...
Extract list of weight matrices from a Network, Layer (module), Trainer, Connection or other pybrain object
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L377-L417
[ "def weight_matrices(nn):\n \"\"\" Extract list of weight matrices from a Network, Layer (module), Trainer, Connection or other pybrain object\"\"\"\n\n if isinstance(nn, ndarray):\n return nn\n\n try:\n return weight_matrices(nn.connections)\n except:\n pass\n\n try:\n re...
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
dataset_nan_locs
python
def dataset_nan_locs(ds): ans = [] for sampnum, sample in enumerate(ds): if pd.isnull(sample).any(): ans += [{ 'sample': sampnum, 'input': pd.isnull(sample[0]).nonzero()[0], 'output': pd.isnull(sample[1]).nonzero()[0], }] r...
from http://stackoverflow.com/a/14033137/623735 # gets the indices of the rows with nan values in a dataframe pd.isnull(df).any(1).nonzero()[0]
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L535-L549
null
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
table_nan_locs
python
def table_nan_locs(table): ans = [] for rownum, row in enumerate(table): try: if pd.isnull(row).any(): colnums = pd.isnull(row).nonzero()[0] ans += [(rownum, colnum) for colnum in colnums] except AttributeError: # table is really just a sequence of sc...
from http://stackoverflow.com/a/14033137/623735 # gets the indices of the rows with nan values in a dataframe pd.isnull(df).any(1).nonzero()[0]
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L552-L567
null
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
plot_network_results
python
def plot_network_results(network, ds=None, mean=0, std=1, title='', show=True, save=True): df = sim_network(network=network, ds=ds, mean=mean, std=std) df.plot() plt.xlabel('Date') plt.ylabel('Threshold (kW)') plt.title(title) if show: try: # ipython notebook overrides plt.s...
Identical to plot_trainer except `network` and `ds` must be provided separately
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L570-L592
[ "def sim_network(network, ds=None, index=None, mean=0, std=1):\n \"\"\"Simulate/activate a Network on a SupervisedDataSet and return DataFrame(columns=['Output','Target'])\n\n The DataSet's target and output values are denormalized before populating the dataframe columns:\n\n denormalized_output = norm...
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
trainer_results
python
def trainer_results(trainer, mean=0, std=1, title='', show=True, save=True): return plot_network_results(network=trainer.module, ds=trainer.ds, mean=mean, std=std, title=title, show=show, save=save)
Plot the performance of the Network and SupervisedDataSet in a pybrain Trainer DataSet target and output values are denormalized before plotting with: output * std + mean Which inverses the normalization (output - mean) / std Args: trainer (Trainer): a pybrain Trainer instance c...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L595-L619
[ "def plot_network_results(network, ds=None, mean=0, std=1, title='', show=True, save=True):\n \"\"\"Identical to plot_trainer except `network` and `ds` must be provided separately\"\"\"\n df = sim_network(network=network, ds=ds, mean=mean, std=std)\n df.plot()\n plt.xlabel('Date')\n plt.ylabel('Thres...
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
sim_trainer
python
def sim_trainer(trainer, mean=0, std=1): return sim_network(network=trainer.module, ds=trainer.ds, mean=mean, std=std)
Simulate a trainer by activating its DataSet and returning DataFrame(columns=['Output','Target'])
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L622-L625
[ "def sim_network(network, ds=None, index=None, mean=0, std=1):\n \"\"\"Simulate/activate a Network on a SupervisedDataSet and return DataFrame(columns=['Output','Target'])\n\n The DataSet's target and output values are denormalized before populating the dataframe columns:\n\n denormalized_output = norm...
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/util.py
sim_network
python
def sim_network(network, ds=None, index=None, mean=0, std=1): # just in case network is a trainer or has a Module-derived instance as one of it's attribute # isinstance(network.module, (networks.Network, modules.Module)) if hasattr(network, 'module') and hasattr(network.module, 'activate'): # may...
Simulate/activate a Network on a SupervisedDataSet and return DataFrame(columns=['Output','Target']) The DataSet's target and output values are denormalized before populating the dataframe columns: denormalized_output = normalized_output * std + mean Which inverses the normalization that produced the...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L628-L664
null
"""Maniuplate, analyze and plot `pybrain` `Network` and `DataSet` objects TODO: Incorporate into pybrain fork so pug doesn't have to depend on pybrain """ from __future__ import print_function import os import warnings import pandas as pd from scipy import ndarray, reshape # array, amin, amax, np = pd.np from m...
hobson/pug-ann
pug/ann/example.py
train_weather_predictor
python
def train_weather_predictor( location='Portland, OR', years=range(2013, 2016,), delays=(1, 2, 3), inputs=('Min Temperature', 'Max Temperature', 'Min Sea Level Pressure', u'Max Sea Level Pressure', 'WindDirDegrees',), outputs=(u'Max TemperatureF',), N_hidden=6, epo...
Train a neural nerual net to predict the weather for tomorrow based on past weather. Builds a linear single hidden layer neural net (multi-dimensional nonlinear regression). The dataset is a basic SupervisedDataSet rather than a SequentialDataSet, so the training set and the test set are sampled randomly. ...
train
https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/example.py#L28-L79
[ "def daily(location='Fresno, CA', years=1, use_cache=True, verbosity=1):\n \"\"\"Retrieve weather for the indicated airport code or 'City, ST' string.\n\n >>> df = daily('Camas, WA', verbosity=-1)\n >>> 365 <= len(df) <= 365 * 2 + 1\n True\n\n Sacramento data has gaps (airport KMCC):\n 8/21/20...
"""Example pybrain network training to predict the weather Installation: pip install pug-ann Examples: In the future DataSets should have an attribute `columns` or `df` to facilitate converting back to dataframes >>> trainer, df = train_weather_predictor('San Francisco, CA', epochs=2, inputs=['Max Tempe...